|
| 1 | +# This file is part of CycloneDX Python Library |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# |
| 15 | +# SPDX-License-Identifier: Apache-2.0 |
| 16 | +# Copyright (c) OWASP Foundation. All Rights Reserved. |
| 17 | + |
| 18 | +"""Bom related utilities""" |
| 19 | + |
| 20 | +__all__ = ['BomRefDiscriminator', 'BomDependencyGraphFlatMerger'] |
| 21 | + |
| 22 | +from collections.abc import Iterable |
| 23 | +from itertools import chain |
| 24 | +from random import random |
| 25 | +from typing import TYPE_CHECKING, Any |
| 26 | + |
| 27 | +from ...model.dependency import Dependency |
| 28 | + |
| 29 | +if TYPE_CHECKING: # pragma: no cover |
| 30 | + from ...model.bom import Bom |
| 31 | + from ...model.bom_ref import BomRef |
| 32 | + |
| 33 | + |
| 34 | +class BomRefDiscriminator: |
| 35 | + """ |
| 36 | + Ensure that a collection of BomRef objects |
| 37 | + has unique, non‑empty :attr:`cyclonedx.model.bom_ref.BomRef.value`. |
| 38 | +
|
| 39 | + The discriminator inspects each provided BomRef and assigns a newly |
| 40 | + generated identifier to any instance whose ``value`` is missing or |
| 41 | + duplicates an earlier one. |
| 42 | + All original values are preserved and can be restored via :meth:`reset()` |
| 43 | + or by using this class as a context manager. |
| 44 | + """ |
| 45 | + |
| 46 | + def __init__(self, bomrefs: Iterable['BomRef'], prefix: str = 'BomRef') -> None: |
| 47 | + # NOTE: do not use dict/set here, different BomRefs with same value |
| 48 | + # have same hash and would shadow each other. |
| 49 | + self._bomrefs = tuple((bomref, bomref.value) for bomref in bomrefs) |
| 50 | + self._prefix = prefix |
| 51 | + |
| 52 | + def __enter__(self) -> None: |
| 53 | + self.discriminate() |
| 54 | + |
| 55 | + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: |
| 56 | + self.reset() |
| 57 | + |
| 58 | + def discriminate(self) -> None: |
| 59 | + """ |
| 60 | + Enforce uniqueness across all |
| 61 | + :attr:`cyclonedx.model.bom_ref.BomRef.value`s. |
| 62 | +
|
| 63 | + Any BomRef whose ``value`` is ``None`` or duplicates a previously |
| 64 | + encountered value is assigned a newly generated unique identifier. |
| 65 | + """ |
| 66 | + known_values = [] |
| 67 | + for bomref, _ in self._bomrefs: |
| 68 | + value = bomref.value |
| 69 | + if value is None or value in known_values: |
| 70 | + value = self._make_unique() |
| 71 | + bomref.value = value |
| 72 | + known_values.append(value) |
| 73 | + |
| 74 | + def reset(self) -> None: |
| 75 | + """ |
| 76 | + Restore all :attr:`cyclonedx.model.bom_ref.BomRef.value`s to |
| 77 | + their original state. |
| 78 | + """ |
| 79 | + for bomref, original_value in self._bomrefs: |
| 80 | + bomref.value = original_value |
| 81 | + |
| 82 | + def _make_unique(self) -> str: |
| 83 | + return f'{self._prefix}{str(random())[1:]}{str(random())[1:]}' # nosec B311 |
| 84 | + |
| 85 | + @classmethod |
| 86 | + def from_bom(cls, bom: 'Bom', prefix: str = 'BomRef') -> 'BomRefDiscriminator': |
| 87 | + """ |
| 88 | + Create a discriminator for all :class:`cyclonedx.model.bom_ref.BomRefs` |
| 89 | + contained within a Bom. |
| 90 | +
|
| 91 | + This includes BomRefs from |
| 92 | + * :attr:`cyclonedx.model.bom.Bom.components` |
| 93 | + * :attr:`cyclonedx.model.bom.Bom.services` |
| 94 | + * :attr:`cyclonedx.model.bom.Bom.vulnerabilities` |
| 95 | + """ |
| 96 | + return cls(chain( |
| 97 | + map(lambda c: c.bom_ref, bom._get_all_components()), |
| 98 | + map(lambda s: s.bom_ref, bom.services), |
| 99 | + map(lambda v: v.bom_ref, bom.vulnerabilities) |
| 100 | + ), prefix) |
| 101 | + |
| 102 | + |
| 103 | +class BomDependencyGraphFlatMerger: |
| 104 | + """ |
| 105 | + Context‑manager utility that temporarily flattens and merges all |
| 106 | + :attr:`cyclonedx.model.bom.Bom.dependencies`. |
| 107 | +
|
| 108 | + When used as a context manager, the :class:`cyclonedx.model.bom.Bom`'s |
| 109 | + dependency graph is replaced with a flattened, merged representation |
| 110 | + for the duration of the ``with`` block and automatically restored |
| 111 | + afterward. |
| 112 | + """ |
| 113 | + |
| 114 | + def __init__(self, bom: 'Bom') -> None: |
| 115 | + self._bom = bom |
| 116 | + # NOTE: do not use the getter - see `reset()` for reasons. |
| 117 | + self._deps = self._bom._dependencies |
| 118 | + |
| 119 | + def __enter__(self) -> None: |
| 120 | + self.flatten_merge() |
| 121 | + |
| 122 | + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: |
| 123 | + self.reset() |
| 124 | + |
| 125 | + def flatten_merge(self) -> None: |
| 126 | + """ |
| 127 | + Flatten and merge all :attr:`cyclonedx.model.bom.Bom.dependencies`. |
| 128 | +
|
| 129 | + This produces a non‑recursive, merged representation of the entire |
| 130 | + dependency graph and assigns it to the Bom. |
| 131 | +
|
| 132 | + .. note:: |
| 133 | + The original dependency graph is not modified. A new, flattened |
| 134 | + dependency structure is assigned to the Bom. |
| 135 | + """ |
| 136 | + self._bom.dependencies = self._flatten_merge(self._deps) |
| 137 | + |
| 138 | + def reset(self) -> None: |
| 139 | + """ |
| 140 | + Restore the :class:`cyclonedx.model.bom.Bom`'s dependency graph to |
| 141 | + its original state. |
| 142 | +
|
| 143 | + .. note:: |
| 144 | + This does not modify the dependency graph. It simply reassigns |
| 145 | + the original dependency collection back to the Bom. |
| 146 | + """ |
| 147 | + # NOTE: not using the setter, which would create overhead, |
| 148 | + # and - most importantly - this could cause deduplication of an existing malformed set. |
| 149 | + # Just access the internal field directly! |
| 150 | + self._bom._dependencies = self._deps |
| 151 | + |
| 152 | + @staticmethod |
| 153 | + def _flatten_merge(deps: Iterable[Dependency]) -> Iterable[Dependency]: |
| 154 | + flat: dict['BomRef', list['BomRef']] = {} |
| 155 | + todos = list(deps) |
| 156 | + seen: set[int] = set() |
| 157 | + while todos: |
| 158 | + todo = todos.pop() |
| 159 | + if (todo_id := id(todo)) in seen: |
| 160 | + continue |
| 161 | + seen.add(todo_id) |
| 162 | + ds = flat.setdefault(todo.ref, []) |
| 163 | + if todo_deps := todo.dependencies: |
| 164 | + ds.extend(d.ref for d in todo_deps) |
| 165 | + todos.extend(todo_deps) |
| 166 | + return ( |
| 167 | + Dependency(br, (Dependency(d) for d in ds)) |
| 168 | + for br, ds |
| 169 | + in flat.items() |
| 170 | + ) |
0 commit comments