forked from CycloneDX/cyclonedx-python-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponent.py
527 lines (424 loc) · 16.5 KB
/
component.py
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# encoding: utf-8
# This file is part of CycloneDX Python Lib
#
# 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.
import warnings
from enum import Enum
from os.path import exists
from typing import List, Optional
# See https://github.com/package-url/packageurl-python/issues/65
from packageurl import PackageURL # type: ignore
from . import ExternalReference, HashAlgorithm, HashType, OrganizationalEntity, sha1sum, LicenseChoice, Property
from .release_note import ReleaseNotes
from .vulnerability import Vulnerability
class ComponentScope(Enum):
"""
Enum object that defines the permissable 'scopes' for a Component according to the CycloneDX schema.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.3/#type_scope
"""
REQUIRED = 'required'
OPTIONAL = 'optional'
EXCLUDED = 'excluded'
class ComponentType(Enum):
"""
Enum object that defines the permissible 'types' for a Component according to the CycloneDX schema.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.3/#type_classification
"""
APPLICATION = 'application'
CONTAINER = 'container'
DEVICE = 'device'
FILE = 'file'
FIRMWARE = 'firmware'
FRAMEWORK = 'framework'
LIBRARY = 'library'
OPERATING_SYSTEM = 'operating-system'
class Component:
"""
This is our internal representation of a Component within a Bom.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.3/#type_component
"""
@staticmethod
def for_file(absolute_file_path: str, path_for_bom: Optional[str]) -> 'Component':
"""
Helper method to create a Component that represents the provided local file as a Component.
Args:
absolute_file_path:
Absolute path to the file you wish to represent
path_for_bom:
Optionally, if supplied this is the path that will be used to identify the file in the BOM
Returns:
`Component` representing the supplied file
"""
if not exists(absolute_file_path):
raise FileExistsError('Supplied file path \'{}\' does not exist'.format(absolute_file_path))
sha1_hash: str = sha1sum(filename=absolute_file_path)
return Component(
name=path_for_bom if path_for_bom else absolute_file_path,
version='0.0.0-{}'.format(sha1_hash[0:12]),
hashes=[
HashType(algorithm=HashAlgorithm.SHA_1, hash_value=sha1_hash)
],
component_type=ComponentType.FILE, purl=PackageURL(
type='generic', name=path_for_bom if path_for_bom else absolute_file_path,
version='0.0.0-{}'.format(sha1_hash[0:12])
)
)
def __init__(self, name: str, component_type: ComponentType = ComponentType.LIBRARY,
mime_type: Optional[str] = None, bom_ref: Optional[str] = None,
supplier: Optional[OrganizationalEntity] = None, author: Optional[str] = None,
publisher: Optional[str] = None, group: Optional[str] = None, version: Optional[str] = None,
description: Optional[str] = None, scope: Optional[ComponentScope] = None,
hashes: Optional[List[HashType]] = None, licenses: Optional[List[LicenseChoice]] = None,
copyright: Optional[str] = None, purl: Optional[PackageURL] = None,
external_references: Optional[List[ExternalReference]] = None,
properties: Optional[List[Property]] = None, release_notes: Optional[ReleaseNotes] = None,
cpe: Optional[str] = None,
# Deprecated parameters kept for backwards compatibility
namespace: Optional[str] = None, license_str: Optional[str] = None
) -> None:
self.type = component_type
self.mime_type = mime_type
self.bom_ref = bom_ref
self.supplier = supplier
self.author = author
self.publisher = publisher
self.group = group
self.name = name
self.version = version
self.description = description
self.scope = scope
self.hashes = hashes or []
self.licenses = licenses or []
self.copyright = copyright
self.purl = purl
self.cpe = cpe
self.external_references = external_references if external_references else []
self.properties = properties
# Deprecated for 1.4, but kept for some backwards compatibility
if namespace:
warnings.warn(
'`namespace` is deprecated and has been replaced with `group` to align with the CycloneDX standard',
DeprecationWarning
)
if not group:
self.group = namespace
if license_str:
warnings.warn(
'`license_str` is deprecated and has been replaced with `licenses` to align with the CycloneDX '
'standard', DeprecationWarning
)
if not licenses:
self.licenses = [LicenseChoice(license_expression=license_str)]
# Added for 1.4
self.release_notes = release_notes
self.__vulnerabilites: List[Vulnerability] = []
@property
def type(self) -> ComponentType:
"""
Get the type of this Component.
Returns:
Declared type of this Component as `ComponentType`.
"""
return self._type
@type.setter
def type(self, component_type: ComponentType) -> None:
self._type = component_type
@property
def mime_type(self) -> Optional[str]:
"""
Get any declared mime-type for this Component.
When used on file components, the mime-type can provide additional context about the kind of file being
represented such as an image, font, or executable. Some library or framework components may also have an
associated mime-type.
Returns:
`str` if set else `None`
"""
return self._mime_type
@mime_type.setter
def mime_type(self, mime_type: Optional[str]) -> None:
self._mime_type = mime_type
@property
def bom_ref(self) -> Optional[str]:
"""
An optional identifier which can be used to reference the component elsewhere in the BOM. Every bom-ref MUST be
unique within the BOM.
Returns:
`str` as a unique identifiers for this Component if set else `None`
"""
return self._bom_ref
@bom_ref.setter
def bom_ref(self, bom_ref: Optional[str]) -> None:
self._bom_ref = bom_ref
@property
def supplier(self) -> Optional[OrganizationalEntity]:
"""
The organization that supplied the component. The supplier may often be the manufacture, but may also be a
distributor or repackager.
Returns:
`OrganizationalEntity` if set else `None`
"""
return self._supplier
@supplier.setter
def supplier(self, supplier: Optional[OrganizationalEntity]) -> None:
self._supplier = supplier
@property
def author(self) -> Optional[str]:
"""
The person(s) or organization(s) that authored the component.
Returns:
`str` if set else `None`
"""
return self._author
@author.setter
def author(self, author: Optional[str]) -> None:
self._author = author
@property
def publisher(self) -> Optional[str]:
"""
The person(s) or organization(s) that published the component
Returns:
`str` if set else `None`
"""
return self._publisher
@publisher.setter
def publisher(self, publisher: Optional[str]) -> None:
self._publisher = publisher
@property
def group(self) -> Optional[str]:
"""
The grouping name or identifier. This will often be a shortened, single name of the company or project that
produced the component, or the source package or domain name. Whitespace and special characters should be
avoided.
Examples include: `apache`, `org.apache.commons`, and `apache.org`.
Returns:
`str` if set else `None`
"""
return self._group
@group.setter
def group(self, group: Optional[str]) -> None:
self._group = group
@property
def name(self) -> str:
"""
The name of the component.
This will often be a shortened, single name of the component.
Examples: `commons-lang3` and `jquery`.
Returns:
`str`
"""
return self._name
@name.setter
def name(self, name: str) -> None:
self._name = name
@property
def version(self) -> Optional[str]:
"""
The component version. The version should ideally comply with semantic versioning but is not enforced.
This is NOT optional for CycloneDX Schema Version < 1.4 but was agreed to default to an empty string where a
version was not supplied for schema versions < 1.4
Returns:
Declared version of this Component as `str` or `None`
"""
return self._version
@version.setter
def version(self, version: Optional[str]) -> None:
self._version = version
@property
def description(self) -> Optional[str]:
"""
Get the description of this Component.
Returns:
`str` if set, else `None`.
"""
return self._description
@description.setter
def description(self, description: Optional[str]) -> None:
self._description = description
@property
def scope(self) -> Optional[ComponentScope]:
"""
Specifies the scope of the component.
If scope is not specified, 'required' scope should be assumed by the consumer of the BOM.
Returns:
`ComponentScope` or `None`
"""
return self._scope
@scope.setter
def scope(self, scope: Optional[ComponentScope]) -> None:
self._scope = scope
@property
def hashes(self) -> List[HashType]:
"""
Optional list of hashes that help specifiy the integrity of this Component.
Returns:
List of `HashType` or `None`
"""
return self._hashes
@hashes.setter
def hashes(self, hashes: List[HashType]) -> None:
self._hashes = hashes
def add_hash(self, a_hash: HashType) -> None:
"""
Adds a hash that pins/identifies this Component.
Args:
a_hash:
`HashType` instance
"""
self.hashes = self.hashes + [a_hash]
@property
def licenses(self) -> List[LicenseChoice]:
"""
A optional list of statements about how this Component is licensed.
Returns:
List of `LicenseChoice` else `None`
"""
return self._licenses
@licenses.setter
def licenses(self, licenses: List[LicenseChoice]) -> None:
self._licenses = licenses
@property
def copyright(self) -> Optional[str]:
"""
An optional copyright notice informing users of the underlying claims to copyright ownership in a published
work.
Returns:
`str` or `None`
"""
return self._copyright
@copyright.setter
def copyright(self, copyright: Optional[str]) -> None:
self._copyright = copyright
@property
def purl(self) -> Optional[PackageURL]:
"""
Specifies the package-url (PURL).
The purl, if specified, must be valid and conform to the specification defined at:
https://github.com/package-url/purl-spec
Returns:
`PackageURL` or `None`
"""
return self._purl
@purl.setter
def purl(self, purl: Optional[PackageURL]) -> None:
self._purl = purl
@property
def cpe(self) -> Optional[str]:
"""
Specifies a well-formed CPE name that conforms to the CPE 2.2 or 2.3 specification.
See https://nvd.nist.gov/products/cpe
Returns:
`str` if set else `None`
"""
return self._cpe
@cpe.setter
def cpe(self, cpe: Optional[str]) -> None:
self._cpe = cpe
@property
def external_references(self) -> List[ExternalReference]:
"""
Provides the ability to document external references related to the component or to the project the component
describes.
Returns:
List of `ExternalReference`s
"""
return self._external_references
@external_references.setter
def external_references(self, external_references: List[ExternalReference]) -> None:
self._external_references = external_references
def add_external_reference(self, reference: ExternalReference) -> None:
"""
Add an `ExternalReference` to this `Component`.
Args:
reference:
`ExternalReference` instance to add.
"""
self.external_references = self._external_references + [reference]
@property
def properties(self) -> Optional[List[Property]]:
"""
Provides the ability to document properties in a key/value store. This provides flexibility to include data not
officially supported in the standard without having to use additional namespaces or create extensions.
Return:
List of `Property` or `None`
"""
return self._properties
@properties.setter
def properties(self, properties: Optional[List[Property]]) -> None:
self._properties = properties
@property
def release_notes(self) -> Optional[ReleaseNotes]:
"""
Specifies optional release notes.
Returns:
`ReleaseNotes` or `None`
"""
return self._release_notes
@release_notes.setter
def release_notes(self, release_notes: Optional[ReleaseNotes]) -> None:
self._release_notes = release_notes
def add_vulnerability(self, vulnerability: Vulnerability) -> None:
"""
Add a Vulnerability to this Component.
Args:
vulnerability:
`cyclonedx.model.vulnerability.Vulnerability` instance to add to this Component.
Returns:
None
"""
self.__vulnerabilites.append(vulnerability)
def get_vulnerabilities(self) -> List[Vulnerability]:
"""
Get all the Vulnerabilities for this Component.
Returns:
List of `Vulnerability` objects assigned to this Component.
"""
return self.__vulnerabilites
def has_vulnerabilities(self) -> bool:
"""
Does this Component have any vulnerabilities?
Returns:
`True` if this Component has 1 or more vulnerabilities, `False` otherwise.
"""
return bool(self.get_vulnerabilities())
def get_pypi_url(self) -> str:
if self.version:
return f'https://pypi.org/project/{self.name}/{self.version}'
else:
return f'https://pypi.org/project/{self.name}'
def __eq__(self, other: object) -> bool:
if isinstance(other, Component):
return hash(other) == hash(self)
return False
def __hash__(self) -> int:
return hash((
self.author, self.bom_ref, self.copyright, self.description, str(self.external_references), self.group,
str(self.hashes), str(self.licenses), self.mime_type, self.name, self.properties, self.publisher, self.purl,
self.release_notes, self.scope, self.supplier, self.type, self.version, self.cpe
))
def __repr__(self) -> str:
return f'<Component group={self.group}, name={self.name}, version={self.version}>'
# Deprecated methods
def get_namespace(self) -> Optional[str]:
"""
Get the namespace of this Component.
Returns:
Declared namespace of this Component as `str` if declared, else `None`.
"""
warnings.warn('`Component.get_namespace()` is deprecated - use `Component.group`', DeprecationWarning)
return self._group