diff --git a/cyclonedx/contrib/bom/utils.py b/cyclonedx/contrib/bom/utils.py
index 9e6712ab..95623949 100644
--- a/cyclonedx/contrib/bom/utils.py
+++ b/cyclonedx/contrib/bom/utils.py
@@ -22,7 +22,7 @@
'BomDependencyGraphFlatMerger',
]
-from collections.abc import Iterable
+from collections.abc import Generator, Iterable
from itertools import chain
from random import random
from typing import TYPE_CHECKING, Any
@@ -85,6 +85,17 @@ def reset(self) -> None:
def _make_unique(self) -> str:
return f'{self._prefix}{str(random())[1:]}{str(random())[1:]}' # nosec B311
+ @classmethod
+ def _get_annotation_bom_refs(cls, bom: 'Bom') -> Generator['BomRef', None, None]:
+ for a in bom.annotations:
+ yield a.bom_ref
+ annotator = a.annotator
+ if annotator:
+ if annotator.component:
+ yield from (c.bom_ref for c in annotator.component.iter_all_nested_components(include_self=True))
+ elif annotator.service:
+ yield annotator.service.bom_ref
+
@classmethod
def from_bom(cls, bom: 'Bom', prefix: str = 'BomRef') -> 'BomRefDiscriminator':
"""
@@ -95,11 +106,13 @@ def from_bom(cls, bom: 'Bom', prefix: str = 'BomRef') -> 'BomRefDiscriminator':
* :attr:`cyclonedx.model.bom.Bom.components`
* :attr:`cyclonedx.model.bom.Bom.services`
* :attr:`cyclonedx.model.bom.Bom.vulnerabilities`
+ * :attr:`cyclonedx.model.bom.Bom.annotations`
"""
return cls(chain(
(c.bom_ref for c in bom._get_all_components()),
(s.bom_ref for s in bom.services),
(v.bom_ref for v in bom.vulnerabilities),
+ cls._get_annotation_bom_refs(bom),
), prefix)
diff --git a/cyclonedx/model/annotation.py b/cyclonedx/model/annotation.py
new file mode 100644
index 00000000..1d2c2ba1
--- /dev/null
+++ b/cyclonedx/model/annotation.py
@@ -0,0 +1,296 @@
+# 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.
+
+from collections.abc import Iterable
+from datetime import datetime
+from typing import Any, Optional, Union
+from xml.etree.ElementTree import Element as XmlElement # nosec B405
+
+import py_serializable as serializable
+from py_serializable.helpers import XsdDateTime
+from sortedcontainers import SortedSet
+
+from .._internal.bom_ref import bom_ref_from_str as _bom_ref_from_str
+from .._internal.compare import ComparableTuple as _ComparableTuple
+from ..exception.serialization import SerializationOfUnexpectedValueException
+from .bom_ref import BomRef
+from .component import Component
+from .contact import OrganizationalContact, OrganizationalEntity
+from .service import Service
+
+
+class _SubjectsSerializationHelper(serializable.helpers.BaseHelper):
+ """THIS CLASS IS NON-PUBLIC API
+
+ JSON: subjects is a plain list of bom-ref strings.
+ XML: subjects wrapper element containing children.
+ """
+
+ @classmethod
+ def json_normalize(cls, o: Any, *,
+ view: Optional[type[serializable.ViewType]] = None,
+ **__: Any) -> Optional[list[str]]:
+ if isinstance(o, (SortedSet, set, list)):
+ return [str(i) for i in o]
+ raise SerializationOfUnexpectedValueException(
+ f'Attempt to serialize a non-subjects collection: {o!r}')
+
+ @classmethod
+ def json_denormalize(cls, o: Any, **__: Any) -> set[BomRef]:
+ subjects: set[BomRef] = set()
+ if isinstance(o, list):
+ for v in o:
+ subjects.add(BomRef(value=str(v)))
+ return subjects
+
+ @classmethod
+ def xml_normalize(cls, o: Any, *,
+ element_name: str,
+ view: Optional[type[serializable.ViewType]] = None,
+ xmlns: Optional[str] = None,
+ **__: Any) -> Optional[XmlElement]:
+ if not o:
+ return None
+ elem = XmlElement(element_name)
+ ref_attr = f'{{{xmlns}}}ref' if xmlns else 'ref'
+ for b in o:
+ sub = XmlElement(f'{{{xmlns}}}subject' if xmlns else 'subject')
+ sub.set(ref_attr, str(b))
+ elem.append(sub)
+ return elem
+
+ @classmethod
+ def xml_denormalize(cls, o: XmlElement, *,
+ default_ns: Optional[str] = None,
+ **__: Any) -> set[BomRef]:
+ subjects: set[BomRef] = set()
+ ns_map = {'bom': default_ns} if default_ns else None
+ sub_elements = o.findall('bom:subject', ns_map) if ns_map else o.findall('subject')
+ for child in sub_elements:
+ ref_val = (child.get(f'{{{default_ns}}}ref') if default_ns else None) or child.get('ref')
+ if ref_val:
+ subjects.add(BomRef(value=ref_val))
+ return subjects
+
+
+@serializable.serializable_class(ignore_unknown_during_deserialization=True)
+class Annotator:
+ """
+ The organization, person, component, or service which created the textual content of the annotation.
+
+ .. note::
+ Exactly one of ``organization``, ``individual``, ``component``, or ``service`` must be provided.
+ While properties can be modified independently after construction, having none or multiple
+ set will produce schema-invalid output.
+ """
+
+ def __init__(
+ self, *,
+ organization: Optional[OrganizationalEntity] = None,
+ individual: Optional[OrganizationalContact] = None,
+ component: Optional[Component] = None,
+ service: Optional[Service] = None,
+ ) -> None:
+ if sum(x is not None for x in (organization, individual, component, service)) != 1:
+ raise ValueError('Exactly one of organization, individual, component, or service must be provided.')
+
+ self.organization = organization
+ self.individual = individual
+ self.component = component
+ self.service = service
+
+ @property
+ @serializable.xml_sequence(1)
+ def organization(self) -> Optional[OrganizationalEntity]:
+ return self._organization
+
+ @organization.setter
+ def organization(self, organization: Optional[OrganizationalEntity]) -> None:
+ self._organization = organization
+
+ @property
+ @serializable.xml_sequence(2)
+ def individual(self) -> Optional[OrganizationalContact]:
+ return self._individual
+
+ @individual.setter
+ def individual(self, individual: Optional[OrganizationalContact]) -> None:
+ self._individual = individual
+
+ @property
+ @serializable.xml_sequence(3)
+ def component(self) -> Optional[Component]:
+ return self._component
+
+ @component.setter
+ def component(self, component: Optional[Component]) -> None:
+ self._component = component
+
+ @property
+ @serializable.xml_sequence(4)
+ def service(self) -> Optional[Service]:
+ return self._service
+
+ @service.setter
+ def service(self, service: Optional[Service]) -> None:
+ self._service = service
+
+ def __comparable_tuple(self) -> _ComparableTuple:
+ return _ComparableTuple((
+ self.organization, self.individual, self.component, self.service
+ ))
+
+ def __eq__(self, other: object) -> bool:
+ if isinstance(other, Annotator):
+ return self.__comparable_tuple() == other.__comparable_tuple()
+ return False
+
+ def __lt__(self, other: Any) -> bool:
+ if isinstance(other, Annotator):
+ return self.__comparable_tuple() < other.__comparable_tuple()
+ return NotImplemented
+
+ def __hash__(self) -> int:
+ return hash(self.__comparable_tuple())
+
+ def __repr__(self) -> str:
+ return (
+ f''
+ )
+
+
+@serializable.serializable_class(ignore_unknown_during_deserialization=True)
+class Annotation:
+ """
+ A comment, note, explanation, or similar textual content which provides additional context
+ to the object(s) being annotated.
+
+ .. note::
+ While CycloneDX schema does not enforce ``minItems`` for subjects, an annotation with no subjects
+ is semantically meaningless and may produce invalid XML output.
+ """
+
+ def __init__(
+ self, *,
+ subjects: Iterable[Union[BomRef, str]],
+ annotator: Annotator,
+ timestamp: datetime,
+ text: str,
+ bom_ref: Optional[Union[str, BomRef]] = None,
+ ) -> None:
+ self._bom_ref = _bom_ref_from_str(bom_ref)
+ self.subjects = subjects
+ self.annotator = annotator
+ self.timestamp = timestamp
+ self.text = text
+
+ @property
+ @serializable.json_name('bom-ref')
+ @serializable.type_mapping(BomRef)
+ @serializable.xml_attribute()
+ @serializable.xml_name('bom-ref')
+ def bom_ref(self) -> BomRef:
+ """
+ An optional identifier which can be used to reference the annotation elsewhere in the BOM.
+ """
+ return self._bom_ref
+
+ @bom_ref.setter
+ def bom_ref(self, bom_ref: BomRef) -> None:
+ self._bom_ref = bom_ref
+
+ @property
+ @serializable.type_mapping(_SubjectsSerializationHelper)
+ @serializable.xml_sequence(1)
+ def subjects(self) -> 'SortedSet[BomRef]':
+ """
+ The object(s) in the BOM identified by its bom-ref.
+
+ .. note::
+ While CycloneDX schema does not enforce ``minItems`` for subjects, an annotation with no subjects
+ is semantically meaningless and may produce invalid XML output.
+ """
+ return self._subjects
+
+ @subjects.setter
+ def subjects(self, subjects: Iterable[Union[BomRef, str]]) -> None:
+ self._subjects = SortedSet(
+ s if isinstance(s, BomRef) else BomRef(value=str(s))
+ for s in subjects
+ )
+
+ @property
+ @serializable.xml_sequence(2)
+ def annotator(self) -> Annotator:
+ """
+ The organization, person, component, or service which created the textual content of the annotation.
+ """
+ return self._annotator
+
+ @annotator.setter
+ def annotator(self, annotator: Annotator) -> None:
+ self._annotator = annotator
+
+ @property
+ @serializable.type_mapping(XsdDateTime)
+ @serializable.xml_sequence(3)
+ def timestamp(self) -> datetime:
+ """
+ The date and time (timestamp) when the annotation was created.
+ """
+ return self._timestamp
+
+ @timestamp.setter
+ def timestamp(self, timestamp: datetime) -> None:
+ self._timestamp = timestamp
+
+ @property
+ @serializable.xml_sequence(4)
+ def text(self) -> str:
+ """
+ The textual content of the annotation.
+ """
+ return self._text
+
+ @text.setter
+ def text(self, text: str) -> None:
+ self._text = text
+
+ def __comparable_tuple(self) -> _ComparableTuple:
+ return _ComparableTuple((
+ self.bom_ref.value, _ComparableTuple(self.subjects),
+ self.annotator, self.timestamp, self.text
+ ))
+
+ def __eq__(self, other: object) -> bool:
+ if isinstance(other, Annotation):
+ return self.__comparable_tuple() == other.__comparable_tuple()
+ return False
+
+ def __lt__(self, other: Any) -> bool:
+ if isinstance(other, Annotation):
+ 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 --git a/cyclonedx/model/bom.py b/cyclonedx/model/bom.py
index 3f76c94a..9231514e 100644
--- a/cyclonedx/model/bom.py
+++ b/cyclonedx/model/bom.py
@@ -43,6 +43,7 @@
)
from ..serialization import UrnUuidHelper
from . import _BOM_LINK_PREFIX, ExternalReference, Property
+from .annotation import Annotation
from .bom_ref import BomRef
from .component import Component
from .contact import OrganizationalContact, OrganizationalEntity
@@ -444,6 +445,7 @@ def __init__(
vulnerabilities: Optional[Iterable[Vulnerability]] = None,
properties: Optional[Iterable[Property]] = None,
definitions: Optional[Definitions] = None,
+ annotations: Optional[Iterable[Annotation]] = None,
) -> None:
"""
Create a new Bom that you can manually/programmatically add data to later.
@@ -461,6 +463,7 @@ def __init__(
self.dependencies = dependencies or []
self.properties = properties or []
self.definitions = definitions or Definitions()
+ self.annotations = annotations or []
@property
@serializable.type_mapping(UrnUuidHelper)
@@ -655,16 +658,25 @@ def vulnerabilities(self) -> 'SortedSet[Vulnerability]':
def vulnerabilities(self, vulnerabilities: Iterable[Vulnerability]) -> None:
self._vulnerabilities = SortedSet(vulnerabilities)
- # @property
- # ...
- # @serializable.view(SchemaVersion1Dot5)
- # @serializable.xml_sequence(9)
- # def annotations(self) -> ...:
- # ... # TODO Since CDX 1.5
- #
- # @annotations.setter
- # def annotations(self, ...) -> None:
- # ... # TODO Since CDX 1.5
+ @property
+ @serializable.view(SchemaVersion1Dot5)
+ @serializable.view(SchemaVersion1Dot6)
+ @serializable.view(SchemaVersion1Dot7)
+ @serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'annotation')
+ @serializable.xml_sequence(90)
+ def annotations(self) -> 'SortedSet[Annotation]':
+ """
+ Comments, notes, explanations, or similar textual content which provides additional context
+ to the object(s) being annotated.
+
+ Returns:
+ Set of `Annotation`
+ """
+ return self._annotations
+
+ @annotations.setter
+ def annotations(self, annotations: Iterable[Annotation]) -> None:
+ self._annotations = SortedSet(annotations)
# @property
# ...
diff --git a/docs/schema-support.rst b/docs/schema-support.rst
index fe37633d..8b7aad40 100644
--- a/docs/schema-support.rst
+++ b/docs/schema-support.rst
@@ -50,7 +50,7 @@ This is a snapshot. See the API docs for the latest state.
| ``bom.vulnerabilities`` | Yes | Note: Prior to CycloneDX 1.4, these were present under ``bom.components`` via a schema extension. |
| | | Note: As of ``cyclonedx-python-lib`` ``>3.0.0``, Vulnerability are modelled differently |
+----------------------------+---------------+---------------------------------------------------------------------------------------------------+
-| ``bom.annotations`` | No | |
+| ``bom.annotations`` | Yes | Supported when outputting to Schema Version >= 1.5. Not supported: ``signature``. |
+----------------------------+---------------+---------------------------------------------------------------------------------------------------+
| ``bom.formulation`` | No | |
+----------------------------+---------------+---------------------------------------------------------------------------------------------------+
diff --git a/tests/_data/models.py b/tests/_data/models.py
index e2052878..ec585ebe 100644
--- a/tests/_data/models.py
+++ b/tests/_data/models.py
@@ -42,6 +42,7 @@
Property,
XsUri,
)
+from cyclonedx.model.annotation import Annotation, Annotator
from cyclonedx.model.bom import Bom, BomMetaData, DistributionConstraints, TlpClassification
from cyclonedx.model.bom_ref import BomRef
from cyclonedx.model.component import (
@@ -1679,6 +1680,90 @@ def get_bom_for_issue941_nested_dependencies_irreversible_migrate() -> Bom:
# ---
+def get_bom_with_annotations() -> Bom:
+ component = Component(
+ name='annotated-component',
+ version='1.0.0',
+ type=ComponentType.LIBRARY,
+ bom_ref='component-1',
+ )
+ service = Service(
+ name='annotated-service',
+ bom_ref='service-1',
+ )
+
+ annotation_org = Annotation(
+ bom_ref='annotation-1',
+ subjects=[component.bom_ref],
+ annotator=Annotator(
+ organization=OrganizationalEntity(
+ name='Acme, Inc.',
+ urls=[XsUri('https://example.com')],
+ )
+ ),
+ timestamp=datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
+ text='This is an annotation by an organization.',
+ )
+
+ annotation_ind = Annotation(
+ bom_ref='annotation-2',
+ subjects=[component.bom_ref, service.bom_ref],
+ annotator=Annotator(
+ individual=OrganizationalContact(
+ name='Jane Doe',
+ email='jane.doe@example.com',
+ )
+ ),
+ timestamp=datetime(2024, 1, 2, 12, 0, 0, tzinfo=timezone.utc),
+ text='This is an annotation by an individual.',
+ )
+
+ annotation_comp = Annotation(
+ bom_ref='annotation-3',
+ subjects=[component.bom_ref],
+ annotator=Annotator(
+ component=Component(
+ name='scanner',
+ version='2.0.0',
+ type=ComponentType.APPLICATION,
+ bom_ref='scanner-1',
+ )
+ ),
+ timestamp=datetime(2024, 1, 3, 12, 0, 0, tzinfo=timezone.utc),
+ text='This is an annotation by a component.',
+ )
+
+ annotation_srv = Annotation(
+ bom_ref='annotation-4',
+ subjects=[service.bom_ref],
+ annotator=Annotator(
+ service=Service(
+ name='auth-service',
+ bom_ref='auth-service-1',
+ )
+ ),
+ timestamp=datetime(2024, 1, 4, 12, 0, 0, tzinfo=timezone.utc),
+ text='This is an annotation by a service.',
+ )
+
+ return _make_bom(
+ components=[component],
+ services=[service],
+ dependencies=[
+ Dependency(ref=component.bom_ref),
+ Dependency(ref=service.bom_ref),
+ ],
+ annotations=[
+ annotation_org,
+ annotation_ind,
+ annotation_comp,
+ annotation_srv,
+ ],
+ )
+
+
+# ---
+
all_get_bom_funct_valid = tuple(
(n, f) for n, f in getmembers(sys.modules[__name__], isfunction)
if n.startswith('get_bom_') and not n.endswith('_invalid')
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.0.xml.bin b/tests/_data/snapshots/get_bom_with_annotations-1.0.xml.bin
new file mode 100644
index 00000000..fac4e945
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.0.xml.bin
@@ -0,0 +1,10 @@
+
+
+
+
+ annotated-component
+ 1.0.0
+ false
+
+
+
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.1.xml.bin b/tests/_data/snapshots/get_bom_with_annotations-1.1.xml.bin
new file mode 100644
index 00000000..bda510d6
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.1.xml.bin
@@ -0,0 +1,9 @@
+
+
+
+
+ annotated-component
+ 1.0.0
+
+
+
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.2.json.bin b/tests/_data/snapshots/get_bom_with_annotations-1.2.json.bin
new file mode 100644
index 00000000..2564d8f6
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.2.json.bin
@@ -0,0 +1,32 @@
+{
+ "components": [
+ {
+ "bom-ref": "component-1",
+ "name": "annotated-component",
+ "type": "library",
+ "version": "1.0.0"
+ }
+ ],
+ "dependencies": [
+ {
+ "ref": "component-1"
+ },
+ {
+ "ref": "service-1"
+ }
+ ],
+ "metadata": {
+ "timestamp": "2023-01-07T13:44:32.312678+00:00"
+ },
+ "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac",
+ "services": [
+ {
+ "bom-ref": "service-1",
+ "name": "annotated-service"
+ }
+ ],
+ "version": 1,
+ "$schema": "http://cyclonedx.org/schema/bom-1.2b.schema.json",
+ "bomFormat": "CycloneDX",
+ "specVersion": "1.2"
+}
\ No newline at end of file
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.2.xml.bin b/tests/_data/snapshots/get_bom_with_annotations-1.2.xml.bin
new file mode 100644
index 00000000..dec259f4
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.2.xml.bin
@@ -0,0 +1,21 @@
+
+
+
+ 2023-01-07T13:44:32.312678+00:00
+
+
+
+ annotated-component
+ 1.0.0
+
+
+
+
+ annotated-service
+
+
+
+
+
+
+
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.3.json.bin b/tests/_data/snapshots/get_bom_with_annotations-1.3.json.bin
new file mode 100644
index 00000000..810409f1
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.3.json.bin
@@ -0,0 +1,32 @@
+{
+ "components": [
+ {
+ "bom-ref": "component-1",
+ "name": "annotated-component",
+ "type": "library",
+ "version": "1.0.0"
+ }
+ ],
+ "dependencies": [
+ {
+ "ref": "component-1"
+ },
+ {
+ "ref": "service-1"
+ }
+ ],
+ "metadata": {
+ "timestamp": "2023-01-07T13:44:32.312678+00:00"
+ },
+ "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac",
+ "services": [
+ {
+ "bom-ref": "service-1",
+ "name": "annotated-service"
+ }
+ ],
+ "version": 1,
+ "$schema": "http://cyclonedx.org/schema/bom-1.3a.schema.json",
+ "bomFormat": "CycloneDX",
+ "specVersion": "1.3"
+}
\ No newline at end of file
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.3.xml.bin b/tests/_data/snapshots/get_bom_with_annotations-1.3.xml.bin
new file mode 100644
index 00000000..acac73a3
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.3.xml.bin
@@ -0,0 +1,21 @@
+
+
+
+ 2023-01-07T13:44:32.312678+00:00
+
+
+
+ annotated-component
+ 1.0.0
+
+
+
+
+ annotated-service
+
+
+
+
+
+
+
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.4.json.bin b/tests/_data/snapshots/get_bom_with_annotations-1.4.json.bin
new file mode 100644
index 00000000..94580ec1
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.4.json.bin
@@ -0,0 +1,32 @@
+{
+ "components": [
+ {
+ "bom-ref": "component-1",
+ "name": "annotated-component",
+ "type": "library",
+ "version": "1.0.0"
+ }
+ ],
+ "dependencies": [
+ {
+ "ref": "component-1"
+ },
+ {
+ "ref": "service-1"
+ }
+ ],
+ "metadata": {
+ "timestamp": "2023-01-07T13:44:32.312678+00:00"
+ },
+ "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac",
+ "services": [
+ {
+ "bom-ref": "service-1",
+ "name": "annotated-service"
+ }
+ ],
+ "version": 1,
+ "$schema": "http://cyclonedx.org/schema/bom-1.4.schema.json",
+ "bomFormat": "CycloneDX",
+ "specVersion": "1.4"
+}
\ No newline at end of file
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.4.xml.bin b/tests/_data/snapshots/get_bom_with_annotations-1.4.xml.bin
new file mode 100644
index 00000000..ab0637a3
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.4.xml.bin
@@ -0,0 +1,21 @@
+
+
+
+ 2023-01-07T13:44:32.312678+00:00
+
+
+
+ annotated-component
+ 1.0.0
+
+
+
+
+ annotated-service
+
+
+
+
+
+
+
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.5.json.bin b/tests/_data/snapshots/get_bom_with_annotations-1.5.json.bin
new file mode 100644
index 00000000..338b2be3
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.5.json.bin
@@ -0,0 +1,105 @@
+{
+ "annotations": [
+ {
+ "annotator": {
+ "organization": {
+ "name": "Acme, Inc.",
+ "url": [
+ "https://example.com"
+ ]
+ }
+ },
+ "bom-ref": "annotation-1",
+ "subjects": [
+ "component-1"
+ ],
+ "text": "This is an annotation by an organization.",
+ "timestamp": "2024-01-01T12:00:00+00:00"
+ },
+ {
+ "annotator": {
+ "individual": {
+ "email": "jane.doe@example.com",
+ "name": "Jane Doe"
+ }
+ },
+ "bom-ref": "annotation-2",
+ "subjects": [
+ "component-1",
+ "service-1"
+ ],
+ "text": "This is an annotation by an individual.",
+ "timestamp": "2024-01-02T12:00:00+00:00"
+ },
+ {
+ "annotator": {
+ "component": {
+ "bom-ref": "scanner-1",
+ "name": "scanner",
+ "type": "application",
+ "version": "2.0.0"
+ }
+ },
+ "bom-ref": "annotation-3",
+ "subjects": [
+ "component-1"
+ ],
+ "text": "This is an annotation by a component.",
+ "timestamp": "2024-01-03T12:00:00+00:00"
+ },
+ {
+ "annotator": {
+ "service": {
+ "bom-ref": "auth-service-1",
+ "name": "auth-service"
+ }
+ },
+ "bom-ref": "annotation-4",
+ "subjects": [
+ "service-1"
+ ],
+ "text": "This is an annotation by a service.",
+ "timestamp": "2024-01-04T12:00:00+00:00"
+ }
+ ],
+ "components": [
+ {
+ "bom-ref": "component-1",
+ "name": "annotated-component",
+ "type": "library",
+ "version": "1.0.0"
+ }
+ ],
+ "dependencies": [
+ {
+ "ref": "component-1"
+ },
+ {
+ "ref": "service-1"
+ }
+ ],
+ "metadata": {
+ "timestamp": "2023-01-07T13:44:32.312678+00:00"
+ },
+ "properties": [
+ {
+ "name": "key1",
+ "value": "val1"
+ },
+ {
+ "name": "key2",
+ "value": "val2"
+ }
+ ],
+ "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac",
+ "services": [
+ {
+ "bom-ref": "service-1",
+ "name": "annotated-service"
+ }
+ ],
+ "version": 1,
+ "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
+ "bomFormat": "CycloneDX",
+ "specVersion": "1.5"
+}
\ No newline at end of file
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.5.xml.bin b/tests/_data/snapshots/get_bom_with_annotations-1.5.xml.bin
new file mode 100644
index 00000000..722e628d
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.5.xml.bin
@@ -0,0 +1,79 @@
+
+
+
+ 2023-01-07T13:44:32.312678+00:00
+
+
+
+ annotated-component
+ 1.0.0
+
+
+
+
+ annotated-service
+
+
+
+
+
+
+
+ val1
+ val2
+
+
+
+
+
+
+
+
+ Acme, Inc.
+ https://example.com
+
+
+ 2024-01-01T12:00:00+00:00
+ This is an annotation by an organization.
+
+
+
+
+
+
+
+
+ Jane Doe
+ jane.doe@example.com
+
+
+ 2024-01-02T12:00:00+00:00
+ This is an annotation by an individual.
+
+
+
+
+
+
+
+ scanner
+ 2.0.0
+
+
+ 2024-01-03T12:00:00+00:00
+ This is an annotation by a component.
+
+
+
+
+
+
+
+ auth-service
+
+
+ 2024-01-04T12:00:00+00:00
+ This is an annotation by a service.
+
+
+
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.6.json.bin b/tests/_data/snapshots/get_bom_with_annotations-1.6.json.bin
new file mode 100644
index 00000000..be35a6b3
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.6.json.bin
@@ -0,0 +1,105 @@
+{
+ "annotations": [
+ {
+ "annotator": {
+ "organization": {
+ "name": "Acme, Inc.",
+ "url": [
+ "https://example.com"
+ ]
+ }
+ },
+ "bom-ref": "annotation-1",
+ "subjects": [
+ "component-1"
+ ],
+ "text": "This is an annotation by an organization.",
+ "timestamp": "2024-01-01T12:00:00+00:00"
+ },
+ {
+ "annotator": {
+ "individual": {
+ "email": "jane.doe@example.com",
+ "name": "Jane Doe"
+ }
+ },
+ "bom-ref": "annotation-2",
+ "subjects": [
+ "component-1",
+ "service-1"
+ ],
+ "text": "This is an annotation by an individual.",
+ "timestamp": "2024-01-02T12:00:00+00:00"
+ },
+ {
+ "annotator": {
+ "component": {
+ "bom-ref": "scanner-1",
+ "name": "scanner",
+ "type": "application",
+ "version": "2.0.0"
+ }
+ },
+ "bom-ref": "annotation-3",
+ "subjects": [
+ "component-1"
+ ],
+ "text": "This is an annotation by a component.",
+ "timestamp": "2024-01-03T12:00:00+00:00"
+ },
+ {
+ "annotator": {
+ "service": {
+ "bom-ref": "auth-service-1",
+ "name": "auth-service"
+ }
+ },
+ "bom-ref": "annotation-4",
+ "subjects": [
+ "service-1"
+ ],
+ "text": "This is an annotation by a service.",
+ "timestamp": "2024-01-04T12:00:00+00:00"
+ }
+ ],
+ "components": [
+ {
+ "bom-ref": "component-1",
+ "name": "annotated-component",
+ "type": "library",
+ "version": "1.0.0"
+ }
+ ],
+ "dependencies": [
+ {
+ "ref": "component-1"
+ },
+ {
+ "ref": "service-1"
+ }
+ ],
+ "metadata": {
+ "timestamp": "2023-01-07T13:44:32.312678+00:00"
+ },
+ "properties": [
+ {
+ "name": "key1",
+ "value": "val1"
+ },
+ {
+ "name": "key2",
+ "value": "val2"
+ }
+ ],
+ "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac",
+ "services": [
+ {
+ "bom-ref": "service-1",
+ "name": "annotated-service"
+ }
+ ],
+ "version": 1,
+ "$schema": "http://cyclonedx.org/schema/bom-1.6.schema.json",
+ "bomFormat": "CycloneDX",
+ "specVersion": "1.6"
+}
\ No newline at end of file
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.6.xml.bin b/tests/_data/snapshots/get_bom_with_annotations-1.6.xml.bin
new file mode 100644
index 00000000..379cc6d4
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.6.xml.bin
@@ -0,0 +1,79 @@
+
+
+
+ 2023-01-07T13:44:32.312678+00:00
+
+
+
+ annotated-component
+ 1.0.0
+
+
+
+
+ annotated-service
+
+
+
+
+
+
+
+ val1
+ val2
+
+
+
+
+
+
+
+
+ Acme, Inc.
+ https://example.com
+
+
+ 2024-01-01T12:00:00+00:00
+ This is an annotation by an organization.
+
+
+
+
+
+
+
+
+ Jane Doe
+ jane.doe@example.com
+
+
+ 2024-01-02T12:00:00+00:00
+ This is an annotation by an individual.
+
+
+
+
+
+
+
+ scanner
+ 2.0.0
+
+
+ 2024-01-03T12:00:00+00:00
+ This is an annotation by a component.
+
+
+
+
+
+
+
+ auth-service
+
+
+ 2024-01-04T12:00:00+00:00
+ This is an annotation by a service.
+
+
+
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.7.json.bin b/tests/_data/snapshots/get_bom_with_annotations-1.7.json.bin
new file mode 100644
index 00000000..21eaaa78
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.7.json.bin
@@ -0,0 +1,105 @@
+{
+ "annotations": [
+ {
+ "annotator": {
+ "organization": {
+ "name": "Acme, Inc.",
+ "url": [
+ "https://example.com"
+ ]
+ }
+ },
+ "bom-ref": "annotation-1",
+ "subjects": [
+ "component-1"
+ ],
+ "text": "This is an annotation by an organization.",
+ "timestamp": "2024-01-01T12:00:00+00:00"
+ },
+ {
+ "annotator": {
+ "individual": {
+ "email": "jane.doe@example.com",
+ "name": "Jane Doe"
+ }
+ },
+ "bom-ref": "annotation-2",
+ "subjects": [
+ "component-1",
+ "service-1"
+ ],
+ "text": "This is an annotation by an individual.",
+ "timestamp": "2024-01-02T12:00:00+00:00"
+ },
+ {
+ "annotator": {
+ "component": {
+ "bom-ref": "scanner-1",
+ "name": "scanner",
+ "type": "application",
+ "version": "2.0.0"
+ }
+ },
+ "bom-ref": "annotation-3",
+ "subjects": [
+ "component-1"
+ ],
+ "text": "This is an annotation by a component.",
+ "timestamp": "2024-01-03T12:00:00+00:00"
+ },
+ {
+ "annotator": {
+ "service": {
+ "bom-ref": "auth-service-1",
+ "name": "auth-service"
+ }
+ },
+ "bom-ref": "annotation-4",
+ "subjects": [
+ "service-1"
+ ],
+ "text": "This is an annotation by a service.",
+ "timestamp": "2024-01-04T12:00:00+00:00"
+ }
+ ],
+ "components": [
+ {
+ "bom-ref": "component-1",
+ "name": "annotated-component",
+ "type": "library",
+ "version": "1.0.0"
+ }
+ ],
+ "dependencies": [
+ {
+ "ref": "component-1"
+ },
+ {
+ "ref": "service-1"
+ }
+ ],
+ "metadata": {
+ "timestamp": "2023-01-07T13:44:32.312678+00:00"
+ },
+ "properties": [
+ {
+ "name": "key1",
+ "value": "val1"
+ },
+ {
+ "name": "key2",
+ "value": "val2"
+ }
+ ],
+ "serialNumber": "urn:uuid:1441d33a-e0fc-45b5-af3b-61ee52a88bac",
+ "services": [
+ {
+ "bom-ref": "service-1",
+ "name": "annotated-service"
+ }
+ ],
+ "version": 1,
+ "$schema": "http://cyclonedx.org/schema/bom-1.7.schema.json",
+ "bomFormat": "CycloneDX",
+ "specVersion": "1.7"
+}
\ No newline at end of file
diff --git a/tests/_data/snapshots/get_bom_with_annotations-1.7.xml.bin b/tests/_data/snapshots/get_bom_with_annotations-1.7.xml.bin
new file mode 100644
index 00000000..ce1dc46f
--- /dev/null
+++ b/tests/_data/snapshots/get_bom_with_annotations-1.7.xml.bin
@@ -0,0 +1,79 @@
+
+
+
+ 2023-01-07T13:44:32.312678+00:00
+
+
+
+ annotated-component
+ 1.0.0
+
+
+
+
+ annotated-service
+
+
+
+
+
+
+
+ val1
+ val2
+
+
+
+
+
+
+
+
+ Acme, Inc.
+ https://example.com
+
+
+ 2024-01-01T12:00:00+00:00
+ This is an annotation by an organization.
+
+
+
+
+
+
+
+
+ Jane Doe
+ jane.doe@example.com
+
+
+ 2024-01-02T12:00:00+00:00
+ This is an annotation by an individual.
+
+
+
+
+
+
+
+ scanner
+ 2.0.0
+
+
+ 2024-01-03T12:00:00+00:00
+ This is an annotation by a component.
+
+
+
+
+
+
+
+ auth-service
+
+
+ 2024-01-04T12:00:00+00:00
+ This is an annotation by a service.
+
+
+
diff --git a/tests/test_contrib/test_bom_utils.py b/tests/test_contrib/test_bom_utils.py
index 013d7070..8b65be00 100644
--- a/tests/test_contrib/test_bom_utils.py
+++ b/tests/test_contrib/test_bom_utils.py
@@ -16,12 +16,16 @@
# Copyright (c) OWASP Foundation. All Rights Reserved.
+from datetime import datetime, timezone
from unittest import TestCase
from cyclonedx.contrib.bom.utils import BomDependencyGraphFlatMerger, BomRefDiscriminator
+from cyclonedx.model.annotation import Annotation, Annotator
from cyclonedx.model.bom import Bom
from cyclonedx.model.bom_ref import BomRef
+from cyclonedx.model.component import Component, ComponentType
from cyclonedx.model.dependency import Dependency
+from cyclonedx.model.service import Service
class TestBomRefDiscriminator(TestCase):
@@ -49,6 +53,52 @@ def test_discriminate_and_reset_with(self) -> None:
self.assertEqual('djdlkfjdslkf', bomref1.value)
self.assertEqual('djdlkfjdslkf', bomref2.value)
+ def test_from_bom_with_annotations(self) -> None:
+ comp = Component(name='c', type=ComponentType.APPLICATION, bom_ref='dup')
+ nested_comp = Component(name='nc', type=ComponentType.APPLICATION, bom_ref='dup-nested')
+ annotator_comp = Component(
+ name='ac', type=ComponentType.APPLICATION, bom_ref='dup-ac',
+ components=[nested_comp]
+ )
+ annotator_srv = Service(name='as', bom_ref='dup-as')
+ annotation1 = Annotation(
+ bom_ref='dup',
+ subjects=[comp.bom_ref],
+ annotator=Annotator(component=annotator_comp),
+ timestamp=datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
+ text='t1'
+ )
+ annotation2 = Annotation(
+ bom_ref='dup-2',
+ subjects=[comp.bom_ref],
+ annotator=Annotator(service=annotator_srv),
+ timestamp=datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
+ text='t2'
+ )
+ annotation3 = Annotation(
+ bom_ref='dup-nested',
+ subjects=[comp.bom_ref],
+ annotator=Annotator(component=Component(name='ac2', type=ComponentType.APPLICATION, bom_ref='dup-ac')),
+ timestamp=datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
+ text='t3'
+ )
+ bom = Bom(components=[comp], annotations=[annotation1, annotation2, annotation3])
+ discr = BomRefDiscriminator.from_bom(bom)
+ with discr:
+ all_refs = [
+ comp.bom_ref.value,
+ annotation1.bom_ref.value,
+ annotator_comp.bom_ref.value,
+ nested_comp.bom_ref.value,
+ annotation2.bom_ref.value,
+ annotator_srv.bom_ref.value,
+ annotation3.bom_ref.value,
+ ]
+ self.assertEqual(len(all_refs), len(set(all_refs)), 'All bom-refs must be unique')
+ self.assertEqual(comp.bom_ref.value, 'dup')
+ self.assertEqual(annotation1.bom_ref.value, 'dup')
+ self.assertEqual(nested_comp.bom_ref.value, 'dup-nested')
+
class TestBomDependencyGraphFlatMerger(TestCase):
diff --git a/tests/test_model_annotation.py b/tests/test_model_annotation.py
new file mode 100644
index 00000000..a70410c4
--- /dev/null
+++ b/tests/test_model_annotation.py
@@ -0,0 +1,111 @@
+# 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.
+
+from datetime import datetime, timezone
+from unittest import TestCase
+
+from cyclonedx.model.annotation import Annotation, Annotator
+from cyclonedx.model.bom_ref import BomRef
+from cyclonedx.model.component import Component, ComponentType
+from cyclonedx.model.contact import OrganizationalContact, OrganizationalEntity
+from cyclonedx.model.service import Service
+from tests import reorder
+
+_TIMESTAMP = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
+
+
+class TestModelAnnotator(TestCase):
+
+ def test_invalid_no_args(self) -> None:
+ with self.assertRaises(ValueError):
+ Annotator()
+
+ def test_invalid_multiple_args(self) -> None:
+ with self.assertRaises(ValueError):
+ Annotator(
+ organization=OrganizationalEntity(name='A'),
+ individual=OrganizationalContact(name='B'),
+ )
+
+ def test_sort(self) -> None:
+ # expected sort order: (organization, individual, component, service)
+ expected_order = [0, 2, 1]
+ annotators = [
+ Annotator(organization=OrganizationalEntity(name='Acme')),
+ Annotator(individual=OrganizationalContact(name='Zoe')),
+ Annotator(individual=OrganizationalContact(name='Alice')),
+ ]
+ self.assertListEqual(sorted(annotators), reorder(annotators, expected_order))
+
+ def test_repr(self) -> None:
+ org = OrganizationalEntity(name='Acme')
+ annotator = Annotator(organization=org)
+ r = repr(annotator)
+ self.assertIn('organization=', r)
+ self.assertIn('Acme', r)
+ self.assertIn('individual=None', r)
+ self.assertIn('component=None', r)
+ self.assertIn('service=None', r)
+
+ def test_component_and_service(self) -> None:
+ comp = Component(name='c', type=ComponentType.APPLICATION)
+ srv = Service(name='s')
+ a_comp = Annotator(component=comp)
+ a_srv = Annotator(service=srv)
+ self.assertEqual(a_comp.component, comp)
+ self.assertEqual(a_srv.service, srv)
+
+
+class TestModelAnnotation(TestCase):
+
+ def test_sort(self) -> None:
+ # expected sort order: (bom_ref.value, subjects, annotator, timestamp, text)
+ annotator = Annotator(organization=OrganizationalEntity(name='Acme'))
+ expected_order = [0, 2, 1]
+ annotations = [
+ Annotation(bom_ref='a', subjects=[BomRef('s')], annotator=annotator,
+ timestamp=_TIMESTAMP, text='alpha'),
+ Annotation(bom_ref='c', subjects=[BomRef('s')], annotator=annotator,
+ timestamp=_TIMESTAMP, text='gamma'),
+ Annotation(bom_ref='b', subjects=[BomRef('s')], annotator=annotator,
+ timestamp=_TIMESTAMP, text='beta'),
+ ]
+ self.assertListEqual(sorted(annotations), reorder(annotations, expected_order))
+
+ def test_subjects_returns_bom_refs(self) -> None:
+ annotator = Annotator(organization=OrganizationalEntity(name='Acme'))
+ annotation = Annotation(
+ subjects=[BomRef('s1'), 's2'],
+ annotator=annotator,
+ timestamp=_TIMESTAMP,
+ text='test'
+ )
+ self.assertEqual(len(annotation.subjects), 2)
+ for s in annotation.subjects:
+ self.assertIsInstance(s, BomRef)
+ self.assertEqual({s.value for s in annotation.subjects}, {'s1', 's2'})
+
+ def test_repr(self) -> None:
+ annotator = Annotator(organization=OrganizationalEntity(name='Acme'))
+ annotation = Annotation(
+ bom_ref='my-ref',
+ subjects=[BomRef('s1')],
+ annotator=annotator,
+ timestamp=_TIMESTAMP,
+ text='test'
+ )
+ self.assertEqual(repr(annotation), '')