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 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
|
# This file is part of CycloneDX Python Library
#
# 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 re
from enum import Enum
from os.path import exists
from typing import Any, Dict, FrozenSet, Iterable, Optional, Set, Type, Union
from warnings import warn
# See https://github.com/package-url/packageurl-python/issues/65
import py_serializable as serializable
from packageurl import PackageURL
from sortedcontainers import SortedSet
from .._internal.bom_ref import bom_ref_from_str as _bom_ref_from_str
from .._internal.compare import ComparablePackageURL as _ComparablePackageURL, ComparableTuple as _ComparableTuple
from .._internal.hash import file_sha1sum as _file_sha1sum
from ..exception.model import InvalidOmniBorIdException, InvalidSwhidException
from ..exception.serialization import (
CycloneDxDeserializationException,
SerializationOfUnexpectedValueException,
SerializationOfUnsupportedComponentTypeException,
)
from ..schema.schema import (
SchemaVersion1Dot0,
SchemaVersion1Dot1,
SchemaVersion1Dot2,
SchemaVersion1Dot3,
SchemaVersion1Dot4,
SchemaVersion1Dot5,
SchemaVersion1Dot6,
)
from ..serialization import PackageUrl as PackageUrlSH
from . import (
AttachedText,
Copyright,
ExternalReference,
HashAlgorithm,
HashType,
IdentifiableAction,
Property,
XsUri,
_HashTypeRepositorySerializationHelper,
)
from .bom_ref import BomRef
from .contact import OrganizationalContact, OrganizationalEntity
from .crypto import CryptoProperties
from .dependency import Dependable
from .issue import IssueType
from .license import License, LicenseRepository, _LicenseRepositorySerializationHelper
from .release_note import ReleaseNotes
@serializable.serializable_class
class Commit:
"""
Our internal representation of the `commitType` complex type.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/xml/#type_commitType
"""
def __init__(
self, *,
uid: Optional[str] = None,
url: Optional[XsUri] = None,
author: Optional[IdentifiableAction] = None,
committer: Optional[IdentifiableAction] = None,
message: Optional[str] = None,
) -> None:
self.uid = uid
self.url = url
self.author = author
self.committer = committer
self.message = message
@property
@serializable.xml_sequence(1)
@serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
def uid(self) -> Optional[str]:
"""
A unique identifier of the commit. This may be version control specific. For example, Subversion uses revision
numbers whereas git uses commit hashes.
Returns:
`str` if set else `None`
"""
return self._uid
@uid.setter
def uid(self, uid: Optional[str]) -> None:
self._uid = uid
@property
@serializable.xml_sequence(2)
def url(self) -> Optional[XsUri]:
"""
The URL to the commit. This URL will typically point to a commit in a version control system.
Returns:
`XsUri` if set else `None`
"""
return self._url
@url.setter
def url(self, url: Optional[XsUri]) -> None:
self._url = url
@property
@serializable.xml_sequence(3)
def author(self) -> Optional[IdentifiableAction]:
"""
The author who created the changes in the commit.
Returns:
`IdentifiableAction` if set else `None`
"""
return self._author
@author.setter
def author(self, author: Optional[IdentifiableAction]) -> None:
self._author = author
@property
@serializable.xml_sequence(4)
def committer(self) -> Optional[IdentifiableAction]:
"""
The person who committed or pushed the commit
Returns:
`IdentifiableAction` if set else `None`
"""
return self._committer
@committer.setter
def committer(self, committer: Optional[IdentifiableAction]) -> None:
self._committer = committer
@property
@serializable.xml_sequence(5)
@serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
def message(self) -> Optional[str]:
"""
The text description of the contents of the commit.
Returns:
`str` if set else `None`
"""
return self._message
@message.setter
def message(self, message: Optional[str]) -> None:
self._message = message
def __comparable_tuple(self) -> _ComparableTuple:
return _ComparableTuple((
self.uid, self.url,
self.author, self.committer,
self.message
))
def __eq__(self, other: object) -> bool:
if isinstance(other, Commit):
return self.__comparable_tuple() == other.__comparable_tuple()
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, Commit):
return self.__comparable_tuple() < other.__comparable_tuple()
return NotImplemented
def __hash__(self) -> int:
return hash(self.__comparable_tuple())
def __repr__(self) -> str:
return f'<Commit uid={self.uid}, url={self.url}, message={self.message}>'
@serializable.serializable_class
class ComponentEvidence:
"""
Our internal representation of the `componentEvidenceType` complex type.
Provides the ability to document evidence collected through various forms of extraction or analysis.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/xml/#type_componentEvidenceType
"""
def __init__(
self, *,
licenses: Optional[Iterable[License]] = None,
copyright: Optional[Iterable[Copyright]] = None,
) -> None:
self.licenses = licenses or [] # type:ignore[assignment]
self.copyright = copyright or [] # type:ignore[assignment]
# @property
# ...
# @serializable.view(SchemaVersion1Dot5)
# @serializable.xml_sequence(1)
# def identity(self) -> ...:
# ... # TODO since CDX1.5
#
# @identity.setter
# def identity(self, ...) -> None:
# ... # TODO since CDX1.5
# @property
# ...
# @serializable.view(SchemaVersion1Dot5)
# @serializable.xml_sequence(2)
# def occurrences(self) -> ...:
# ... # TODO since CDX1.5
#
# @occurrences.setter
# def occurrences(self, ...) -> None:
# ... # TODO since CDX1.5
# @property
# ...
# @serializable.view(SchemaVersion1Dot5)
# @serializable.xml_sequence(3)
# def callstack(self) -> ...:
# ... # TODO since CDX1.5
#
# @callstack.setter
# def callstack(self, ...) -> None:
# ... # TODO since CDX1.5
@property
@serializable.type_mapping(_LicenseRepositorySerializationHelper)
@serializable.xml_sequence(4)
def licenses(self) -> LicenseRepository:
"""
Optional list of licenses obtained during analysis.
Returns:
Set of `LicenseChoice`
"""
return self._licenses
@licenses.setter
def licenses(self, licenses: Iterable[License]) -> None:
self._licenses = LicenseRepository(licenses)
@property
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'text')
@serializable.xml_sequence(5)
def copyright(self) -> 'SortedSet[Copyright]':
"""
Optional list of copyright statements.
Returns:
Set of `Copyright`
"""
return self._copyright
@copyright.setter
def copyright(self, copyright: Iterable[Copyright]) -> None:
self._copyright = SortedSet(copyright)
def __comparable_tuple(self) -> _ComparableTuple:
return _ComparableTuple((
_ComparableTuple(self.licenses),
_ComparableTuple(self.copyright),
))
def __eq__(self, other: object) -> bool:
if isinstance(other, ComponentEvidence):
return self.__comparable_tuple() == other.__comparable_tuple()
return False
def __hash__(self) -> int:
return hash(self.__comparable_tuple())
def __repr__(self) -> str:
return f'<ComponentEvidence id={id(self)}>'
@serializable.serializable_enum
class ComponentScope(str, 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.6/#type_scope
"""
# see `_ComponentScopeSerializationHelper.__CASES` for view/case map
REQUIRED = 'required'
OPTIONAL = 'optional'
EXCLUDED = 'excluded' # Only supported in >= 1.1
class _ComponentScopeSerializationHelper(serializable.helpers.BaseHelper):
""" THIS CLASS IS NON-PUBLIC API """
__CASES: Dict[Type[serializable.ViewType], FrozenSet[ComponentScope]] = dict()
__CASES[SchemaVersion1Dot0] = frozenset({
ComponentScope.REQUIRED,
ComponentScope.OPTIONAL,
})
__CASES[SchemaVersion1Dot1] = __CASES[SchemaVersion1Dot0] | {
ComponentScope.EXCLUDED,
}
__CASES[SchemaVersion1Dot2] = __CASES[SchemaVersion1Dot1]
__CASES[SchemaVersion1Dot3] = __CASES[SchemaVersion1Dot2]
__CASES[SchemaVersion1Dot4] = __CASES[SchemaVersion1Dot3]
__CASES[SchemaVersion1Dot5] = __CASES[SchemaVersion1Dot4]
__CASES[SchemaVersion1Dot6] = __CASES[SchemaVersion1Dot5]
@classmethod
def __normalize(cls, cs: ComponentScope, view: Type[serializable.ViewType]) -> Optional[str]:
return cs.value \
if cs in cls.__CASES.get(view, ()) \
else None
@classmethod
def json_normalize(cls, o: Any, *,
view: Optional[Type[serializable.ViewType]],
**__: Any) -> Optional[str]:
assert view is not None
return cls.__normalize(o, view)
@classmethod
def xml_normalize(cls, o: Any, *,
view: Optional[Type[serializable.ViewType]],
**__: Any) -> Optional[str]:
assert view is not None
return cls.__normalize(o, view)
@classmethod
def deserialize(cls, o: Any) -> ComponentScope:
return ComponentScope(o)
@serializable.serializable_enum
class ComponentType(str, 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.6/#type_classification
"""
# see `_ComponentTypeSerializationHelper.__CASES` for view/case map
APPLICATION = 'application'
CONTAINER = 'container' # Only supported in >= 1.2
CRYPTOGRAPHIC_ASSET = 'cryptographic-asset' # Only supported in >= 1.6
DATA = 'data' # Only supported in >= 1.5
DEVICE = 'device'
DEVICE_DRIVER = 'device-driver' # Only supported in >= 1.5
FILE = 'file' # Only supported in >= 1.1
FIRMWARE = 'firmware' # Only supported in >= 1.2
FRAMEWORK = 'framework'
LIBRARY = 'library'
MACHINE_LEARNING_MODEL = 'machine-learning-model' # Only supported in >= 1.5
OPERATING_SYSTEM = 'operating-system'
PLATFORM = 'platform' # Only supported in >= 1.5
class _ComponentTypeSerializationHelper(serializable.helpers.BaseHelper):
""" THIS CLASS IS NON-PUBLIC API """
__CASES: Dict[Type[serializable.ViewType], FrozenSet[ComponentType]] = dict()
__CASES[SchemaVersion1Dot0] = frozenset({
ComponentType.APPLICATION,
ComponentType.DEVICE,
ComponentType.FRAMEWORK,
ComponentType.LIBRARY,
ComponentType.OPERATING_SYSTEM,
})
__CASES[SchemaVersion1Dot1] = __CASES[SchemaVersion1Dot0] | {
ComponentType.FILE,
}
__CASES[SchemaVersion1Dot2] = __CASES[SchemaVersion1Dot1] | {
ComponentType.CONTAINER,
ComponentType.FIRMWARE,
}
__CASES[SchemaVersion1Dot3] = __CASES[SchemaVersion1Dot2]
__CASES[SchemaVersion1Dot4] = __CASES[SchemaVersion1Dot3]
__CASES[SchemaVersion1Dot5] = __CASES[SchemaVersion1Dot4] | {
ComponentType.DATA,
ComponentType.DEVICE_DRIVER,
ComponentType.MACHINE_LEARNING_MODEL,
ComponentType.PLATFORM,
}
__CASES[SchemaVersion1Dot6] = __CASES[SchemaVersion1Dot5] | {
ComponentType.CRYPTOGRAPHIC_ASSET,
}
@classmethod
def __normalize(cls, ct: ComponentType, view: Type[serializable.ViewType]) -> Optional[str]:
if ct in cls.__CASES.get(view, ()):
return ct.value
raise SerializationOfUnsupportedComponentTypeException(f'unsupported {ct!r} for view {view!r}')
@classmethod
def json_normalize(cls, o: Any, *,
view: Optional[Type[serializable.ViewType]],
**__: Any) -> Optional[str]:
assert view is not None
return cls.__normalize(o, view)
@classmethod
def xml_normalize(cls, o: Any, *,
view: Optional[Type[serializable.ViewType]],
**__: Any) -> Optional[str]:
assert view is not None
return cls.__normalize(o, view)
@classmethod
def deserialize(cls, o: Any) -> ComponentType:
return ComponentType(o)
@serializable.serializable_class
class Diff:
"""
Our internal representation of the `diffType` complex type.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/xml/#type_diffType
"""
def __init__(
self, *,
text: Optional[AttachedText] = None,
url: Optional[XsUri] = None,
) -> None:
self.text = text
self.url = url
@property
def text(self) -> Optional[AttachedText]:
"""
Specifies the optional text of the diff.
Returns:
`AttachedText` if set else `None`
"""
return self._text
@text.setter
def text(self, text: Optional[AttachedText]) -> None:
self._text = text
@property
def url(self) -> Optional[XsUri]:
"""
Specifies the URL to the diff.
Returns:
`XsUri` if set else `None`
"""
return self._url
@url.setter
def url(self, url: Optional[XsUri]) -> None:
self._url = url
def __comparable_tuple(self) -> _ComparableTuple:
return _ComparableTuple((
self.url,
self.text,
))
def __eq__(self, other: object) -> bool:
if isinstance(other, Diff):
return self.__comparable_tuple() == other.__comparable_tuple()
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, Diff):
return self.__comparable_tuple() < other.__comparable_tuple()
return NotImplemented
def __hash__(self) -> int:
return hash(self.__comparable_tuple())
def __repr__(self) -> str:
return f'<Diff url={self.url}>'
@serializable.serializable_enum
class PatchClassification(str, Enum):
"""
Enum object that defines the permissible `patchClassification`s.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/xml/#type_patchClassification
"""
BACKPORT = 'backport'
CHERRY_PICK = 'cherry-pick'
MONKEY = 'monkey'
UNOFFICIAL = 'unofficial'
@serializable.serializable_class
class Patch:
"""
Our internal representation of the `patchType` complex type.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/xml/#type_patchType
"""
def __init__(
self, *,
type: PatchClassification,
diff: Optional[Diff] = None,
resolves: Optional[Iterable[IssueType]] = None,
) -> None:
self.type = type
self.diff = diff
self.resolves = resolves or [] # type:ignore[assignment]
@property
@serializable.xml_attribute()
def type(self) -> PatchClassification:
"""
Specifies the purpose for the patch including the resolution of defects, security issues, or new behavior or
functionality.
Returns:
`PatchClassification`
"""
return self._type
@type.setter
def type(self, type: PatchClassification) -> None:
self._type = type
@property
def diff(self) -> Optional[Diff]:
"""
The patch file (or diff) that show changes.
.. note::
Refer to https://en.wikipedia.org/wiki/Diff.
Returns:
`Diff` if set else `None`
"""
return self._diff
@diff.setter
def diff(self, diff: Optional[Diff]) -> None:
self._diff = diff
@property
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'issue')
def resolves(self) -> 'SortedSet[IssueType]':
"""
Optional list of issues resolved by this patch.
Returns:
Set of `IssueType`
"""
return self._resolves
@resolves.setter
def resolves(self, resolves: Iterable[IssueType]) -> None:
self._resolves = SortedSet(resolves)
def __comparable_tuple(self) -> _ComparableTuple:
return _ComparableTuple((
self.type, self.diff,
_ComparableTuple(self.resolves)
))
def __eq__(self, other: object) -> bool:
if isinstance(other, Patch):
return self.__comparable_tuple() == other.__comparable_tuple()
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, Patch):
return self.__comparable_tuple() < other.__comparable_tuple()
return NotImplemented
def __hash__(self) -> int:
return hash(self.__comparable_tuple())
def __repr__(self) -> str:
return f'<Patch type={self.type}, id={id(self)}>'
@serializable.serializable_class
class Pedigree:
"""
Our internal representation of the `pedigreeType` complex type.
Component pedigree is a way to document complex supply chain scenarios where components are created, distributed,
modified, redistributed, combined with other components, etc. Pedigree supports viewing this complex chain from the
beginning, the end, or anywhere in the middle. It also provides a way to document variants where the exact relation
may not be known.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/xml/#type_pedigreeType
"""
def __init__(
self, *,
ancestors: Optional[Iterable['Component']] = None,
descendants: Optional[Iterable['Component']] = None,
variants: Optional[Iterable['Component']] = None,
commits: Optional[Iterable[Commit]] = None,
patches: Optional[Iterable[Patch]] = None,
notes: Optional[str] = None,
) -> None:
self.ancestors = ancestors or [] # type:ignore[assignment]
self.descendants = descendants or [] # type:ignore[assignment]
self.variants = variants or [] # type:ignore[assignment]
self.commits = commits or [] # type:ignore[assignment]
self.patches = patches or [] # type:ignore[assignment]
self.notes = notes
@property
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'component')
@serializable.xml_sequence(1)
def ancestors(self) -> "SortedSet['Component']":
"""
Describes zero or more components in which a component is derived from. This is commonly used to describe forks
from existing projects where the forked version contains a ancestor node containing the original component it
was forked from.
For example, Component A is the original component. Component B is the component being used and documented in
the BOM. However, Component B contains a pedigree node with a single ancestor documenting Component A - the
original component from which Component B is derived from.
Returns:
Set of `Component`
"""
return self._ancestors
@ancestors.setter
def ancestors(self, ancestors: Iterable['Component']) -> None:
self._ancestors = SortedSet(ancestors)
@property
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'component')
@serializable.xml_sequence(2)
def descendants(self) -> "SortedSet['Component']":
"""
Descendants are the exact opposite of ancestors. This provides a way to document all forks (and their forks) of
an original or root component.
Returns:
Set of `Component`
"""
return self._descendants
@descendants.setter
def descendants(self, descendants: Iterable['Component']) -> None:
self._descendants = SortedSet(descendants)
@property
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'component')
@serializable.xml_sequence(3)
def variants(self) -> "SortedSet['Component']":
"""
Variants describe relations where the relationship between the components are not known. For example, if
Component A contains nearly identical code to Component B. They are both related, but it is unclear if one is
derived from the other, or if they share a common ancestor.
Returns:
Set of `Component`
"""
return self._variants
@variants.setter
def variants(self, variants: Iterable['Component']) -> None:
self._variants = SortedSet(variants)
@property
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'commit')
@serializable.xml_sequence(4)
def commits(self) -> 'SortedSet[Commit]':
"""
A list of zero or more commits which provide a trail describing how the component deviates from an ancestor,
descendant, or variant.
Returns:
Set of `Commit`
"""
return self._commits
@commits.setter
def commits(self, commits: Iterable[Commit]) -> None:
self._commits = SortedSet(commits)
@property
@serializable.view(SchemaVersion1Dot2)
@serializable.view(SchemaVersion1Dot3)
@serializable.view(SchemaVersion1Dot4)
@serializable.view(SchemaVersion1Dot5)
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'patch')
@serializable.xml_sequence(5)
def patches(self) -> 'SortedSet[Patch]':
"""
A list of zero or more patches describing how the component deviates from an ancestor, descendant, or variant.
Patches may be complimentary to commits or may be used in place of commits.
Returns:
Set of `Patch`
"""
return self._patches
@patches.setter
def patches(self, patches: Iterable[Patch]) -> None:
self._patches = SortedSet(patches)
@property
@serializable.xml_sequence(6)
def notes(self) -> Optional[str]:
"""
Notes, observations, and other non-structured commentary describing the components pedigree.
Returns:
`str` if set else `None`
"""
return self._notes
@notes.setter
def notes(self, notes: Optional[str]) -> None:
self._notes = notes
def __comparable_tuple(self) -> _ComparableTuple:
return _ComparableTuple((
_ComparableTuple(self.ancestors),
_ComparableTuple(self.descendants),
_ComparableTuple(self.variants),
_ComparableTuple(self.commits),
_ComparableTuple(self.patches),
self.notes
))
def __eq__(self, other: object) -> bool:
if isinstance(other, Pedigree):
return self.__comparable_tuple() == other.__comparable_tuple()
return False
def __hash__(self) -> int:
return hash(self.__comparable_tuple())
def __repr__(self) -> str:
return f'<Pedigree id={id(self)}, hash={hash(self)}>'
@serializable.serializable_class
class Swid:
"""
Our internal representation of the `swidType` complex type.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/xml/#type_swidType
"""
def __init__(
self, *,
tag_id: str,
name: str,
version: Optional[str] = None,
tag_version: Optional[int] = None,
patch: Optional[bool] = None,
text: Optional[AttachedText] = None,
url: Optional[XsUri] = None,
) -> None:
self.tag_id = tag_id
self.name = name
self.version = version
self.tag_version = tag_version
self.patch = patch
self.text = text
self.url = url
@property
@serializable.xml_attribute()
def tag_id(self) -> str:
"""
Maps to the tagId of a SoftwareIdentity.
Returns:
`str`
"""
return self._tag_id
@tag_id.setter
def tag_id(self, tag_id: str) -> None:
self._tag_id = tag_id
@property
@serializable.xml_attribute()
def name(self) -> str:
"""
Maps to the name of a SoftwareIdentity.
Returns:
`str`
"""
return self._name
@name.setter
def name(self, name: str) -> None:
self._name = name
@property
@serializable.xml_attribute()
def version(self) -> Optional[str]:
"""
Maps to the version of a SoftwareIdentity.
Returns:
`str` if set else `None`.
"""
return self._version
@version.setter
def version(self, version: Optional[str]) -> None:
self._version = version
@property
@serializable.xml_attribute()
def tag_version(self) -> Optional[int]:
"""
Maps to the tagVersion of a SoftwareIdentity.
Returns:
`int` if set else `None`
"""
return self._tag_version
@tag_version.setter
def tag_version(self, tag_version: Optional[int]) -> None:
self._tag_version = tag_version
@property
@serializable.xml_attribute()
def patch(self) -> Optional[bool]:
"""
Maps to the patch of a SoftwareIdentity.
Returns:
`bool` if set else `None`
"""
return self._patch
@patch.setter
def patch(self, patch: Optional[bool]) -> None:
self._patch = patch
@property
def text(self) -> Optional[AttachedText]:
"""
Specifies the full content of the SWID tag.
Returns:
`AttachedText` if set else `None`
"""
return self._text
@text.setter
def text(self, text: Optional[AttachedText]) -> None:
self._text = text
@property
def url(self) -> Optional[XsUri]:
"""
The URL to the SWID file.
Returns:
`XsUri` if set else `None`
"""
return self._url
@url.setter
def url(self, url: Optional[XsUri]) -> None:
self._url = url
def __comparable_tuple(self) -> _ComparableTuple:
return _ComparableTuple((
self.tag_id,
self.name, self.version,
self.tag_version,
self.patch,
self.url,
self.text,
))
def __eq__(self, other: object) -> bool:
if isinstance(other, Swid):
return self.__comparable_tuple() == other.__comparable_tuple()
return False
def __hash__(self) -> int:
return hash(self.__comparable_tuple())
def __repr__(self) -> str:
return f'<Swid tagId={self.tag_id}, name={self.name}, version={self.version}>'
@serializable.serializable_class
class OmniborId(serializable.helpers.BaseHelper):
"""
Helper class that allows us to perform validation on data strings that must conform to
https://www.iana.org/assignments/uri-schemes/prov/gitoid.
"""
_VALID_OMNIBOR_ID_REGEX = re.compile(r'^gitoid:(blob|tree|commit|tag):sha(1|256):([a-z0-9]+)$')
def __init__(self, id: str) -> None:
if OmniborId._VALID_OMNIBOR_ID_REGEX.match(id) is None:
raise InvalidOmniBorIdException(
f'Supplied value "{id} does not meet format specification.'
)
self._id = id
@property
@serializable.json_name('.')
@serializable.xml_name('.')
def id(self) -> str:
return self._id
@classmethod
def serialize(cls, o: Any) -> str:
if isinstance(o, OmniborId):
return str(o)
raise SerializationOfUnexpectedValueException(
f'Attempt to serialize a non-OmniBorId: {o!r}')
@classmethod
def deserialize(cls, o: Any) -> 'OmniborId':
try:
return OmniborId(id=str(o))
except ValueError as err:
raise CycloneDxDeserializationException(
f'OmniBorId string supplied does not parse: {o!r}'
) from err
def __eq__(self, other: Any) -> bool:
if isinstance(other, OmniborId):
return self._id == other._id
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, OmniborId):
return self._id < other._id
return NotImplemented
def __hash__(self) -> int:
return hash(self._id)
def __repr__(self) -> str:
return f'<OmniBorId {self._id}>'
def __str__(self) -> str:
return self._id
@serializable.serializable_class
class Swhid(serializable.helpers.BaseHelper):
"""
Helper class that allows us to perform validation on data strings that must conform to
https://docs.softwareheritage.org/devel/swh-model/persistent-identifiers.html.
"""
_VALID_SWHID_REGEX = re.compile(r'^swh:1:(cnp|rel|rev|dir|cnt):([0-9a-z]{40})(.*)?$')
def __init__(self, id: str) -> None:
if Swhid._VALID_SWHID_REGEX.match(id) is None:
raise InvalidSwhidException(
f'Supplied value "{id} does not meet format specification.'
)
self._id = id
@property
@serializable.json_name('.')
@serializable.xml_name('.')
def id(self) -> str:
return self._id
@classmethod
def serialize(cls, o: Any) -> str:
if isinstance(o, Swhid):
return str(o)
raise SerializationOfUnexpectedValueException(
f'Attempt to serialize a non-Swhid: {o!r}')
@classmethod
def deserialize(cls, o: Any) -> 'Swhid':
try:
return Swhid(id=str(o))
except ValueError as err:
raise CycloneDxDeserializationException(
f'Swhid string supplied does not parse: {o!r}'
) from err
def __eq__(self, other: Any) -> bool:
if isinstance(other, Swhid):
return self._id == other._id
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, Swhid):
return self._id < other._id
return NotImplemented
def __hash__(self) -> int:
return hash(self._id)
def __repr__(self) -> str:
return f'<Swhid {self._id}>'
def __str__(self) -> str:
return self._id
@serializable.serializable_class
class Component(Dependable):
"""
This is our internal representation of a Component within a Bom.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/#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(f'Supplied file path {absolute_file_path!r} does not exist')
sha1_hash: str = _file_sha1sum(absolute_file_path)
return Component(
name=path_for_bom if path_for_bom else absolute_file_path,
version=f'0.0.0-{sha1_hash[0:12]}',
hashes=[
HashType(alg=HashAlgorithm.SHA_1, content=sha1_hash)
],
type=ComponentType.FILE, purl=PackageURL(
type='generic', name=path_for_bom if path_for_bom else absolute_file_path,
version=f'0.0.0-{sha1_hash[0:12]}'
)
)
def __init__(
self, *,
name: str,
type: ComponentType = ComponentType.LIBRARY,
mime_type: Optional[str] = None,
bom_ref: Optional[Union[str, BomRef]] = None,
supplier: Optional[OrganizationalEntity] = None,
publisher: Optional[str] = None,
group: Optional[str] = None,
version: Optional[str] = None,
description: Optional[str] = None,
scope: Optional[ComponentScope] = None,
hashes: Optional[Iterable[HashType]] = None,
licenses: Optional[Iterable[License]] = None,
copyright: Optional[str] = None,
purl: Optional[PackageURL] = None,
external_references: Optional[Iterable[ExternalReference]] = None,
properties: Optional[Iterable[Property]] = None,
release_notes: Optional[ReleaseNotes] = None,
cpe: Optional[str] = None,
swid: Optional[Swid] = None,
pedigree: Optional[Pedigree] = None,
components: Optional[Iterable['Component']] = None,
evidence: Optional[ComponentEvidence] = None,
modified: bool = False,
manufacturer: Optional[OrganizationalEntity] = None,
authors: Optional[Iterable[OrganizationalContact]] = None,
omnibor_ids: Optional[Iterable[OmniborId]] = None,
swhids: Optional[Iterable[Swhid]] = None,
crypto_properties: Optional[CryptoProperties] = None,
tags: Optional[Iterable[str]] = None,
# Deprecated in v1.6
author: Optional[str] = None,
) -> None:
self.type = type
self.mime_type = mime_type
self._bom_ref = _bom_ref_from_str(bom_ref)
self.supplier = supplier
self.manufacturer = manufacturer
self.authors = authors or [] # type:ignore[assignment]
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 [] # type:ignore[assignment]
self.licenses = licenses or [] # type:ignore[assignment]
self.copyright = copyright
self.cpe = cpe
self.purl = purl
self.omnibor_ids = omnibor_ids or [] # type:ignore[assignment]
self.swhids = swhids or [] # type:ignore[assignment]
self.swid = swid
self.modified = modified
self.pedigree = pedigree
self.external_references = external_references or [] # type:ignore[assignment]
self.properties = properties or [] # type:ignore[assignment]
self.components = components or [] # type:ignore[assignment]
self.evidence = evidence
self.release_notes = release_notes
self.crypto_properties = crypto_properties
self.tags = tags or [] # type:ignore[assignment]
if modified:
warn('`.component.modified` is deprecated from CycloneDX v1.3 onwards. '
'Please use `@.pedigree` instead.', DeprecationWarning)
if author:
warn('`.component.author` is deprecated from CycloneDX v1.6 onwards. '
'Please use `@.authors` or `@.manufacturer` instead.', DeprecationWarning)
@property
@serializable.type_mapping(_ComponentTypeSerializationHelper)
@serializable.xml_attribute()
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, type: ComponentType) -> None:
self._type = type
@property
@serializable.xml_string(serializable.XmlStringSerializationType.TOKEN)
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
@serializable.json_name('bom-ref')
@serializable.type_mapping(BomRef)
@serializable.view(SchemaVersion1Dot1)
@serializable.view(SchemaVersion1Dot2)
@serializable.view(SchemaVersion1Dot3)
@serializable.view(SchemaVersion1Dot4)
@serializable.view(SchemaVersion1Dot5)
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_attribute()
@serializable.xml_name('bom-ref')
def bom_ref(self) -> BomRef:
"""
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:
`BomRef`
"""
return self._bom_ref
@property
@serializable.view(SchemaVersion1Dot2)
@serializable.view(SchemaVersion1Dot3)
@serializable.view(SchemaVersion1Dot4)
@serializable.view(SchemaVersion1Dot5)
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_sequence(1)
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
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_sequence(2)
def manufacturer(self) -> Optional[OrganizationalEntity]:
"""
The organization that created the component.
Manufacturer is common in components created through automated processes.
Components created through manual means may have `@.authors` instead.
Returns:
`OrganizationalEntity` if set else `None`
"""
return self._manufacturer
@manufacturer.setter
def manufacturer(self, manufacturer: Optional[OrganizationalEntity]) -> None:
self._manufacturer = manufacturer
@property
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'author')
@serializable.xml_sequence(3)
def authors(self) -> 'SortedSet[OrganizationalContact]':
"""
The person(s) who created the component.
Authors are common in components created through manual processes.
Components created through automated means may have `@.manufacturer` instead.
Returns:
`Iterable[OrganizationalContact]` if set else `None`
"""
return self._authors
@authors.setter
def authors(self, authors: Iterable[OrganizationalContact]) -> None:
self._authors = SortedSet(authors)
@property
@serializable.view(SchemaVersion1Dot2)
@serializable.view(SchemaVersion1Dot3)
@serializable.view(SchemaVersion1Dot4)
@serializable.view(SchemaVersion1Dot5)
@serializable.view(SchemaVersion1Dot6) # todo: this is deprecated in v1.6?
@serializable.xml_sequence(4)
@serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
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
@serializable.xml_sequence(5)
@serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
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
@serializable.xml_sequence(6)
@serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
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
@serializable.xml_sequence(7)
@serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
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
@serializable.include_none(SchemaVersion1Dot0, '')
@serializable.include_none(SchemaVersion1Dot1, '')
@serializable.include_none(SchemaVersion1Dot2, '')
@serializable.include_none(SchemaVersion1Dot3, '')
@serializable.xml_sequence(8)
@serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
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:
if version and len(version) > 1024:
warn('`.component.version`has a maximum length of 1024 from CycloneDX v1.6 onwards.', UserWarning)
self._version = version
@property
@serializable.xml_sequence(9)
@serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
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
@serializable.type_mapping(_ComponentScopeSerializationHelper)
@serializable.xml_sequence(10)
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
@serializable.type_mapping(_HashTypeRepositorySerializationHelper)
@serializable.xml_sequence(11)
def hashes(self) -> 'SortedSet[HashType]':
"""
Optional list of hashes that help specify the integrity of this Component.
Returns:
Set of `HashType`
"""
return self._hashes
@hashes.setter
def hashes(self, hashes: Iterable[HashType]) -> None:
self._hashes = SortedSet(hashes)
@property
@serializable.view(SchemaVersion1Dot1)
@serializable.view(SchemaVersion1Dot2)
@serializable.view(SchemaVersion1Dot3)
@serializable.view(SchemaVersion1Dot4)
@serializable.view(SchemaVersion1Dot5)
@serializable.view(SchemaVersion1Dot6)
@serializable.type_mapping(_LicenseRepositorySerializationHelper)
@serializable.xml_sequence(12)
def licenses(self) -> LicenseRepository:
"""
A optional list of statements about how this Component is licensed.
Returns:
Set of `LicenseChoice`
"""
return self._licenses
@licenses.setter
def licenses(self, licenses: Iterable[License]) -> None:
self._licenses = LicenseRepository(licenses)
@property
@serializable.xml_sequence(13)
@serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
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
@serializable.xml_sequence(14)
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
@serializable.type_mapping(PackageUrlSH)
@serializable.xml_sequence(15)
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
@serializable.json_name('omniborId')
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_array(serializable.XmlArraySerializationType.FLAT, child_name='omniborId')
@serializable.xml_sequence(16)
def omnibor_ids(self) -> 'SortedSet[OmniborId]':
"""
Specifies the OmniBOR Artifact ID. The OmniBOR, if specified, MUST be valid and conform to the specification
defined at: https://www.iana.org/assignments/uri-schemes/prov/gitoid
Returns:
`Iterable[str]` or `None`
"""
return self._omnibor_ids
@omnibor_ids.setter
def omnibor_ids(self, omnibor_ids: Iterable[OmniborId]) -> None:
self._omnibor_ids = SortedSet(omnibor_ids)
@property
@serializable.json_name('swhid')
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_array(serializable.XmlArraySerializationType.FLAT, child_name='swhid')
@serializable.xml_sequence(17)
def swhids(self) -> 'SortedSet[Swhid]':
"""
Specifies the Software Heritage persistent identifier (SWHID). The SWHID, if specified, MUST be valid and
conform to the specification defined at:
https://docs.softwareheritage.org/devel/swh-model/persistent-identifiers.html
Returns:
`Iterable[Swhid]` if set else `None`
"""
return self._swhids
@swhids.setter
def swhids(self, swhids: Iterable[Swhid]) -> None:
self._swhids = SortedSet(swhids)
@property
@serializable.view(SchemaVersion1Dot2)
@serializable.view(SchemaVersion1Dot3)
@serializable.view(SchemaVersion1Dot4)
@serializable.view(SchemaVersion1Dot5)
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_sequence(18)
def swid(self) -> Optional[Swid]:
"""
Specifies metadata and content for ISO-IEC 19770-2 Software Identification (SWID) Tags.
Returns:
`Swid` if set else `None`
"""
return self._swid
@swid.setter
def swid(self, swid: Optional[Swid]) -> None:
self._swid = swid
@property
@serializable.view(SchemaVersion1Dot0) # todo: Deprecated in v1.3
@serializable.xml_sequence(19)
def modified(self) -> bool:
return self._modified
@modified.setter
def modified(self, modified: bool) -> None:
self._modified = modified
@property
@serializable.view(SchemaVersion1Dot1)
@serializable.view(SchemaVersion1Dot2)
@serializable.view(SchemaVersion1Dot3)
@serializable.view(SchemaVersion1Dot4)
@serializable.view(SchemaVersion1Dot5)
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_sequence(20)
def pedigree(self) -> Optional[Pedigree]:
"""
Component pedigree is a way to document complex supply chain scenarios where components are created,
distributed, modified, redistributed, combined with other components, etc.
Returns:
`Pedigree` if set else `None`
"""
return self._pedigree
@pedigree.setter
def pedigree(self, pedigree: Optional[Pedigree]) -> None:
self._pedigree = pedigree
@property
@serializable.view(SchemaVersion1Dot1)
@serializable.view(SchemaVersion1Dot2)
@serializable.view(SchemaVersion1Dot3)
@serializable.view(SchemaVersion1Dot4)
@serializable.view(SchemaVersion1Dot5)
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'reference')
@serializable.xml_sequence(21)
def external_references(self) -> 'SortedSet[ExternalReference]':
"""
Provides the ability to document external references related to the component or to the project the component
describes.
Returns:
Set of `ExternalReference`
"""
return self._external_references
@external_references.setter
def external_references(self, external_references: Iterable[ExternalReference]) -> None:
self._external_references = SortedSet(external_references)
@property
@serializable.view(SchemaVersion1Dot3)
@serializable.view(SchemaVersion1Dot4)
@serializable.view(SchemaVersion1Dot5)
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'property')
@serializable.xml_sequence(22)
def properties(self) -> 'SortedSet[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:
Set of `Property`
"""
return self._properties
@properties.setter
def properties(self, properties: Iterable[Property]) -> None:
self._properties = SortedSet(properties)
@property
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'component')
@serializable.xml_sequence(23)
def components(self) -> "SortedSet['Component']":
"""
A list of software and hardware components included in the parent component. This is not a dependency tree. It
provides a way to specify a hierarchical representation of component assemblies, similar to system -> subsystem
-> parts assembly in physical supply chains.
Returns:
Set of `Component`
"""
return self._components
@components.setter
def components(self, components: Iterable['Component']) -> None:
self._components = SortedSet(components)
@property
@serializable.view(SchemaVersion1Dot3)
@serializable.view(SchemaVersion1Dot4)
@serializable.view(SchemaVersion1Dot5)
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_sequence(24)
def evidence(self) -> Optional[ComponentEvidence]:
"""
Provides the ability to document evidence collected through various forms of extraction or analysis.
Returns:
`ComponentEvidence` if set else `None`
"""
return self._evidence
@evidence.setter
def evidence(self, evidence: Optional[ComponentEvidence]) -> None:
self._evidence = evidence
@property
@serializable.view(SchemaVersion1Dot4)
@serializable.view(SchemaVersion1Dot5)
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_sequence(25)
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
# @property
# ...
# @serializable.view(SchemaVersion1Dot5)
# @serializable.xml_sequence(22)
# def model_card(self) -> ...:
# ... # TODO since CDX1.5
#
# @model_card.setter
# def model_card(self, ...) -> None:
# ... # TODO since CDX1.5
# @property
# ...
# @serializable.view(SchemaVersion1Dot5)
# @serializable.xml_sequence(23)
# def data(self) -> ...:
# ... # TODO since CDX1.5
#
# @data.setter
# def data(self, ...) -> None:
# ... # TODO since CDX1.5
@property
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_sequence(30)
def crypto_properties(self) -> Optional[CryptoProperties]:
"""
Cryptographic assets have properties that uniquely define them and that make them actionable for further
reasoning. As an example, it makes a difference if one knows the algorithm family (e.g. AES) or the specific
variant or instantiation (e.g. AES-128-GCM). This is because the security level and the algorithm primitive
(authenticated encryption) is only defined by the definition of the algorithm variant. The presence of a weak
cryptographic algorithm like SHA1 vs. HMAC-SHA1 also makes a difference.
Returns:
`CryptoProperties` or `None`
"""
return self._crypto_properties
@crypto_properties.setter
def crypto_properties(self, crypto_properties: Optional[CryptoProperties]) -> None:
self._crypto_properties = crypto_properties
@property
@serializable.view(SchemaVersion1Dot6)
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'tag')
@serializable.xml_sequence(31)
def tags(self) -> 'SortedSet[str]':
"""
Textual strings that aid in discovery, search, and retrieval of the associated object.
Tags often serve as a way to group or categorize similar or related objects by various attributes.
Returns:
`Iterable[str]`
"""
return self._tags
@tags.setter
def tags(self, tags: Iterable[str]) -> None:
self._tags = SortedSet(tags)
def get_all_nested_components(self, include_self: bool = False) -> Set['Component']:
components = set()
if include_self:
components.add(self)
for c in self.components:
components.update(c.get_all_nested_components(include_self=True))
return components
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 __comparable_tuple(self) -> _ComparableTuple:
return _ComparableTuple((
self.type, self.group, self.name, self.version,
self.bom_ref.value,
None if self.purl is None else _ComparablePackageURL(self.purl),
self.swid, self.cpe, _ComparableTuple(self.swhids),
self.supplier, self.author, self.publisher,
self.description,
self.mime_type, self.scope, _ComparableTuple(self.hashes),
_ComparableTuple(self.licenses), self.copyright,
self.pedigree,
_ComparableTuple(self.external_references), _ComparableTuple(self.properties),
_ComparableTuple(self.components), self.evidence, self.release_notes, self.modified,
_ComparableTuple(self.authors), _ComparableTuple(self.omnibor_ids), self.manufacturer,
self.crypto_properties, _ComparableTuple(self.tags),
))
def __eq__(self, other: object) -> bool:
if isinstance(other, Component):
return self.__comparable_tuple() == other.__comparable_tuple()
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, Component):
return self.__comparable_tuple() < other.__comparable_tuple()
return NotImplemented
def __hash__(self) -> int:
return hash(self.__comparable_tuple())
def __repr__(self) -> str:
return f'<Component bom-ref={self.bom_ref!r}, group={self.group}, name={self.name}, ' \
f'version={self.version}, type={self.type}>'
|