Class: SBOM Private

Inherits:
Object show all
Includes:
Utils::Output::Mixin
Defined in:
sbom.rb

Overview

This class is part of a private API. This class may only be used in the Homebrew/brew repository. Third parties should avoid using this class if possible, as it may be removed or changed without warning.

Rather than calling new directly, use one of the class methods like SBOM.create.

Defined Under Namespace

Classes: Source

Constant Summary collapse

FILENAME =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"sbom.spdx.json"
SCHEMA_FILE =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

T.let((HOMEBREW_LIBRARY_PATH/"data/schemas/sbom.json").freeze, Pathname)
SPDXHash =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

T.type_alias { T::Hash[String, Object] }
SPDXSymbolHash =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

T.type_alias { T::Hash[Symbol, Object] }

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils::Output::Mixin

#issue_reporting_message, #odebug, #odeprecated, #odie, #odisabled, #ofail, #oh1, #oh1_title, #ohai, #ohai_title, #onoe, #opoo, #opoo_once, #opoo_outside_github_actions, #opoo_without_github_actions_annotation, #pretty_cannot_install, #pretty_deprecated, #pretty_disabled, #pretty_duration, #pretty_incompatible, #pretty_install_status, #pretty_installed, #pretty_removed, #pretty_uninstalled, #pretty_unmarked, #pretty_upgradable, #pretty_warning

Class Method Details

.brew_purl(full_name, version) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



168
169
170
171
172
173
174
175
176
# File 'sbom.rb', line 168

def self.brew_purl(full_name, version)
  namespace, _, name = full_name.rpartition("/")
  Homebrew::Vulns::Purl.new(
    type:      "brew",
    namespace: namespace.presence,
    name:,
    version:   version&.to_s,
  ).to_s
end

.create(formula, tab) ⇒ T.attached_class

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Instantiates a SBOM for a new installation of a formula.

Parameters:

Returns:

  • (T.attached_class)


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'sbom.rb', line 35

def self.create(formula, tab)
  active_spec = formula.active_spec
  active_spec_sym = formula.active_spec_sym

  new(
    name:                 formula.name,
    spdxfile:             SBOM.spdxfile(formula),
    source_modified_time: tab.source_modified_time.to_i,
    compiler:             tab.compiler,
    stdlib:               tab.stdlib,
    runtime_dependencies: SBOM.runtime_deps_hash(T.cast(Array(tab.runtime_dependencies),
                                                        T::Array[T::Hash[String, Object]])),
    license:              SPDX.license_expression_to_string(formula.license),
    built_on:             DevelopmentTools.build_system_info,
    source:               Source.new(
      path:         formula.specified_path.to_s,
      tap_name:     formula.tap&.name,
      # We can only get `tap_git_head` if the tap is installed locally
      tap_git_head: (formula.tap!.git_head if formula.tap&.installed?),
      spec:         active_spec_sym,
      patches:      active_spec.patches,
      bottle:       formula.bottle_hash,
      version:      active_spec.version,
      url:          active_spec.url,
      checksum:     active_spec.checksum,
    ),
  )
end

.exist?(formula) ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:

  • (Boolean)


86
87
88
# File 'sbom.rb', line 86

def self.exist?(formula)
  spdxfile(formula).exist?
end

.github_packages_sbom_supplement_annotation(supplement, formula_full_name:, formula_name:, version:, tar_gz_sha256:, root_url:, license:, created_date:) ⇒ String?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'sbom.rb', line 102

def self.github_packages_sbom_supplement_annotation(supplement, formula_full_name:, formula_name:, version:,
                                                    tar_gz_sha256:, root_url:, license:, created_date:)
  require "github_packages"

  add_bottle_package_to_supplement(
    supplement,
    bottle_package(
      formula_full_name,
      formula_name,
      version,
      tar_gz_sha256,
      root_url:,
      license:,
      created_date:,
    ),
  )&.to_json
end

.runtime_deps_hash(deps) ⇒ Array<Hash{String => Object}>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'sbom.rb', line 70

def self.runtime_deps_hash(deps)
  deps.map do |dep|
    full_name = dep.fetch("full_name").to_s
    dep_formula = Formula[full_name]
    {
      "full_name"           => full_name,
      "pkg_version"         => dep.fetch("pkg_version"),
      "name"                => dep_formula.name,
      "license"             => SPDX.license_expression_to_string(dep_formula.license),
      "bottle"              => dep_formula.bottle_hash,
      "formula_pkg_version" => dep_formula.pkg_version.to_s,
    }
  end
end

.schema ⇒ Hash{String => T.anything}

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



204
205
206
# File 'sbom.rb', line 204

def self.schema
  @schema ||= T.let(JSON.parse(SCHEMA_FILE.read, freeze: true), T.nilable(T::Hash[String, Object]))
end

.spdx_id(id) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns an SPDX identifier, escaping punctuation and the dot escape delimiter.

Parameters:

Returns:



162
163
164
165
# File 'sbom.rb', line 162

def self.spdx_id(id)
  escaped_id = id.gsub(/[^a-zA-Z0-9-]/) { |character| ".#{character.unpack1("H*")}." }
  "SPDXRef-#{escaped_id}"
end

.spdxfile(formula) ⇒ Pathname

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



65
66
67
# File 'sbom.rb', line 65

def self.spdxfile(formula)
  formula.prefix/FILENAME
end

.update_pour_metadata(spdxfile, homebrew_version:, time:, supplement: nil) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'sbom.rb', line 186

def self.(spdxfile, homebrew_version:, time:, supplement: nil)
  return unless spdxfile.exist?

  spdx = JSON.parse(spdxfile.read)
  return unless spdx.is_a?(Hash)

  creation_info = spdx["creationInfo"]
  return unless creation_info.is_a?(Hash)

  creation_info["created"] = Time.at(time).utc.iso8601
  creation_info["creators"] = ["Tool: https://github.com/Homebrew/brew@#{homebrew_version}"]
  merge_spdx_supplement(spdx, supplement) if supplement
  spdxfile.atomic_write(JSON.pretty_generate(spdx))
rescue JSON::ParserError
  nil
end

Instance Method Details

#schema_validation_errors(data = nil, bottling: false) ⇒ Array<String>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • data (Hash{Symbol => T.anything}, nil) (defaults to: nil)
  • bottling (Boolean) (defaults to: false)

Returns:



209
210
211
212
213
214
215
216
217
218
219
# File 'sbom.rb', line 209

def schema_validation_errors(data = nil, bottling: false)
  unless Utils::Ruby.require? "json_schemer"
    error_message = "Need json_schemer to validate SBOM, run `brew install-bundler-gems --add-groups=bottle`!"
    odie error_message if ENV["HOMEBREW_ENFORCE_SBOM"]
    return []
  end

  schemer = JSONSchemer.schema(SBOM.schema)

  schemer.validate(data || to_spdx_sbom(bottling:)).map { |error| error["error"] }
end

#to_spdx_sbom(bottling: false) ⇒ Hash{Symbol => T.anything}

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • bottling (Boolean) (defaults to: false)

Returns:



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'sbom.rb', line 251

def to_spdx_sbom(bottling: false)
  runtime_full = full_spdx_runtime_dependencies(bottling:)
  compiler_info = compiler_packages
  compiler_info = {} if bottling

  bottle = []
  if bottle_package?(bottling:) &&
     (bottle_info = get_bottle_info(source.bottle)) &&
     (stable_version = source.version)
    bottle << {
      SPDXID:           bottle_spdx_id,
      name:             name.to_s,
      versionInfo:      stable_version.to_s,
      filesAnalyzed:    false,
      licenseDeclared:  assert_value(nil),
      builtDate:        source_modified_time.iso8601,
      licenseConcluded: assert_value(license),
      downloadLocation: bottle_info.fetch("url"),
      copyrightText:    assert_value(nil),
      externalRefs:     [
        {
          referenceCategory: "PACKAGE-MANAGER",
          referenceLocator:  SBOM.brew_purl([source.tap_name, name].compact.join("/"), stable_version),
          referenceType:     "purl",
        },
      ],
      checksums:        [
        {
          algorithm:     "SHA256",
          checksumValue: bottle_info.fetch("sha256"),
        },
      ],
    }
  end

  patches = source.patches.each_with_index.filter_map do |patch, index|
    next unless patch.is_a?(ExternalPatch)

    package = {
      SPDXID:           SBOM.spdx_id("Patch-#{name}-#{index}"),
      name:             "#{name} patch #{index}",
      filesAnalyzed:    false,
      licenseDeclared:  assert_value(nil),
      licenseConcluded: assert_value(nil),
      downloadLocation: assert_value(patch.url),
      copyrightText:    assert_value(nil),
      checksums:        [],
      externalRefs:     [],
    }
    if (checksum = patch.resource.checksum.presence)
      package[:checksums] = [
        {
          algorithm:     "SHA256",
          checksumValue: checksum.hexdigest,
        },
      ]
    end
    package
  end

  source_purl = SBOM.brew_purl([source.tap_name, name].compact.join("/"), spec_version)

  external_refs = T.let([
    {
      referenceCategory: "PACKAGE-MANAGER",
      referenceLocator:  source_purl,
      referenceType:     "purl",
    },
  ], T::Array[SPDXSymbolHash])

  if (registry_pkg = Homebrew::Vulns::Identify.registry_package(source.url))
    external_refs << {
      referenceCategory: "PACKAGE-MANAGER",
      referenceLocator:  registry_pkg.purl,
      referenceType:     "purl",
    }
  end

  packages = [
    {
      SPDXID:           SBOM.spdx_id("Archive-#{name}-src"),
      name:             name.to_s,
      versionInfo:      spec_version.to_s,
      filesAnalyzed:    false,
      licenseDeclared:  assert_value(nil),
      builtDate:        source_modified_time.iso8601,
      licenseConcluded: assert_value(license),
      downloadLocation: source.url,
      copyrightText:    assert_value(nil),
      externalRefs:     external_refs,
      checksums:        source.checksum.presence&.then do |checksum|
        [{ algorithm: "SHA256", checksumValue: checksum.hexdigest }]
      end || [],
    },
  ] + patches + runtime_full + compiler_info.values + bottle
  files = generate_files_json

  runtime_relations = runtime_full.map do |dependency|
    {
      spdxElementId:      dependency[:SPDXID],
      relationshipType:   "RUNTIME_DEPENDENCY_OF",
      relatedSpdxElement: described_package_spdx_id(bottling:),
    }
  end

  patch_relations = source.patches.each_with_index.filter_map do |patch, index|
    next unless patch.is_a?(ExternalPatch)

    {
      spdxElementId:      SBOM.spdx_id("Patch-#{name}-#{index}"),
      relationshipType:   "PATCH_APPLIED",
      relatedSpdxElement: SBOM.spdx_id("Archive-#{name}-src"),
    }
  end

  base_relations = T.let([], T::Array[SPDXSymbolHash])

  if source.checksum.present?
    base_relations << {
      spdxElementId:      SBOM.spdx_id("File-#{name}"),
      relationshipType:   "PACKAGE_OF",
      relatedSpdxElement: SBOM.spdx_id("Archive-#{name}-src"),
    }
  end

  unless bottling
    base_relations << {
      spdxElementId:      "SPDXRef-Compiler",
      relationshipType:   "BUILD_TOOL_OF",
      relatedSpdxElement: SBOM.spdx_id("Archive-#{name}-src"),
    }

    if compiler_info["SPDXRef-Stdlib"].present?
      base_relations << {
        spdxElementId:      "SPDXRef-Stdlib",
        relationshipType:   "DEPENDENCY_OF",
        relatedSpdxElement: described_package_spdx_id(bottling:),
      }
    end
  end

  {
    SPDXID:            "SPDXRef-DOCUMENT",
    spdxVersion:       "SPDX-2.3",
    name:              "SBOM-SPDX-#{name}-#{spec_version}",
    creationInfo:      {
      created:  source_modified_time.iso8601,
      creators: ["Tool: https://github.com/Homebrew/brew"],
    },
    dataLicense:       "CC0-1.0",
    documentNamespace: "https://formulae.brew.sh/spdx/#{name}-#{spec_version}.json",
    documentDescribes: packages.map { |dependency| dependency[:SPDXID] },
    files:,
    packages:,
    relationships:     runtime_relations + patch_relations + base_relations,
  }
end

#to_spdx_supplement ⇒ SPDXHash

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'sbom.rb', line 410

def to_spdx_supplement
  runtime_full = full_spdx_runtime_dependencies(bottling: false)
  compiler_info = compiler_packages
  packages = runtime_full + compiler_info.values
  relationships = T.let([], T::Array[SPDXSymbolHash])
  runtime_full.each do |dependency|
    relationships << {
      spdxElementId:      dependency[:SPDXID],
      relationshipType:   "RUNTIME_DEPENDENCY_OF",
      relatedSpdxElement: bottle_spdx_id,
    }
  end

  if compiler_info["SPDXRef-Compiler"].present?
    relationships << {
      spdxElementId:      "SPDXRef-Compiler",
      relationshipType:   "BUILD_TOOL_OF",
      relatedSpdxElement: SBOM.spdx_id("Archive-#{name}-src"),
    }
  end

  if compiler_info["SPDXRef-Stdlib"].present?
    relationships << {
      spdxElementId:      "SPDXRef-Stdlib",
      relationshipType:   "DEPENDENCY_OF",
      relatedSpdxElement: bottle_spdx_id,
    }
  end

  {
    "documentDescribes" => packages.map { |package| package[:SPDXID] },
    "packages"          => packages,
    "relationships"     => relationships,
  }
end

#valid?(data = nil, bottling: false) ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • data (Hash{Symbol => T.anything}, nil) (defaults to: nil)
  • bottling (Boolean) (defaults to: false)

Returns:

  • (Boolean)


222
223
224
225
226
227
228
229
230
231
232
# File 'sbom.rb', line 222

def valid?(data = nil, bottling: false)
  validation_errors = schema_validation_errors(data, bottling:)
  return true if validation_errors.empty?

  opoo "SBOM validation errors:"
  validation_errors.each { |error| $stderr.puts error }

  odie "Failed to validate SBOM against JSON schema!" if ENV["HOMEBREW_ENFORCE_SBOM"]

  false
end

#write(validate: true, bottling: false) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • validate (Boolean) (defaults to: true)
  • bottling (Boolean) (defaults to: false)


235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'sbom.rb', line 235

def write(validate: true, bottling: false)
  # If this is a new installation, the cache of installed formulae
  # will no longer be valid.
  Formula.clear_cache unless spdxfile.exist?

  spdx_sbom = to_spdx_sbom(bottling:)

  if validate && !valid?(spdx_sbom, bottling:)
    opoo "SBOM is not valid, not writing to disk!"
    return
  end

  spdxfile.atomic_write(JSON.pretty_generate(spdx_sbom))
end