-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbuilders.ts
More file actions
454 lines (403 loc) · 17.4 KB
/
builders.ts
File metadata and controls
454 lines (403 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
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
408
409
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
445
446
447
448
449
450
451
452
453
454
/*!
This file is part of CycloneDX SBOM plugin for yarn.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
Copyright (c) OWASP Foundation. All Rights Reserved.
*/
/* eslint-disable @typescript-eslint/max-params -- bassdscho */
// import submodules so to prevent load of unused not-tree-shakable dependencies - like 'AJV'
import { Utils as BomUUtils } from '@cyclonedx/cyclonedx-library/Contrib/Bom'
import type { Builders as FromNodePackageJsonBuilders } from '@cyclonedx/cyclonedx-library/Contrib/FromNodePackageJson'
import { Utils as LicenseUtils } from '@cyclonedx/cyclonedx-library/Contrib/License'
import { ComponentType, ExternalReferenceType, LicenseAcknowledgement } from '@cyclonedx/cyclonedx-library/Enums'
import type { License } from '@cyclonedx/cyclonedx-library/Models'
import { Bom, Component, ComponentEvidence, ExternalReference, NamedLicense, Property } from '@cyclonedx/cyclonedx-library/Models'
import type { FetchOptions, Locator, LocatorHash, Package, Project, Workspace } from '@yarnpkg/core'
import { Cache, structUtils, ThrowReport, YarnVersion } from '@yarnpkg/core'
import type { PortablePath } from '@yarnpkg/fslib'
import { ppath } from '@yarnpkg/fslib'
import { gitUtils as YarnPluginGitUtils } from '@yarnpkg/plugin-git'
import type { PackageURL } from "packageurl-js"
import { getBuildtimeInfo } from './_buildtimeInfo'
import {
isString,
normalizePackageManifest,
tryRemoveSecretsFromUrl,
trySanitizeGitUrl
} from './_helpers'
import type { PackageUrlFactory } from './factories'
import { PropertyNames, PropertyValueBool } from './properties'
type ManifestFetcher = (pkg: Package) => Promise<NonNullable<any>>
type LicenseEvidenceFetcher = (pkg: Package) => AsyncGenerator<License>
interface BomBuilderOptions {
omitDevDependencies?: BomBuilder['omitDevDependencies']
metaComponentType?: BomBuilder['metaComponentType']
reproducible?: BomBuilder['reproducible']
shortPURLs?: BomBuilder['shortPURLs']
gatherLicenseTexts?: BomBuilder['gatherLicenseTexts']
}
export class BomBuilder {
readonly toolBuilder: FromNodePackageJsonBuilders.ToolBuilder
readonly componentBuilder: FromNodePackageJsonBuilders.ComponentBuilder
readonly purlFactory: PackageUrlFactory
readonly omitDevDependencies: boolean
readonly metaComponentType: ComponentType
readonly reproducible: boolean
readonly shortPURLs: boolean
readonly gatherLicenseTexts: boolean
readonly console: Console
constructor (
toolBuilder: BomBuilder['toolBuilder'],
componentBuilder: BomBuilder['componentBuilder'],
purlFactory: BomBuilder['purlFactory'],
options: BomBuilderOptions,
console_: BomBuilder['console']
) {
this.toolBuilder = toolBuilder
this.componentBuilder = componentBuilder
this.purlFactory = purlFactory
this.omitDevDependencies = options.omitDevDependencies ?? false
this.metaComponentType = options.metaComponentType ?? ComponentType.Application
this.reproducible = options.reproducible ?? false
this.shortPURLs = options.shortPURLs ?? false
this.gatherLicenseTexts = options.gatherLicenseTexts ?? false
this.console = console_
}
async buildFromWorkspace (workspace: Workspace): Promise<Bom> {
// @TODO make switch to disable load from fs
const fetchManifest: ManifestFetcher = await this.makeManifestFetcher(workspace.project)
const fetchLicenseEvidences: LicenseEvidenceFetcher = await this.makeLicenseEvidenceFetcher(workspace.project)
const setLicensesDeclared = function (license: License): void {
/* eslint-disable no-param-reassign -- intended */
license.acknowledgement = LicenseAcknowledgement.Declared
/* eslint-enable no-param-reassign */
}
const rootComponent: Component = this.makeComponentFromWorkspace(workspace, this.metaComponentType)
?? new DummyComponent(this.metaComponentType, 'RootComponent')
rootComponent.licenses.forEach(setLicensesDeclared)
const bom = new Bom()
// region metadata
bom.metadata.component = rootComponent
for await (const toolC of this.makeToolCs()) {
bom.metadata.tools.components.add(toolC)
}
if (this.reproducible) {
bom.metadata.properties.add(
new Property(PropertyNames.Reproducible, PropertyValueBool.True)
)
} else {
bom.serialNumber = BomUUtils.randomSerialNumber()
bom.metadata.timestamp = new Date()
}
// endregion metadata
// region components
const rootPackage = workspace.anchoredPackage
if (this.omitDevDependencies) {
for (const dep of workspace.manifest.devDependencies.keys()) {
rootPackage.dependencies.delete(dep)
}
}
// Build map of workspace packages' devDependencies for filtering
const workspaceDevDeps = this.omitDevDependencies
? this.gatherWorkspaceDevDependencies(workspace.project)
: new Map<LocatorHash, Set<string>>()
for await (const component of this.gatherDependencies(
rootComponent, rootPackage,
workspace.project,
fetchManifest, fetchLicenseEvidences,
workspaceDevDeps
)) {
component.licenses.forEach(setLicensesDeclared)
this.console.info('INFO | add component for %s/%s@%s',
component.group ?? '-',
component.name,
component.version ?? '-'
)
bom.components.add(component)
}
// endregion components
return bom
}
private makeComponentFromWorkspace (workspace: Workspace, type?: ComponentType ): Component | undefined {
return this.makeComponent(workspace.anchoredLocator, workspace.manifest.raw, type)
}
private async makeManifestFetcher (project: Project): Promise<ManifestFetcher> {
const fetcher = project.configuration.makeFetcher()
const fetcherOptions: FetchOptions = {
project,
fetcher,
cache: await Cache.find(project.configuration),
checksums: project.storedChecksums,
report: new ThrowReport(),
cacheOptions: { skipIntegrityCheck: true }
}
return async function (pkg: Package): Promise<NonNullable<any>> {
const { packageFs, prefixPath, releaseFs } = await fetcher.fetch(pkg, fetcherOptions)
try {
const manifestPath = ppath.join(prefixPath, 'package.json')
return JSON.parse(await packageFs.readFilePromise(manifestPath, 'utf8')) ?? {}
} finally {
if (releaseFs !== undefined) {
releaseFs()
}
}
}
}
private async makeLicenseEvidenceFetcher (project: Project): Promise<LicenseEvidenceFetcher> {
const fetcher = project.configuration.makeFetcher()
const fetcherOptions: FetchOptions = {
project,
fetcher,
cache: await Cache.find(project.configuration),
checksums: project.storedChecksums,
report: new ThrowReport(),
cacheOptions: { skipIntegrityCheck: true }
}
const console_ = this.console
return async function * (pkg: Package): AsyncGenerator<License> {
const { packageFs, prefixPath, releaseFs } = await fetcher.fetch(pkg, fetcherOptions)
const leGatherer = new LicenseUtils.LicenseEvidenceGatherer<PortablePath>({fs: packageFs, path: ppath})
const files = leGatherer.getFileAttachments(
prefixPath,
(error: Error): void => {
/* c8 ignore next 2 */
console_.info(error.message)
console_.debug(error.message, error)
}
)
try {
for (const {file, text} of files) {
yield new NamedLicense(`file: ${file}`, {text})
}
}
/* c8 ignore next 3 */
catch (e) {
// generator will not throw before first `.nest()` is called ...
console_.warn('collecting license evidence in', prefixPath, 'failed:', e)
} finally {
if (releaseFs !== undefined) {
releaseFs()
}
}
}
}
private async makeComponentFromPackage (
pkg: Package,
fetchManifest: ManifestFetcher,
fetchLicenseEvidence: LicenseEvidenceFetcher,
type?: ComponentType
): Promise<Component | undefined> {
/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
-- not unsafe! is not null nor undefined */
const manifest = await fetchManifest(pkg)
// the data in the manifest might be incomplete, so lets set the properties that yarn discovered and fixed
/* eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- needed */
manifest.name = pkg.scope ? `@${pkg.scope}/${pkg.name}` : pkg.name
manifest.version = pkg.version
const component = this.makeComponent(pkg, manifest, type)
if (component === undefined) {
return undefined
}
if (this.gatherLicenseTexts) {
component.evidence = new ComponentEvidence()
for await (const le of fetchLicenseEvidence(pkg)) {
component.evidence.licenses.add(le)
}
}
/* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment */
return component
}
private makeComponent (locator: Locator, manifest: NonNullable<any>, type?: ComponentType ): Component | undefined {
// work with a deep copy, because `normalizePackageManifest()` might modify the data
/* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- ack */
const manifestC = structuredClone(manifest)
normalizePackageManifest(manifestC)
const component = this.componentBuilder.makeComponent(manifestC, type)
if (component === undefined) {
this.console.debug('DEBUG | skip broken component: %j', locator)
return undefined
}
switch (true) {
case locator.reference.startsWith('workspace:'): {
// @TODO: add CDX-Property for it - cdx:yarn:reference:workspace = $workspaceName
// -- reminder: skip `workspace:.`
break
}
case locator.reference.startsWith('npm:'): {
// see https://github.com/yarnpkg/berry/blob/bfa6489467e0e11ee87268e01e38e4f7e8d4d4b0/packages/plugin-npm/sources/NpmHttpFetcher.ts#L51
const { params } = structUtils.parseRange(locator.reference)
if (params !== null && isString(params.__archiveUrl)) {
component.externalReferences.add(new ExternalReference(
tryRemoveSecretsFromUrl(params.__archiveUrl),
ExternalReferenceType.Distribution,
{ comment: 'as detected from YarnLocator property "reference::__archiveUrl"' }
))
}
// For range and remap there are no concrete evidence how the resolution was done on install-time.
// Therefore, do not do anything speculative.
break
}
case YarnPluginGitUtils.isGitUrl(locator.reference): {
component.externalReferences.add(new ExternalReference(
trySanitizeGitUrl(locator.reference),
ExternalReferenceType.VCS,
{ comment: 'as detected from YarnLocator property "reference"' }
))
break
}
case locator.reference.startsWith('http:') || locator.reference.startsWith('https:'): {
component.externalReferences.add(new ExternalReference(
tryRemoveSecretsFromUrl(locator.reference),
ExternalReferenceType.Distribution,
{ comment: 'as detected from YarnLocator property "reference"' }
))
break
}
case locator.reference.startsWith('link:'): {
// TODO: add CDX-Property for it - cdx:yarn:reference:link = relative path from workspace
// see https://github.com/yarnpkg/berry/tree/master/packages/plugin-link
break
}
case locator.reference.startsWith('portal:'): {
// TODO: add CDX-Property for it - cdx:yarn:reference:portal = relative path from workspace
// see https://github.com/yarnpkg/berry/tree/master/packages/plugin-link
break
}
case locator.reference.startsWith('file:'): {
// TODO: add CDX-Property for it - cdx:yarn:reference:portal = relative path from workspace
// see https://github.com/yarnpkg/berry/tree/master/packages/plugin-file
break
}
default:
break
}
component.purl = this.finalizePurl(this.purlFactory.makeFromLocatedManifest(
locator,
manifest // eslint-disable-line @typescript-eslint/no-unsafe-argument -- false positive
))
component.bomRef.value = structUtils.prettyLocatorNoColors(locator)
return component
}
private finalizePurl (purl: PackageURL|undefined): string|undefined {
if (purl === undefined) { return purl }
if (this.shortPURLs) {
/* eslint-disable no-param-reassign -- ack */
purl.qualifiers = undefined
purl.subpath = undefined
/* eslint-enable no-param-reassign */
}
return purl.toString()
}
private async * makeToolCs (): AsyncGenerator<Component> {
yield new Component(ComponentType.Application, 'yarn', { version: YarnVersion ?? undefined })
for (const pd of Object.values(await getBuildtimeInfo())) {
const toolC = this.componentBuilder.makeComponent(pd, ComponentType.Library)
if (toolC !== undefined) {
yield toolC
}
}
}
/**
* Gathers devDependencies from all workspace packages in the project.
* Returns a map of package locatorHash to Set of devDependency names.
*/
private gatherWorkspaceDevDependencies (project: Project): Map<LocatorHash, Set<string>> {
const workspaceDevDeps = new Map<LocatorHash, Set<string>>()
for (const workspace of project.workspaces) {
const pkg = workspace.anchoredPackage
// Only process workspace packages (not external dependencies)
if (pkg.reference.startsWith('workspace:')) {
const devDeps = new Set<string>()
for (const depIdent of workspace.manifest.devDependencies.keys()) {
devDeps.add(depIdent)
}
if (devDeps.size > 0) {
workspaceDevDeps.set(pkg.locatorHash, devDeps)
this.console.debug('DEBUG | workspace %s has %d devDependencies',
structUtils.prettyLocatorNoColors(pkg),
devDeps.size
)
}
}
}
return workspaceDevDeps
}
private * getDeps (
pkg: Package,
project: Project,
workspaceDevDeps: Map<LocatorHash, Set<string>>
): Generator<Package> {
const parentDevDeps = workspaceDevDeps.get(pkg.locatorHash)
for (const depDesc of pkg.dependencies.values()) {
// Skip if this is a devDependency of the parent workspace package
if (parentDevDeps?.has(depDesc.identHash) === true) {
this.console.debug('DEBUG | skipping devDependency %s of workspace package %s',
depDesc.identHash,
structUtils.prettyLocatorNoColors(pkg)
)
continue
}
const depRes = project.storedResolutions.get(depDesc.descriptorHash)
if (typeof depRes === 'undefined') {
throw new Error(`missing depRes for : ${depDesc.descriptorHash}`)
}
const depPackage = project.storedPackages.get(depRes)
if (typeof depPackage === 'undefined') {
throw new Error(`missing depPackage for depRes: ${depRes}`)
}
yield depPackage
}
}
async * gatherDependencies (
component: Component, pkg: Package,
project: Project,
fetchManifest: ManifestFetcher,
fetchLicenseEvidences: LicenseEvidenceFetcher,
workspaceDevDeps: Map<LocatorHash, Set<string>>
): AsyncGenerator<Component> {
// ATTENTION: multiple packages may have the same `identHash`, but the `locatorHash` is unique.
const knownComponents = new Map<LocatorHash, Component>([[pkg.locatorHash, component]])
type pendingType = [Package, Component]
const pending: pendingType[] = [[pkg, component]]
let pendingEntry // eslint-disable-line @typescript-eslint/init-declarations -- ack
while ((pendingEntry = pending.pop()) !== undefined) {
const [pendingPkg, pendingComponent] = pendingEntry
for (const depPkg of this.getDeps(pendingPkg, project, workspaceDevDeps)) {
let depComponent = knownComponents.get(depPkg.locatorHash)
if (depComponent === undefined) {
const _depIDN = structUtils.prettyLocatorNoColors(depPkg)
/* eslint-disable-next-line no-await-in-loop -- ack */
const _depC = await this.makeComponentFromPackage(depPkg,
fetchManifest, fetchLicenseEvidences)
if (_depC === undefined) {
depComponent = new DummyComponent(ComponentType.Library, `InterferedDependency.${_depIDN}`)
this.console.warn('WARN | InterferedDependency %j', _depIDN)
} else {
depComponent = _depC
this.console.debug('DEBUG | built component %j: %j', _depIDN, depComponent)
}
yield depComponent
knownComponents.set(depPkg.locatorHash, depComponent)
pending.push([depPkg, depComponent])
}
pendingComponent.dependencies.add(depComponent.bomRef)
}
}
}
}
class DummyComponent extends Component {
constructor (type: Component['type'], name: Component['name']) {
super(type, `DummyComponent.${name}`, {
bomRef: `DummyComponent.${name}`,
description: `This is a dummy component "${name}" that fills the gap where the actual built failed.`
})
}
}