Skip to content

Inventory Backends

Query-driven InventoryBackend protocol, zerobom.backends entry-point loader, conformance test harness, hardened SBOM parser/indexer, and built-in inventory plugins (local_sbom, dependency_track, oci_sbom, k8s_sbom).

backends

Cloud-agnostic inventory backend interfaces, plugin registry, parser, and conformance.

BackendConfigError

Bases: BackendLoadError

Raised when backend configuration options or credentials are invalid or missing.

BackendConformanceCase(expected_backend_name, vulnerable_advisory, safe_advisory, unmatched_advisory, min_vulnerable_hits=1) dataclass

Parameterized conformance test suite describing expected plugin matching behavior.

Attributes:

Name Type Description
expected_backend_name str

Expected value of backend.name.

vulnerable_advisory OsvAdvisory

Advisory that must match at least min_vulnerable_hits components.

safe_advisory OsvAdvisory

Same package with a fixed bound lower than installed versions (0 hits).

unmatched_advisory OsvAdvisory

Unrelated non-existent package (must return 0 hits).

min_vulnerable_hits int

Minimum vulnerable matches expected for vulnerable_advisory.

BackendConformanceError

Bases: AssertionError

Raised when an :class:InventoryBackend plugin violates conformance invariants.

BackendError

Bases: RuntimeError

Base exception for inventory backend loading, configuration, and query errors.

BackendLoadError

Bases: BackendError

Raised when a requested inventory backend cannot be found, loaded, or instantiated.

BackendQueryError

Bases: BackendError

Raised when an inventory backend runtime query fails or exceeds safety ceilings.

BackendRegistry(*, entry_points_provider=None, include_builtins=True)

Discovers, validates, and instantiates built-in and plugin inventory backends.

Initialize the backend registry.

Parameters:

Name Type Description Default
entry_points_provider Callable[[str], Iterable[Any]] | None

Optional callable overriding importlib.metadata.entry_points for isolated offline testing of third-party plugins.

None
include_builtins bool

Whether to register the built-in local_sbom backend automatically.

True
Source code in src/zerobom/backends/registry.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def __init__(
    self,
    *,
    entry_points_provider: Callable[[str], Iterable[Any]] | None = None,
    include_builtins: bool = True,
) -> None:
    """Initialize the backend registry.

    Args:
        entry_points_provider: Optional callable overriding ``importlib.metadata.entry_points``
            for isolated offline testing of third-party plugins.
        include_builtins: Whether to register the built-in ``local_sbom`` backend automatically.
    """
    self._entry_points_provider = entry_points_provider or _default_entry_points
    self._factories: dict[str, Callable[..., Any]] = {}
    if include_builtins:
        self._factories["local_sbom"] = LocalSbomBackend

create(name, *, config=None, **kwargs)

Instantiate and protocol-verify a named inventory backend.

When config is supplied and the backend factory defines a callable from_config hook, from_config(merged_config) is invoked; otherwise keyword arguments are passed directly to the backend constructor.

Parameters:

Name Type Description Default
name str

Registered or plugin backend name.

required
config Mapping[str, Any] | None

Optional parsed configuration mapping (from :func:parse_backend_options).

None
**kwargs Any

Explicit keyword arguments forwarded or merged into config.

{}

Returns:

Type Description
InventoryBackend

Instantiated object satisfying :class:InventoryBackend.

Raises:

Type Description
BackendLoadError

If loading/instantiation fails or the object does not implement :class:InventoryBackend.

BackendConfigError

Propagated directly if configuration validation fails.

Source code in src/zerobom/backends/registry.py
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
def create(
    self,
    name: str,
    *,
    config: Mapping[str, Any] | None = None,
    **kwargs: Any,
) -> InventoryBackend:
    """Instantiate and protocol-verify a named inventory backend.

    When ``config`` is supplied and the backend factory defines a callable ``from_config``
    hook, ``from_config(merged_config)`` is invoked; otherwise keyword arguments are passed
    directly to the backend constructor.

    Args:
        name: Registered or plugin backend name.
        config: Optional parsed configuration mapping (from :func:`parse_backend_options`).
        **kwargs: Explicit keyword arguments forwarded or merged into ``config``.

    Returns:
        Instantiated object satisfying :class:`InventoryBackend`.

    Raises:
        BackendLoadError: If loading/instantiation fails or the object does not implement
            :class:`InventoryBackend`.
        BackendConfigError: Propagated directly if configuration validation fails.
    """
    factory = self.get_factory(name)
    try:
        if config is not None:
            merged = {**config, **kwargs}
            from_config_hook = getattr(factory, "from_config", None)
            if callable(from_config_hook):
                instance = from_config_hook(merged)
            else:
                instance = factory(**merged)
        else:
            instance = factory(**kwargs)
    except BackendLoadError:
        raise
    except Exception as exc:
        raise BackendLoadError(f"Failed to instantiate backend {name!r}: {exc}") from exc

    if not isinstance(instance, InventoryBackend):
        raise BackendLoadError(
            f"Backend {name!r} instance {instance!r} does not satisfy InventoryBackend."
        )
    return instance

get_factory(name)

Resolve and lazily load the factory callable for a named backend.

Parameters:

Name Type Description Default
name str

Registered or entry-point backend identifier.

required

Returns:

Type Description
Callable[..., Any]

Factory callable capable of instantiating the backend.

Raises:

Type Description
BackendLoadError

If name is invalid, missing, fails to import, or is not callable.

Source code in src/zerobom/backends/registry.py
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
def get_factory(self, name: str) -> Callable[..., Any]:
    """Resolve and lazily load the factory callable for a named backend.

    Args:
        name: Registered or entry-point backend identifier.

    Returns:
        Factory callable capable of instantiating the backend.

    Raises:
        BackendLoadError: If ``name`` is invalid, missing, fails to import, or is not callable.
    """
    if not _BACKEND_NAME_RE.match(name):
        raise BackendLoadError(f"Invalid backend name {name!r}.")

    if name in self._factories:
        return self._factories[name]

    discovered = self._discover_entry_points()
    ep = discovered.get(name)
    if ep is None:
        available = ", ".join(self.list_backends()) or "none"
        raise BackendLoadError(
            f"Unknown inventory backend {name!r}. Available backends: {available}."
        )

    try:
        loaded = ep.load()
    except Exception as exc:
        raise BackendLoadError(
            f"Failed to load entry point for backend {name!r}: {exc}"
        ) from exc

    if not callable(loaded):
        raise BackendLoadError(
            f"Entry point for backend {name!r} resolved to non-callable {loaded!r}."
        )

    factory = cast(Callable[..., Any], loaded)
    self._factories[name] = factory
    return factory

list_backends()

Return sorted valid names of all registered and entry-point-discovered backends.

Source code in src/zerobom/backends/registry.py
190
191
192
193
def list_backends(self) -> tuple[str, ...]:
    """Return sorted valid names of all registered and entry-point-discovered backends."""
    names = set(self._factories.keys()) | set(self._discover_entry_points().keys())
    return tuple(sorted(names))

register(name, factory)

Manually register an inventory backend factory under a validated name.

Parameters:

Name Type Description Default
name str

Backend identifier matching ^[a-z][a-z0-9_-]{0,63}$.

required
factory Callable[..., InventoryBackend]

Callable returning an :class:InventoryBackend instance.

required

Raises:

Type Description
ValueError

If name is invalid or factory is not callable.

Source code in src/zerobom/backends/registry.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def register(self, name: str, factory: Callable[..., InventoryBackend]) -> None:
    """Manually register an inventory backend factory under a validated name.

    Args:
        name: Backend identifier matching ``^[a-z][a-z0-9_-]{0,63}$``.
        factory: Callable returning an :class:`InventoryBackend` instance.

    Raises:
        ValueError: If ``name`` is invalid or ``factory`` is not callable.
    """
    if not _BACKEND_NAME_RE.match(name):
        raise ValueError(
            f"Invalid backend name {name!r}; expected lowercase identifier "
            "matching ^[a-z][a-z0-9_-]{0,63}$"
        )
    if not callable(factory):
        raise ValueError("Backend factory must be callable")
    self._factories[name] = factory

DependencyTrackBackend(*, base_url, api_key=None, bearer_token=None, project_uuid=None, query_mode='coordinates', exclude_inactive_projects=True, only_latest_project_versions=False, page_size=100, max_pages=50, timeout_seconds=DEFAULT_API_TIMEOUT_SECONDS, max_response_bytes=DEFAULT_MAX_RESPONSE_BYTES, ca_bundle=None, verify_tls=True, allow_insecure_http=False, http_client=None)

Query-driven OWASP Dependency-Track REST API v1 inventory backend.

Initialize an OWASP Dependency-Track API v1 inventory backend.

Parameters:

Name Type Description Default
base_url str

Dependency-Track API root URL (e.g., https://dtrack.internal).

required
api_key str | None

Dependency-Track X-Api-Key credential.

None
bearer_token str | None

Optional OIDC/JWT bearer credential (mutually exclusive with api_key).

None
project_uuid str | None

Optional single Dependency-Track project UUID filter.

None
query_mode Literal['coordinates', 'purl']

Lookup strategy ("coordinates" using name/group or "purl" using canonical PURLs).

'coordinates'
exclude_inactive_projects bool

Exclude inactive projects when querying components.

True
only_latest_project_versions bool

Restrict queries to latest project versions.

False
page_size int

API page size in 1..1000.

100
max_pages int

Maximum paginated pages per query in 1..500 before failing closed.

50
timeout_seconds float

HTTP request timeout in 0.5..120.0 seconds.

DEFAULT_API_TIMEOUT_SECONDS
max_response_bytes int

Maximum response payload size per HTTP call.

DEFAULT_MAX_RESPONSE_BYTES
ca_bundle str | Path | None

Optional custom PEM CA bundle path for private internal PKI.

None
verify_tls bool

Enable TLS certificate verification (recommended).

True
allow_insecure_http bool

Explicit opt-in to permit http:// URLs for local testing.

False
http_client Client | None

Optional externally managed :class:httpx.Client (e.g., in tests).

None

Raises:

Type Description
BackendConfigError

If URL, credentials, TLS options, or bounds are invalid.

Source code in src/zerobom/backends/dependency_track.py
 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
def __init__(
    self,
    *,
    base_url: str,
    api_key: str | None = None,
    bearer_token: str | None = None,
    project_uuid: str | None = None,
    query_mode: Literal["coordinates", "purl"] = "coordinates",
    exclude_inactive_projects: bool = True,
    only_latest_project_versions: bool = False,
    page_size: int = 100,
    max_pages: int = 50,
    timeout_seconds: float = DEFAULT_API_TIMEOUT_SECONDS,
    max_response_bytes: int = DEFAULT_MAX_RESPONSE_BYTES,
    ca_bundle: str | Path | None = None,
    verify_tls: bool = True,
    allow_insecure_http: bool = False,
    http_client: httpx.Client | None = None,
) -> None:
    """Initialize an OWASP Dependency-Track API v1 inventory backend.

    Args:
        base_url: Dependency-Track API root URL (e.g., ``https://dtrack.internal``).
        api_key: Dependency-Track ``X-Api-Key`` credential.
        bearer_token: Optional OIDC/JWT bearer credential (mutually exclusive with
            ``api_key``).
        project_uuid: Optional single Dependency-Track project UUID filter.
        query_mode: Lookup strategy (``"coordinates"`` using ``name``/``group`` or
            ``"purl"`` using canonical PURLs).
        exclude_inactive_projects: Exclude inactive projects when querying components.
        only_latest_project_versions: Restrict queries to latest project versions.
        page_size: API page size in ``1..1000``.
        max_pages: Maximum paginated pages per query in ``1..500`` before failing closed.
        timeout_seconds: HTTP request timeout in ``0.5..120.0`` seconds.
        max_response_bytes: Maximum response payload size per HTTP call.
        ca_bundle: Optional custom PEM CA bundle path for private internal PKI.
        verify_tls: Enable TLS certificate verification (recommended).
        allow_insecure_http: Explicit opt-in to permit ``http://`` URLs for local testing.
        http_client: Optional externally managed :class:`httpx.Client` (e.g., in tests).

    Raises:
        BackendConfigError: If URL, credentials, TLS options, or bounds are invalid.
    """
    if not isinstance(allow_insecure_http, bool):
        raise BackendConfigError("Configuration option 'allow_insecure_http' must be a bool.")
    if not isinstance(verify_tls, bool):
        raise BackendConfigError("Configuration option 'verify_tls' must be a bool.")
    if not isinstance(exclude_inactive_projects, bool):
        raise BackendConfigError(
            "Configuration option 'exclude_inactive_projects' must be a bool."
        )
    if not isinstance(only_latest_project_versions, bool):
        raise BackendConfigError(
            "Configuration option 'only_latest_project_versions' must be a bool."
        )

    self._base_url = validate_api_base_url(
        base_url,
        allow_insecure_http=allow_insecure_http,
        field_name="base_url",
    )

    if api_key is not None and bearer_token is not None:
        raise BackendConfigError("Specify either 'api_key' or 'bearer_token', not both.")
    if api_key is None and bearer_token is None:
        raise BackendConfigError(
            "DependencyTrackBackend requires either 'api_key' or 'bearer_token'."
        )

    self._api_key = (
        validate_no_control_chars(api_key, field_name="api_key", max_length=4096)
        if api_key is not None
        else None
    )
    self._bearer_token = (
        validate_no_control_chars(bearer_token, field_name="bearer_token", max_length=4096)
        if bearer_token is not None
        else None
    )

    self._project_uuid: str | None = None
    if project_uuid is not None:
        cleaned_uuid = validate_no_control_chars(
            project_uuid,
            field_name="project_uuid",
            max_length=128,
        )
        if not _PROJECT_ID_RE.fullmatch(cleaned_uuid):
            raise BackendConfigError(
                "Configuration option 'project_uuid' contains invalid characters."
            )
        self._project_uuid = cleaned_uuid

    if query_mode not in ("coordinates", "purl"):
        raise BackendConfigError(
            f"Configuration option 'query_mode' must be 'coordinates' or 'purl', "
            f"got {query_mode!r}."
        )
    self._query_mode: Literal["coordinates", "purl"] = query_mode
    self._exclude_inactive_projects = exclude_inactive_projects
    self._only_latest_project_versions = only_latest_project_versions
    self._page_size = validate_bounded_int(
        page_size, field_name="page_size", min_value=1, max_value=1000
    )
    self._max_pages = validate_bounded_int(
        max_pages, field_name="max_pages", min_value=1, max_value=500
    )
    self._timeout_seconds = validate_timeout_seconds(timeout_seconds)
    self._max_response_bytes = validate_bounded_int(
        max_response_bytes,
        field_name="max_response_bytes",
        min_value=1024,
        max_value=100 * 1024 * 1024,
    )

    if http_client is not None:
        self._client = http_client
        self._owns_client = False
    else:
        verify_arg = resolve_tls_verify(verify_tls=verify_tls, ca_bundle=ca_bundle)
        self._client = httpx.Client(
            timeout=self._timeout_seconds,
            verify=verify_arg,
            follow_redirects=False,
        )
        self._owns_client = True

name property

Registered backend plugin identifier ("dependency_track").

close()

Close the internally managed HTTP client connection pool.

Source code in src/zerobom/backends/dependency_track.py
284
285
286
287
def close(self) -> None:
    """Close the internally managed HTTP client connection pool."""
    if self._owns_client:
        self._client.close()

find_components(queries)

Query Dependency-Track /api/v1/component/identity for candidate packages.

Parameters:

Name Type Description Default
queries Sequence[PackageQuery]

Normalized package queries built from an OSV advisory.

required

Returns:

Name Type Description
Deduplicated tuple[InventoryComponent, ...]

class:InventoryComponent entries matched via canonical PURL index.

Raises:

Type Description
BackendQueryError

On HTTP failure, auth denial, redirect, pagination overflow, or malformed JSON responses.

Source code in src/zerobom/backends/dependency_track.py
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
def find_components(self, queries: Sequence[PackageQuery]) -> tuple[InventoryComponent, ...]:
    """Query Dependency-Track ``/api/v1/component/identity`` for candidate packages.

    Args:
        queries: Normalized package queries built from an OSV advisory.

    Returns:
        Deduplicated :class:`InventoryComponent` entries matched via canonical PURL index.

    Raises:
        BackendQueryError: On HTTP failure, auth denial, redirect, pagination overflow,
            or malformed JSON responses.
    """
    if not queries:
        return ()

    unique_queries: list[PackageQuery] = []
    seen_keys: set[tuple[str, ...]] = set()
    for query in queries:
        if self._query_mode == "purl":
            key: tuple[str, ...] = (query.canonical_purl,)
        else:
            group = (
                query.namespace
                if query.namespace is not None and query.ecosystem not in {"deb", "rpm", "apk"}
                else ""
            )
            key = (group, query.name)
        if key not in seen_keys:
            seen_keys.add(key)
            unique_queries.append(query)

    index = InMemoryComponentIndex()
    for query in unique_queries:
        index.add_components(self._query_single_purl(query))

    return index.find_components(queries)

from_config(config) classmethod

Instantiate :class:DependencyTrackBackend from CLI/file configuration.

Environment variable fallbacks: ZEROBOM_DT_URL, ZEROBOM_DT_API_KEY, and ZEROBOM_DT_BEARER_TOKEN.

Source code in src/zerobom/backends/dependency_track.py
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
@classmethod
def from_config(cls, config: Mapping[str, Any]) -> DependencyTrackBackend:
    """Instantiate :class:`DependencyTrackBackend` from CLI/file configuration.

    Environment variable fallbacks: ``ZEROBOM_DT_URL``, ``ZEROBOM_DT_API_KEY``,
    and ``ZEROBOM_DT_BEARER_TOKEN``.
    """
    reject_unknown_config_keys(config, _ALLOWED_CONFIG_KEYS, backend_name="dependency_track")

    base_url = parse_optional_str_opt(
        config,
        "base_url",
        env_var="ZEROBOM_DT_URL",
        max_length=MAX_API_URL_LENGTH,
    )
    if base_url is None:
        raise BackendConfigError(
            "DependencyTrackBackend requires 'base_url' "
            "(or ZEROBOM_DT_URL environment variable)."
        )

    cfg_api_key = parse_optional_str_opt(config, "api_key", max_length=4096)
    cfg_bearer = parse_optional_str_opt(config, "bearer_token", max_length=4096)
    api_key = cfg_api_key
    bearer_token = cfg_bearer
    if api_key is None and bearer_token is None:
        raw_env_key = os.environ.get("ZEROBOM_DT_API_KEY")
        raw_env_bearer = os.environ.get("ZEROBOM_DT_BEARER_TOKEN")
        if raw_env_key and raw_env_key.strip():
            api_key = validate_no_control_chars(
                raw_env_key,
                field_name="ZEROBOM_DT_API_KEY",
                max_length=4096,
            )
        if raw_env_bearer and raw_env_bearer.strip():
            bearer_token = validate_no_control_chars(
                raw_env_bearer,
                field_name="ZEROBOM_DT_BEARER_TOKEN",
                max_length=4096,
            )

    raw_qmode = parse_optional_str_opt(config, "query_mode", max_length=32)
    qmode: Literal["coordinates", "purl"]
    if raw_qmode is None or raw_qmode == "coordinates":
        qmode = "coordinates"
    elif raw_qmode == "purl":
        qmode = "purl"
    else:
        raise BackendConfigError(
            f"Configuration option 'query_mode' must be 'coordinates' or 'purl', "
            f"got {raw_qmode!r}."
        )

    return cls(
        base_url=base_url,
        api_key=api_key,
        bearer_token=bearer_token,
        project_uuid=parse_optional_str_opt(config, "project_uuid", max_length=128),
        query_mode=qmode,
        exclude_inactive_projects=parse_bool_opt(
            config, "exclude_inactive_projects", default=True
        ),
        only_latest_project_versions=parse_bool_opt(
            config, "only_latest_project_versions", default=False
        ),
        page_size=parse_int_opt(config, "page_size", default=100, min_value=1, max_value=1000),
        max_pages=parse_int_opt(config, "max_pages", default=50, min_value=1, max_value=500),
        timeout_seconds=parse_float_opt(
            config,
            "timeout_seconds",
            default=DEFAULT_API_TIMEOUT_SECONDS,
            min_value=0.5,
            max_value=MAX_API_TIMEOUT_SECONDS,
        ),
        max_response_bytes=parse_int_opt(
            config,
            "max_response_bytes",
            default=DEFAULT_MAX_RESPONSE_BYTES,
            min_value=1024,
            max_value=100 * 1024 * 1024,
        ),
        ca_bundle=parse_optional_str_opt(config, "ca_bundle", max_length=2048),
        verify_tls=parse_bool_opt(config, "verify_tls", default=True),
        allow_insecure_http=parse_bool_opt(config, "allow_insecure_http", default=False),
    )

InMemoryComponentIndex(components=())

In-memory O(1) lookup index over normalized :class:InventoryComponent records.

Initialize the index and ingest any initial component records.

Source code in src/zerobom/backends/sbom_parser.py
451
452
453
454
455
456
457
458
def __init__(self, components: Iterable[InventoryComponent] = ()) -> None:
    """Initialize the index and ingest any initial component records."""
    self._components: list[InventoryComponent] = []
    self._by_canonical_purl: dict[str, list[InventoryComponent]] = {}
    self._by_upstream_purl: dict[str, list[InventoryComponent]] = {}
    self._fallback_by_name: dict[str, list[InventoryComponent]] = {}
    if components:
        self.add_components(components)

components property

All indexed :class:InventoryComponent records in insertion order.

add_components(components)

Add normalized components into canonical PURL, upstream, and fallback indices.

Source code in src/zerobom/backends/sbom_parser.py
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
def add_components(self, components: Iterable[InventoryComponent]) -> None:
    """Add normalized components into canonical PURL, upstream, and fallback indices."""
    for comp in components:
        self._components.append(comp)
        if comp.canonical_purl is not None:
            self._by_canonical_purl.setdefault(comp.canonical_purl, []).append(comp)
            if comp.upstream_package is not None:
                up_purl = _build_upstream_canonical(comp.canonical_purl, comp.upstream_package)
                if up_purl is not None:
                    self._by_upstream_purl.setdefault(up_purl, []).append(comp)
        else:
            lower_name = comp.name.strip().lower()
            pep503_name = _normalize_pep503(lower_name)
            keys = {lower_name, pep503_name}
            if comp.namespace is not None:
                ns_lower = comp.namespace.strip().lower()
                keys.add(f"{ns_lower}:{lower_name}")
                keys.add(f"{ns_lower}/{lower_name}")
            for key in keys:
                self._fallback_by_name.setdefault(key, []).append(comp)

find_components(queries)

Return deduplicated candidate components matching any supplied query.

Parameters:

Name Type Description Default
queries Sequence[PackageQuery]

Canonical package descriptors built from an OSV advisory.

required

Returns:

Type Description
tuple[InventoryComponent, ...]

Deduplicated tuple of matching :class:InventoryComponent objects.

Source code in src/zerobom/backends/sbom_parser.py
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
def find_components(self, queries: Sequence[PackageQuery]) -> tuple[InventoryComponent, ...]:
    """Return deduplicated candidate components matching any supplied query.

    Args:
        queries: Canonical package descriptors built from an OSV advisory.

    Returns:
        Deduplicated tuple of matching :class:`InventoryComponent` objects.
    """
    matched: list[InventoryComponent] = []
    seen_ids: set[int] = set()

    def _collect(bucket: Sequence[InventoryComponent]) -> None:
        for comp in bucket:
            obj_id = id(comp)
            if obj_id not in seen_ids:
                seen_ids.add(obj_id)
                matched.append(comp)

    for query in queries:
        _collect(self._by_canonical_purl.get(query.canonical_purl, ()))
        _collect(self._by_upstream_purl.get(query.canonical_purl, ()))

        q_name_lower = query.name.lower()
        if (
            query.namespace is not None
            and query.ecosystem in {"maven", "npm", "golang", "composer"}
            and len(query.name) > 1
        ):
            ns_lower = query.namespace.lower()
            _collect(self._fallback_by_name.get(f"{ns_lower}:{q_name_lower}", ()))
            _collect(self._fallback_by_name.get(f"{ns_lower}/{q_name_lower}", ()))
        elif len(query.name) > 1 and q_name_lower not in GENERIC_PACKAGE_BLOCKLIST:
            _collect(self._fallback_by_name.get(q_name_lower, ()))
            if query.ecosystem == "pypi":
                _collect(self._fallback_by_name.get(_normalize_pep503(q_name_lower), ()))
            if query.namespace is not None:
                ns_lower = query.namespace.lower()
                _collect(self._fallback_by_name.get(f"{ns_lower}:{q_name_lower}", ()))
                _collect(self._fallback_by_name.get(f"{ns_lower}/{q_name_lower}", ()))

    return tuple(matched)

InventoryBackend

Bases: Protocol

Query-driven contract implemented by local SBOMs and external/cloud plugins.

All backends return normalized :class:InventoryComponent entries; deterministic version range matching remains exclusively in :mod:zerobom.verify.osv_compiler.

name property

Unique identifier for this inventory backend (e.g., "local_sbom").

find_components(queries)

Look up candidate components matching any of the supplied package queries.

Parameters:

Name Type Description Default
queries Sequence[PackageQuery]

Canonical package descriptors extracted from an OSV advisory.

required

Returns:

Type Description
tuple[InventoryComponent, ...]

Tuple of matching :class:InventoryComponent records with attached AssetRef.

Source code in src/zerobom/backends/base.py
40
41
42
43
44
45
46
47
48
def find_components(self, queries: Sequence[PackageQuery]) -> tuple[InventoryComponent, ...]:
    """Look up candidate components matching any of the supplied package queries.

    Args:
        queries: Canonical package descriptors extracted from an OSV advisory.

    Returns:
        Tuple of matching :class:`InventoryComponent` records with attached ``AssetRef``.
    """

K8sSbomBackend(*, api_server=None, kubeconfig=None, context=None, cluster_name=None, namespace=None, include_cluster_reports=False, label_selector=None, bearer_token=None, token_file=None, username=None, password=None, ca_bundle=None, ca_pem_data=None, client_cert=None, client_key=None, in_cluster=False, serviceaccount_token_path=_SA_TOKEN_DEFAULT, serviceaccount_ca_path=_SA_CA_DEFAULT, env=None, page_size=100, max_pages=50, verify_tls=True, allow_insecure_http=False, timeout_seconds=DEFAULT_API_TIMEOUT_SECONDS, max_response_bytes=DEFAULT_MAX_RESPONSE_BYTES, http_client=None)

Read-only Kubernetes API backend querying Trivy Operator SbomReport CRDs.

Initialize a read-only Kubernetes Trivy Operator SbomReport backend.

Supports explicit api_server + credentials, standard kubeconfig YAML files (excluding exec credential plugins), and in-cluster ServiceAccount discovery.

Raises:

Type Description
BackendConfigError

If cluster discovery, auth, TLS, namespace, or bounds fail.

Source code in src/zerobom/backends/k8s_sbom.py
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
def __init__(
    self,
    *,
    api_server: str | None = None,
    kubeconfig: str | Path | None = None,
    context: str | None = None,
    cluster_name: str | None = None,
    namespace: str | None = None,
    include_cluster_reports: bool = False,
    label_selector: str | None = None,
    bearer_token: str | None = None,
    token_file: str | Path | None = None,
    username: str | None = None,
    password: str | None = None,
    ca_bundle: str | Path | None = None,
    ca_pem_data: str | None = None,
    client_cert: str | Path | None = None,
    client_key: str | Path | None = None,
    in_cluster: bool = False,
    serviceaccount_token_path: str | Path = _SA_TOKEN_DEFAULT,
    serviceaccount_ca_path: str | Path = _SA_CA_DEFAULT,
    env: Mapping[str, str] | None = None,
    page_size: int = 100,
    max_pages: int = 50,
    verify_tls: bool = True,
    allow_insecure_http: bool = False,
    timeout_seconds: float = DEFAULT_API_TIMEOUT_SECONDS,
    max_response_bytes: int = DEFAULT_MAX_RESPONSE_BYTES,
    http_client: httpx.Client | None = None,
) -> None:
    """Initialize a read-only Kubernetes Trivy Operator ``SbomReport`` backend.

    Supports explicit ``api_server`` + credentials, standard ``kubeconfig`` YAML files
    (excluding ``exec`` credential plugins), and in-cluster ServiceAccount discovery.

    Raises:
        BackendConfigError: If cluster discovery, auth, TLS, namespace, or bounds fail.
    """
    if not isinstance(include_cluster_reports, bool):
        raise BackendConfigError(
            "Configuration option 'include_cluster_reports' must be a bool."
        )
    if not isinstance(in_cluster, bool):
        raise BackendConfigError("Configuration option 'in_cluster' must be a bool.")
    if not isinstance(verify_tls, bool):
        raise BackendConfigError("Configuration option 'verify_tls' must be a bool.")
    if not isinstance(allow_insecure_http, bool):
        raise BackendConfigError("Configuration option 'allow_insecure_http' must be a bool.")

    self._page_size = validate_bounded_int(
        page_size, field_name="page_size", min_value=1, max_value=500
    )
    self._max_pages = validate_bounded_int(
        max_pages, field_name="max_pages", min_value=1, max_value=500
    )
    self._timeout_seconds = validate_timeout_seconds(timeout_seconds)
    self._max_response_bytes = validate_bounded_int(
        max_response_bytes,
        field_name="max_response_bytes",
        min_value=1024,
        max_value=100 * 1024 * 1024,
    )

    if namespace is not None:
        cleaned_ns = validate_no_control_chars(namespace, field_name="namespace", max_length=63)
        if not _K8S_NAMESPACE_RE.fullmatch(cleaned_ns):
            raise BackendConfigError(
                f"Invalid Kubernetes namespace {namespace!r}; must match DNS-1123 label."
            )
        self._namespace: str | None = cleaned_ns
    else:
        self._namespace = None

    self._label_selector: str | None = (
        validate_no_control_chars(label_selector, field_name="label_selector", max_length=512)
        if label_selector is not None
        else None
    )
    self._include_cluster_reports = include_cluster_reports
    self._index: InMemoryComponentIndex | None = None

    if (username is None) != (password is None):
        raise BackendConfigError("Both 'username' and 'password' must be provided together.")

    env_map = env if env is not None else os.environ

    resolved_server: str | None = (
        validate_api_base_url(
            api_server,
            allow_insecure_http=allow_insecure_http,
            field_name="api_server",
        )
        if api_server is not None
        else None
    )
    resolved_cluster_name: str | None = (
        validate_no_control_chars(cluster_name, field_name="cluster_name", max_length=128)
        if cluster_name is not None
        else None
    )
    resolved_token: str | None = (
        validate_no_control_chars(bearer_token, field_name="bearer_token", max_length=8192)
        if bearer_token is not None
        else None
    )
    if resolved_token is None and token_file is not None:
        tf_path = Path(
            validate_no_control_chars(str(token_file), field_name="token_file", max_length=2048)
        )
        resolved_token = _read_bounded_secret_file(tf_path, field_name="token_file")

    resolved_user: str | None = (
        validate_no_control_chars(username, field_name="username", max_length=512)
        if username is not None
        else None
    )
    resolved_pass: str | None = (
        validate_no_control_chars(password, field_name="password", max_length=4096)
        if password is not None
        else None
    )
    resolved_ca_bundle: str | Path | None = ca_bundle
    resolved_ca_pem: str | None = ca_pem_data
    resolved_client_cert: str | Path | None = client_cert
    resolved_client_key: str | Path | None = client_key
    client_cert_bytes: bytes | None = None
    client_key_bytes: bytes | None = None

    kubeconfig_candidate: Path | None = None
    if kubeconfig is not None:
        kc_str = validate_no_control_chars(
            str(kubeconfig), field_name="kubeconfig", max_length=2048
        )
        kubeconfig_candidate = Path(kc_str)
    elif not in_cluster and resolved_server is None:
        raw_kc_env = env_map.get("KUBECONFIG")
        if raw_kc_env and raw_kc_env.strip():
            first_kc = raw_kc_env.split(os.pathsep)[0]
            kubeconfig_candidate = Path(
                validate_no_control_chars(first_kc, field_name="KUBECONFIG", max_length=2048)
            )

    if kubeconfig_candidate is not None:
        (
            kc_server,
            kc_cluster,
            kc_token,
            kc_user,
            kc_pass,
            kc_ca_bundle,
            kc_ca_pem,
            kc_cert_path,
            kc_key_path,
            kc_cert_bytes,
            kc_key_bytes,
        ) = self._load_kubeconfig(
            kubeconfig_candidate,
            context_name=context,
            verify_tls=verify_tls,
            allow_insecure_http=allow_insecure_http,
        )
        if resolved_server is None:
            resolved_server = kc_server
        if resolved_cluster_name is None:
            resolved_cluster_name = kc_cluster
        if resolved_token is None:
            resolved_token = kc_token
        if resolved_user is None and resolved_pass is None:
            resolved_user = kc_user
            resolved_pass = kc_pass
        if resolved_ca_bundle is None and resolved_ca_pem is None:
            resolved_ca_bundle = kc_ca_bundle
            resolved_ca_pem = kc_ca_pem
        if resolved_client_cert is None and resolved_client_key is None:
            if kc_cert_path is not None and kc_key_path is not None:
                resolved_client_cert = kc_cert_path
                resolved_client_key = kc_key_path
            elif kc_cert_bytes is not None and kc_key_bytes is not None:
                client_cert_bytes = kc_cert_bytes
                client_key_bytes = kc_key_bytes
    elif in_cluster or resolved_server is None:
        sa_server, sa_token, sa_ca = self._load_in_cluster(
            env_map=env_map,
            token_path=Path(serviceaccount_token_path),
            ca_path=Path(serviceaccount_ca_path),
            allow_insecure_http=allow_insecure_http,
            require_token=(resolved_token is None and resolved_user is None),
        )
        if resolved_server is None:
            resolved_server = sa_server
        if resolved_token is None:
            resolved_token = sa_token
        if resolved_ca_bundle is None and resolved_ca_pem is None and sa_ca is not None:
            resolved_ca_bundle = sa_ca
        if resolved_cluster_name is None:
            resolved_cluster_name = "in-cluster"

    if resolved_server is None:
        raise BackendConfigError(
            "K8sSbomBackend could not determine a Kubernetes API server; supply 'api_server', "
            "'kubeconfig', KUBECONFIG, or in-cluster ServiceAccount environment variables."
        )

    self._api_server = resolved_server
    self._cluster_name = resolved_cluster_name or "default"
    self._bearer_token = resolved_token
    self._username = resolved_user
    self._password = resolved_pass

    if http_client is not None:
        if client_cert_bytes is not None and client_key_bytes is not None and not verify_tls:
            raise BackendConfigError(
                "Cannot combine verify_tls=False with client certificate authentication."
            )
        self._client = http_client
        self._owns_client = False
    else:
        if client_cert_bytes is not None and client_key_bytes is not None:
            if not verify_tls:
                raise BackendConfigError(
                    "Cannot combine verify_tls=False with client certificate authentication."
                )
            with tempfile.TemporaryDirectory() as tmp_dir:
                cert_tmp = Path(tmp_dir) / "client.crt"
                key_tmp = Path(tmp_dir) / "client.key"
                cert_tmp.write_bytes(client_cert_bytes)
                key_tmp.write_bytes(client_key_bytes)
                verify_arg = resolve_tls_verify(
                    verify_tls=verify_tls,
                    ca_bundle=resolved_ca_bundle,
                    ca_pem_data=resolved_ca_pem,
                    client_cert=cert_tmp,
                    client_key=key_tmp,
                )
        else:
            verify_arg = resolve_tls_verify(
                verify_tls=verify_tls,
                ca_bundle=resolved_ca_bundle,
                ca_pem_data=resolved_ca_pem,
                client_cert=resolved_client_cert,
                client_key=resolved_client_key,
            )

        self._client = httpx.Client(
            timeout=self._timeout_seconds,
            verify=verify_arg,
            follow_redirects=False,
        )
        self._owns_client = True

name property

Registered backend plugin identifier ("k8s_sbom").

close()

Close the internally managed HTTP client connection pool.

Source code in src/zerobom/backends/k8s_sbom.py
466
467
468
469
def close(self) -> None:
    """Close the internally managed HTTP client connection pool."""
    if self._owns_client:
        self._client.close()

find_components(queries)

Search indexed Kubernetes SbomReport components for candidate matches.

Source code in src/zerobom/backends/k8s_sbom.py
499
500
501
502
503
504
505
506
507
def find_components(self, queries: Sequence[PackageQuery]) -> tuple[InventoryComponent, ...]:
    """Search indexed Kubernetes ``SbomReport`` components for candidate matches."""
    if not queries:
        return ()
    if self._index is None:
        self.load()
    if self._index is None:
        return ()
    return self._index.find_components(queries)

from_config(config) classmethod

Instantiate :class:K8sSbomBackend from CLI options or YAML/JSON config.

Source code in src/zerobom/backends/k8s_sbom.py
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
@classmethod
def from_config(cls, config: Mapping[str, Any]) -> K8sSbomBackend:
    """Instantiate :class:`K8sSbomBackend` from CLI options or YAML/JSON config."""
    reject_unknown_config_keys(config, _ALLOWED_CONFIG_KEYS, backend_name="k8s_sbom")

    return cls(
        api_server=parse_optional_str_opt(config, "api_server", max_length=MAX_API_URL_LENGTH),
        kubeconfig=parse_optional_str_opt(config, "kubeconfig", max_length=2048),
        context=parse_optional_str_opt(config, "context", max_length=128),
        cluster_name=parse_optional_str_opt(config, "cluster_name", max_length=128),
        namespace=parse_optional_str_opt(config, "namespace", max_length=63),
        include_cluster_reports=parse_bool_opt(
            config, "include_cluster_reports", default=False
        ),
        label_selector=parse_optional_str_opt(config, "label_selector", max_length=512),
        bearer_token=parse_optional_str_opt(
            config, "bearer_token", env_var="ZEROBOM_K8S_TOKEN", max_length=8192
        ),
        token_file=parse_optional_str_opt(config, "token_file", max_length=2048),
        username=parse_optional_str_opt(config, "username", max_length=512),
        password=parse_optional_str_opt(config, "password", max_length=4096),
        ca_bundle=parse_optional_str_opt(config, "ca_bundle", max_length=2048),
        verify_tls=parse_bool_opt(config, "verify_tls", default=True),
        allow_insecure_http=parse_bool_opt(config, "allow_insecure_http", default=False),
        in_cluster=parse_bool_opt(config, "in_cluster", default=False),
        page_size=parse_int_opt(config, "page_size", default=100, min_value=1, max_value=500),
        max_pages=parse_int_opt(config, "max_pages", default=50, min_value=1, max_value=500),
        timeout_seconds=parse_float_opt(
            config,
            "timeout_seconds",
            default=DEFAULT_API_TIMEOUT_SECONDS,
            min_value=0.5,
            max_value=MAX_API_TIMEOUT_SECONDS,
        ),
        max_response_bytes=parse_int_opt(
            config,
            "max_response_bytes",
            default=DEFAULT_MAX_RESPONSE_BYTES,
            min_value=1024,
            max_value=100 * 1024 * 1024,
        ),
    )

load()

Fetch and index Trivy Operator SbomReport objects into memory.

Source code in src/zerobom/backends/k8s_sbom.py
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def load(self) -> int:
    """Fetch and index Trivy Operator ``SbomReport`` objects into memory."""
    urls: list[str] = []
    if self._namespace is not None:
        urls.append(
            f"{self._api_server}/apis/{_TRIVY_GROUP_VERSION}/"
            f"namespaces/{self._namespace}/sbomreports"
        )
    else:
        urls.append(f"{self._api_server}/apis/{_TRIVY_GROUP_VERSION}/sbomreports")
    if self._include_cluster_reports:
        urls.append(f"{self._api_server}/apis/{_TRIVY_GROUP_VERSION}/clustersbomreports")

    index = InMemoryComponentIndex()
    for url in urls:
        for item in self._fetch_paginated_list(url):
            index.add_components(self._parse_sbom_report_item(item))

    self._index = index
    return len(index.components)

LocalSbomBackend(paths, *, max_file_bytes=MAX_SBOM_FILE_BYTES, max_files=MAX_SBOM_FILES, max_depth=MAX_CYCLONEDX_DEPTH)

Zero-config inventory backend reading CycloneDX and SPDX JSON SBOMs from disk.

Load and index CycloneDX and SPDX JSON SBOM files from files or directories.

Parameters:

Name Type Description Default
paths Path | str | Sequence[Path | str]

File path, directory path, or sequence of paths to scan.

required
max_file_bytes int

Maximum allowed byte size per SBOM JSON file.

MAX_SBOM_FILE_BYTES
max_files int

Maximum number of JSON files permitted in a directory scan.

MAX_SBOM_FILES
max_depth int

Maximum CycloneDX nested components[] depth permitted.

MAX_CYCLONEDX_DEPTH

Raises:

Type Description
ValueError

If resource ceilings are non-positive or paths is empty.

SbomParseError

If an explicit file is missing/malformed/oversized/unrecognized, a directory exceeds max_files, or a nested SBOM exceeds max_depth.

Source code in src/zerobom/backends/local_sbom.py
 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
def __init__(
    self,
    paths: Path | str | Sequence[Path | str],
    *,
    max_file_bytes: int = MAX_SBOM_FILE_BYTES,
    max_files: int = MAX_SBOM_FILES,
    max_depth: int = MAX_CYCLONEDX_DEPTH,
) -> None:
    """Load and index CycloneDX and SPDX JSON SBOM files from files or directories.

    Args:
        paths: File path, directory path, or sequence of paths to scan.
        max_file_bytes: Maximum allowed byte size per SBOM JSON file.
        max_files: Maximum number of JSON files permitted in a directory scan.
        max_depth: Maximum CycloneDX nested ``components[]`` depth permitted.

    Raises:
        ValueError: If resource ceilings are non-positive or ``paths`` is empty.
        SbomParseError: If an explicit file is missing/malformed/oversized/unrecognized,
            a directory exceeds ``max_files``, or a nested SBOM exceeds ``max_depth``.
    """
    if max_file_bytes < 1 or max_files < 1 or max_depth < 1:
        raise ValueError("max_file_bytes, max_files, and max_depth must be >= 1")

    self._max_file_bytes = max_file_bytes
    self._max_files = max_files
    self._max_depth = max_depth

    path_items = [paths] if isinstance(paths, (Path, str)) else list(paths)
    if not path_items:
        raise ValueError("At least one SBOM file or directory path must be provided.")

    loaded_files: list[Path] = []
    skipped_files: list[Path] = []
    all_components: list[InventoryComponent] = []

    for raw_item in path_items:
        target = Path(raw_item)
        if not target.exists():
            raise SbomParseError(f"SBOM path does not exist: {target}")

        if target.is_file():
            data = _load_sbom_json(target, max_file_bytes=self._max_file_bytes)
            parsed = self._parse_explicit_file(target, data)
            loaded_files.append(target)
            all_components.extend(parsed)
        elif target.is_dir():
            self._scan_directory(
                target,
                loaded_files=loaded_files,
                skipped_files=skipped_files,
                all_components=all_components,
            )
        else:
            raise SbomParseError(f"Unsupported SBOM path type: {target}")

    self._loaded_files = tuple(loaded_files)
    self._skipped_files = tuple(skipped_files)
    self._index = InMemoryComponentIndex(all_components)

components property

All normalized inventory components parsed from configured SBOM files.

loaded_files property

SBOM files successfully parsed during initialization.

name property

Backend identifier registered in zerobom.backends.

skipped_files property

JSON or symlinked files skipped during directory scanning.

find_components(queries)

Return candidate components matching any query in O(1) per index lookup.

Parameters:

Name Type Description Default
queries Sequence[PackageQuery]

Canonical package descriptors built from an OSV advisory.

required

Returns:

Type Description
tuple[InventoryComponent, ...]

Deduplicated tuple of matching :class:InventoryComponent objects.

Source code in src/zerobom/backends/local_sbom.py
290
291
292
293
294
295
296
297
298
299
def find_components(self, queries: Sequence[PackageQuery]) -> tuple[InventoryComponent, ...]:
    """Return candidate components matching any query in O(1) per index lookup.

    Args:
        queries: Canonical package descriptors built from an OSV advisory.

    Returns:
        Deduplicated tuple of matching :class:`InventoryComponent` objects.
    """
    return self._index.find_components(queries)

from_config(config) classmethod

Instantiate :class:LocalSbomBackend from parsed CLI or YAML/JSON configuration.

Parameters:

Name Type Description Default
config Mapping[str, Any]

Mapping containing paths (or path / sbom) plus optional max_file_bytes, max_files, and max_depth integer ceilings.

required

Returns:

Name Type Description
Initialized LocalSbomBackend

class:LocalSbomBackend.

Raises:

Type Description
BackendConfigError

If paths is missing or configuration values are invalid.

Source code in src/zerobom/backends/local_sbom.py
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
@classmethod
def from_config(cls, config: Mapping[str, Any]) -> LocalSbomBackend:
    """Instantiate :class:`LocalSbomBackend` from parsed CLI or YAML/JSON configuration.

    Args:
        config: Mapping containing ``paths`` (or ``path`` / ``sbom``) plus optional
            ``max_file_bytes``, ``max_files``, and ``max_depth`` integer ceilings.

    Returns:
        Initialized :class:`LocalSbomBackend`.

    Raises:
        BackendConfigError: If ``paths`` is missing or configuration values are invalid.
    """
    raw_paths: Any = None
    for key in ("paths", "path", "sbom"):
        if key in config and config[key] is not None:
            raw_paths = config[key]
            break

    if raw_paths is None:
        raise BackendConfigError("local_sbom configuration requires 'paths' (or 'sbom').")

    if isinstance(raw_paths, (Path, str)):
        if isinstance(raw_paths, str) and not raw_paths.strip():
            raise BackendConfigError("local_sbom 'paths' must not be empty.")
        validated_paths: Path | str | Sequence[Path | str] = raw_paths
    elif isinstance(raw_paths, Sequence):
        items: list[Path | str] = []
        for item in raw_paths:
            if not isinstance(item, (Path, str)):
                raise BackendConfigError("local_sbom 'paths' items must be file or dir paths.")
            if isinstance(item, str) and not item.strip():
                raise BackendConfigError("local_sbom 'paths' must not contain empty paths.")
            items.append(item)
        if not items:
            raise BackendConfigError("local_sbom 'paths' must contain at least one path.")
        validated_paths = tuple(items)
    else:
        raise BackendConfigError("local_sbom 'paths' must be a path or sequence of paths.")

    max_file_bytes = _parse_positive_int_option(config, "max_file_bytes", MAX_SBOM_FILE_BYTES)
    max_files = _parse_positive_int_option(config, "max_files", MAX_SBOM_FILES)
    max_depth = _parse_positive_int_option(config, "max_depth", MAX_CYCLONEDX_DEPTH)
    return cls(
        validated_paths,
        max_file_bytes=max_file_bytes,
        max_files=max_files,
        max_depth=max_depth,
    )

OciSbomBackend(*, images, username=None, password=None, bearer_token=None, platform=None, allowed_auth_hosts=(), fallback_tag_schema=True, allow_blob_redirects=True, allow_private_redirects=False, allow_insecure_http=False, ca_bundle=None, verify_tls=True, timeout_seconds=DEFAULT_API_TIMEOUT_SECONDS, max_sbom_bytes=DEFAULT_MAX_RESPONSE_BYTES, strict=False, dns_resolver=None, http_client=None)

OCI Distribution v1.1 container image SBOM and attestation inventory backend.

Initialize an OCI container registry SBOM inventory backend.

Parameters:

Name Type Description Default
images Sequence[str]

Container image references to scan for attached SBOMs/attestations.

required
username str | None

Optional registry username for HTTP Basic / Bearer token exchange.

None
password str | None

Optional registry password or PAT matching username.

None
bearer_token str | None

Optional pre-minted registry Bearer token.

None
platform str | None

Optional multi-arch filter formatted as os/arch (e.g. linux/amd64).

None
allowed_auth_hosts Sequence[str]

Optional explicit third-party bearer auth realm host allowlist.

()
fallback_tag_schema bool

Fall back to OCI 1.0 sha256-<hex> tags on 404 referrers.

True
allow_blob_redirects bool

Follow one validated HTTPS redirect on /blobs/ requests with authorization headers stripped.

True
allow_private_redirects bool

Explicit opt-in to permit private/loopback redirect or realm targets for internal registries.

False
allow_insecure_http bool

Explicit opt-in to permit http:// registries/token realms.

False
ca_bundle str | Path | None

Optional PEM CA bundle path for private internal registries.

None
verify_tls bool

Enable TLS certificate verification.

True
timeout_seconds float

HTTP request timeout in 0.5..120.0 seconds.

DEFAULT_API_TIMEOUT_SECONDS
max_sbom_bytes int

Maximum SBOM/attestation blob size permitted per layer.

DEFAULT_MAX_RESPONSE_BYTES
strict bool

Raise :class:BackendQueryError if an image yields zero SBOM components.

False
dns_resolver DnsResolver | None

Optional DNS resolver callable for offline SSRF testing.

None
http_client Client | None

Optional externally managed :class:httpx.Client (e.g., in tests).

None

Raises:

Type Description
BackendConfigError

If image references, credentials, platform, TLS, or bounds fail.

Source code in src/zerobom/backends/oci_sbom.py
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
def __init__(
    self,
    *,
    images: Sequence[str],
    username: str | None = None,
    password: str | None = None,
    bearer_token: str | None = None,
    platform: str | None = None,
    allowed_auth_hosts: Sequence[str] = (),
    fallback_tag_schema: bool = True,
    allow_blob_redirects: bool = True,
    allow_private_redirects: bool = False,
    allow_insecure_http: bool = False,
    ca_bundle: str | Path | None = None,
    verify_tls: bool = True,
    timeout_seconds: float = DEFAULT_API_TIMEOUT_SECONDS,
    max_sbom_bytes: int = DEFAULT_MAX_RESPONSE_BYTES,
    strict: bool = False,
    dns_resolver: DnsResolver | None = None,
    http_client: httpx.Client | None = None,
) -> None:
    """Initialize an OCI container registry SBOM inventory backend.

    Args:
        images: Container image references to scan for attached SBOMs/attestations.
        username: Optional registry username for HTTP Basic / Bearer token exchange.
        password: Optional registry password or PAT matching ``username``.
        bearer_token: Optional pre-minted registry Bearer token.
        platform: Optional multi-arch filter formatted as ``os/arch`` (e.g. ``linux/amd64``).
        allowed_auth_hosts: Optional explicit third-party bearer auth realm host allowlist.
        fallback_tag_schema: Fall back to OCI 1.0 ``sha256-<hex>`` tags on 404 referrers.
        allow_blob_redirects: Follow one validated HTTPS redirect on ``/blobs/`` requests
            with authorization headers stripped.
        allow_private_redirects: Explicit opt-in to permit private/loopback redirect or realm
            targets for internal registries.
        allow_insecure_http: Explicit opt-in to permit ``http://`` registries/token realms.
        ca_bundle: Optional PEM CA bundle path for private internal registries.
        verify_tls: Enable TLS certificate verification.
        timeout_seconds: HTTP request timeout in ``0.5..120.0`` seconds.
        max_sbom_bytes: Maximum SBOM/attestation blob size permitted per layer.
        strict: Raise :class:`BackendQueryError` if an image yields zero SBOM components.
        dns_resolver: Optional DNS resolver callable for offline SSRF testing.
        http_client: Optional externally managed :class:`httpx.Client` (e.g., in tests).

    Raises:
        BackendConfigError: If image references, credentials, platform, TLS, or bounds fail.
    """
    if not isinstance(fallback_tag_schema, bool):
        raise BackendConfigError("Configuration option 'fallback_tag_schema' must be a bool.")
    if not isinstance(allow_blob_redirects, bool):
        raise BackendConfigError("Configuration option 'allow_blob_redirects' must be a bool.")
    if not isinstance(allow_private_redirects, bool):
        raise BackendConfigError(
            "Configuration option 'allow_private_redirects' must be a bool."
        )
    if not isinstance(allow_insecure_http, bool):
        raise BackendConfigError("Configuration option 'allow_insecure_http' must be a bool.")
    if not isinstance(verify_tls, bool):
        raise BackendConfigError("Configuration option 'verify_tls' must be a bool.")
    if not isinstance(strict, bool):
        raise BackendConfigError("Configuration option 'strict' must be a bool.")

    if isinstance(images, (str, bytes)) or not isinstance(images, Sequence):
        raise BackendConfigError(
            "Configuration option 'images' must be a sequence of image references."
        )
    if not images:
        raise BackendConfigError("OciSbomBackend requires at least one image reference.")
    if len(images) > _MAX_IMAGES:
        raise BackendConfigError(f"OciSbomBackend supports at most {_MAX_IMAGES} images.")

    parsed_refs: list[OciImageRef] = [parse_oci_image_ref(ref) for ref in images]
    self._image_refs: tuple[OciImageRef, ...] = tuple(parsed_refs)

    if (username is None) != (password is None):
        raise BackendConfigError("Both 'username' and 'password' must be provided together.")
    if bearer_token is not None and username is not None:
        raise BackendConfigError("Specify either 'bearer_token' or 'username'/'password'.")

    self._username = (
        validate_no_control_chars(username, field_name="username", max_length=512)
        if username is not None
        else None
    )
    self._password = (
        validate_no_control_chars(password, field_name="password", max_length=4096)
        if password is not None
        else None
    )
    self._bearer_token = (
        validate_no_control_chars(bearer_token, field_name="bearer_token", max_length=8192)
        if bearer_token is not None
        else None
    )

    self._platform_os: str | None = None
    self._platform_arch: str | None = None
    self._platform: str | None = None
    if platform is not None:
        cleaned_platform = validate_no_control_chars(
            platform, field_name="platform", max_length=64
        )
        os_part, sep, arch_part = cleaned_platform.partition("/")
        if not sep or not os_part or not arch_part or "/" in arch_part:
            raise BackendConfigError(
                "Configuration option 'platform' must be formatted as '<os>/<arch>'."
            )
        self._platform_os = os_part.lower()
        self._platform_arch = arch_part.lower()
        self._platform = f"{self._platform_os}/{self._platform_arch}"

    self._timeout_seconds = validate_timeout_seconds(timeout_seconds)
    self._max_sbom_bytes = validate_bounded_int(
        max_sbom_bytes,
        field_name="max_sbom_bytes",
        min_value=1024,
        max_value=100 * 1024 * 1024,
    )

    self._allowed_auth_hosts: frozenset[str] = frozenset(
        validate_no_control_chars(host, field_name="allowed_auth_hosts", max_length=255)
        .lower()
        .rsplit(":", 1)[0]
        for host in allowed_auth_hosts
        if isinstance(host, str) and host.strip()
    )
    self._fallback_tag_schema = fallback_tag_schema
    self._allow_blob_redirects = allow_blob_redirects
    self._allow_private_redirects = allow_private_redirects
    self._allow_insecure_http = allow_insecure_http
    self._strict = strict
    self._scheme = "http" if allow_insecure_http else "https"
    self._dns_resolver = dns_resolver

    self._scoped_tokens: dict[tuple[str, str], str] = {}
    self._index: InMemoryComponentIndex | None = None

    if http_client is not None:
        self._client = http_client
        self._owns_client = False
    else:
        verify_arg = resolve_tls_verify(verify_tls=verify_tls, ca_bundle=ca_bundle)
        self._client = create_pinned_httpx_client(
            timeout=self._timeout_seconds,
            verify=verify_arg,
            dns_resolver=self._dns_resolver or default_dns_resolver,
            allow_private_targets=self._allow_private_redirects,
            private_allowed_hosts=frozenset(
                ref.registry.rsplit(":", 1)[0].lower() for ref in self._image_refs
            ),
            block_link_local=not self._allow_private_redirects,
            on_blocked=lambda msg: BackendQueryError(f"[{self.name}] {msg}"),
        )
        self._owns_client = True

image_refs property

Configured OCI image references.

name property

Registered backend plugin identifier ("oci_sbom").

close()

Close the internally managed HTTP client connection pool.

Source code in src/zerobom/backends/oci_sbom.py
608
609
610
611
def close(self) -> None:
    """Close the internally managed HTTP client connection pool."""
    if self._owns_client:
        self._client.close()

find_components(queries)

Search indexed OCI image SBOM components for candidate package matches.

Parameters:

Name Type Description Default
queries Sequence[PackageQuery]

Canonical package descriptors built from an OSV advisory.

required

Returns:

Name Type Description
Matching tuple[InventoryComponent, ...]

class:InventoryComponent records bound to each oci:// image asset.

Source code in src/zerobom/backends/oci_sbom.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
def find_components(self, queries: Sequence[PackageQuery]) -> tuple[InventoryComponent, ...]:
    """Search indexed OCI image SBOM components for candidate package matches.

    Args:
        queries: Canonical package descriptors built from an OSV advisory.

    Returns:
        Matching :class:`InventoryComponent` records bound to each ``oci://`` image asset.
    """
    if not queries:
        return ()
    if self._index is None:
        self.load()
    if self._index is None:
        return ()
    return self._index.find_components(queries)

from_config(config) classmethod

Instantiate :class:OciSbomBackend from CLI options or YAML/JSON config.

Environment variable fallbacks: ZEROBOM_OCI_TOKEN, ZEROBOM_OCI_USERNAME, and ZEROBOM_OCI_PASSWORD.

Source code in src/zerobom/backends/oci_sbom.py
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
@classmethod
def from_config(cls, config: Mapping[str, Any]) -> OciSbomBackend:
    """Instantiate :class:`OciSbomBackend` from CLI options or YAML/JSON config.

    Environment variable fallbacks: ``ZEROBOM_OCI_TOKEN``, ``ZEROBOM_OCI_USERNAME``,
    and ``ZEROBOM_OCI_PASSWORD``.
    """
    reject_unknown_config_keys(config, _ALLOWED_CONFIG_KEYS, backend_name="oci_sbom")

    images = parse_str_list_opt(config, "images", max_items=_MAX_IMAGES, max_item_length=512)
    if not images:
        raise BackendConfigError("OciSbomBackend requires non-empty 'images' configuration.")

    username = parse_optional_str_opt(
        config, "username", env_var="ZEROBOM_OCI_USERNAME", max_length=512
    )
    password = parse_optional_str_opt(
        config, "password", env_var="ZEROBOM_OCI_PASSWORD", max_length=4096
    )
    bearer_token = parse_optional_str_opt(
        config, "bearer_token", env_var="ZEROBOM_OCI_TOKEN", max_length=8192
    )
    if "bearer_token" in config and "username" not in config and "password" not in config:
        username = None
        password = None
    elif (
        "bearer_token" not in config
        and ("username" in config or "password" in config)
        and username is not None
        and password is not None
    ):
        # Explicit username/password in config overrides stale ZEROBOM_OCI_TOKEN env var.
        bearer_token = None

    return cls(
        images=images,
        username=username,
        password=password,
        bearer_token=bearer_token,
        platform=parse_optional_str_opt(config, "platform", max_length=64),
        allowed_auth_hosts=parse_str_list_opt(
            config, "allowed_auth_hosts", max_items=20, max_item_length=255
        ),
        fallback_tag_schema=parse_bool_opt(config, "fallback_tag_schema", default=True),
        allow_blob_redirects=parse_bool_opt(config, "allow_blob_redirects", default=True),
        allow_private_redirects=parse_bool_opt(
            config, "allow_private_redirects", default=False
        ),
        allow_insecure_http=parse_bool_opt(config, "allow_insecure_http", default=False),
        ca_bundle=parse_optional_str_opt(config, "ca_bundle", max_length=2048),
        verify_tls=parse_bool_opt(config, "verify_tls", default=True),
        timeout_seconds=parse_float_opt(
            config,
            "timeout_seconds",
            default=DEFAULT_API_TIMEOUT_SECONDS,
            min_value=0.5,
            max_value=MAX_API_TIMEOUT_SECONDS,
        ),
        max_sbom_bytes=parse_int_opt(
            config,
            "max_sbom_bytes",
            default=DEFAULT_MAX_RESPONSE_BYTES,
            min_value=1024,
            max_value=100 * 1024 * 1024,
        ),
        strict=parse_bool_opt(config, "strict", default=False),
    )

load()

Fetch and index SBOMs/attestations for all configured container images.

Source code in src/zerobom/backends/oci_sbom.py
620
621
622
623
624
625
626
627
628
629
630
631
632
def load(self) -> int:
    """Fetch and index SBOMs/attestations for all configured container images."""
    index = InMemoryComponentIndex()
    for ref in self._image_refs:
        components = self._load_image_components(ref)
        if self._strict and not components:
            raise BackendQueryError(
                f"[{self.name}] No verifiable SBOM components found for image "
                f"{ref.raw_reference}."
            )
        index.add_components(components)
    self._index = index
    return len(index.components)

SbomParseError

Bases: ValueError

Raised when an SBOM input path or JSON document violates schema or safety bounds.

assert_backend_conformance(backend, case)

Verify that an :class:InventoryBackend plugin fulfills every ZeroBOM contract invariant.

Parameters:

Name Type Description Default
backend InventoryBackend

Instantiated backend plugin under test.

required
case BackendConformanceCase

Parameterized conformance test case.

required

Returns:

Type Description
tuple[MatchResult, ...]

Verified tuple of vulnerable :class:MatchResult hits from case.vulnerable_advisory.

Raises:

Type Description
BackendConformanceError

If any protocol, identifier, AssetRef, deterministic univers version filtering, empty-query, or idempotency check fails.

Source code in src/zerobom/backends/conformance.py
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
def assert_backend_conformance(
    backend: InventoryBackend,
    case: BackendConformanceCase,
) -> tuple[MatchResult, ...]:
    """Verify that an :class:`InventoryBackend` plugin fulfills every ZeroBOM contract invariant.

    Args:
        backend: Instantiated backend plugin under test.
        case: Parameterized conformance test case.

    Returns:
        Verified tuple of vulnerable :class:`MatchResult` hits from ``case.vulnerable_advisory``.

    Raises:
        BackendConformanceError: If any protocol, identifier, ``AssetRef``, deterministic
            ``univers`` version filtering, empty-query, or idempotency check fails.
    """
    if case.min_vulnerable_hits < 1:
        raise BackendConformanceError("BackendConformanceCase.min_vulnerable_hits must be >= 1.")

    if not isinstance(backend, InventoryBackend):
        raise BackendConformanceError(
            f"Backend {backend!r} does not implement the InventoryBackend protocol."
        )

    backend_name = backend.name
    if not isinstance(backend_name, str) or not _CONFORMANCE_BACKEND_NAME_RE.match(backend_name):
        raise BackendConformanceError(
            f"Backend.name {backend_name!r} must match ^[a-z][a-z0-9_-]{{0,63}}$."
        )
    if backend_name != case.expected_backend_name:
        raise BackendConformanceError(
            f"Expected backend.name={case.expected_backend_name!r}, got {backend_name!r}."
        )

    empty_results = backend.find_components(())
    if not isinstance(empty_results, Sequence) or len(empty_results) != 0:
        raise BackendConformanceError(
            f"find_components(()) must return an empty sequence, got {empty_results!r}."
        )

    vuln_queries = build_package_queries(case.vulnerable_advisory)
    raw_candidates = backend.find_components(vuln_queries)
    if not isinstance(raw_candidates, Sequence):
        raise BackendConformanceError(
            f"find_components() must return a sequence, got {type(raw_candidates).__name__}."
        )
    for comp in raw_candidates:
        if not isinstance(comp, InventoryComponent):
            raise BackendConformanceError(
                f"find_components() yielded non-InventoryComponent {comp!r}."
            )
        if comp.asset.backend != backend_name:
            raise BackendConformanceError(
                f"Component {comp.name}@{comp.version} has AssetRef.backend={comp.asset.backend!r},"
                f" expected {backend_name!r}."
            )

    vuln_matches = match_advisory_with_backend(
        case.vulnerable_advisory,
        backend,
        only_vulnerable=True,
    )
    if len(vuln_matches) < case.min_vulnerable_hits:
        raise BackendConformanceError(
            f"Expected at least {case.min_vulnerable_hits} vulnerable match(es) for "
            f"{case.vulnerable_advisory.id}, got {len(vuln_matches)}."
        )
    for match in vuln_matches:
        if not match.is_vulnerable:
            raise BackendConformanceError(
                f"only_vulnerable=True returned non-vulnerable match {match!r}."
            )
        if match.asset is None or match.asset.backend != backend_name:
            raise BackendConformanceError(
                f"Match {match.component_purl} missing consistent "
                f"AssetRef.backend={backend_name!r}."
            )

    safe_matches = match_advisory_with_backend(case.safe_advisory, backend, only_vulnerable=True)
    if safe_matches:
        raise BackendConformanceError(
            "Safe/patched advisory yielded false-positive vulnerable matches; version math must "
            "be handled via zerobom's univers evaluator."
        )

    unmatched_matches = match_advisory_with_backend(
        case.unmatched_advisory,
        backend,
        only_vulnerable=True,
    )
    if unmatched_matches:
        raise BackendConformanceError(
            f"Unmatched advisory yielded unexpected matches: {unmatched_matches!r}."
        )

    repeat_matches = match_advisory_with_backend(
        case.vulnerable_advisory,
        backend,
        only_vulnerable=True,
    )
    if vuln_matches != repeat_matches:
        raise BackendConformanceError(
            "Backend matching is non-idempotent across consecutive identical queries."
        )

    return vuln_matches

build_default_conformance_case(*, backend_name, package_name='requests', ecosystem='PyPI', canonical_purl='pkg:pypi/requests', vulnerable_fixed='2.31.0', safe_fixed='1.0.0')

Construct a standard three-advisory conformance fixture for a backend plugin.

Parameters:

Name Type Description Default
backend_name str

Expected plugin name property.

required
package_name str

Target package present in the plugin's inventory.

'requests'
ecosystem str

OSV ecosystem string for package_name.

'PyPI'
canonical_purl str

Versionless canonical PURL matching the inventory entry.

'pkg:pypi/requests'
vulnerable_fixed str

Version higher than installed version (triggers vulnerable hit).

'2.31.0'
safe_fixed str

Version lower than installed version (must yield zero vulnerable hits).

'1.0.0'

Returns:

Name Type Description
Configured BackendConformanceCase

class:BackendConformanceCase.

Source code in src/zerobom/backends/conformance.py
 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
def build_default_conformance_case(
    *,
    backend_name: str,
    package_name: str = "requests",
    ecosystem: str = "PyPI",
    canonical_purl: str = "pkg:pypi/requests",
    vulnerable_fixed: str = "2.31.0",
    safe_fixed: str = "1.0.0",
) -> BackendConformanceCase:
    """Construct a standard three-advisory conformance fixture for a backend plugin.

    Args:
        backend_name: Expected plugin ``name`` property.
        package_name: Target package present in the plugin's inventory.
        ecosystem: OSV ecosystem string for ``package_name``.
        canonical_purl: Versionless canonical PURL matching the inventory entry.
        vulnerable_fixed: Version higher than installed version (triggers vulnerable hit).
        safe_fixed: Version lower than installed version (must yield zero vulnerable hits).

    Returns:
        Configured :class:`BackendConformanceCase`.
    """
    vulnerable_advisory = OsvAdvisory(
        id="PRECVE-2026-00000001",
        modified=_CONFORMANCE_TS,
        published=_CONFORMANCE_TS,
        summary=f"Conformance vulnerable advisory for {package_name}",
        affected=(
            OsvAffected(
                package=OsvPackage(ecosystem=ecosystem, name=package_name, purl=canonical_purl),
                ranges=(
                    OsvRange(
                        type="ECOSYSTEM",
                        events=(
                            OsvRangeEvent(introduced="0"),
                            OsvRangeEvent(fixed=vulnerable_fixed),
                        ),
                    ),
                ),
            ),
        ),
    )
    safe_advisory = OsvAdvisory(
        id="PRECVE-2026-00000002",
        modified=_CONFORMANCE_TS,
        published=_CONFORMANCE_TS,
        summary=f"Conformance already-patched advisory for {package_name}",
        affected=(
            OsvAffected(
                package=OsvPackage(ecosystem=ecosystem, name=package_name, purl=canonical_purl),
                ranges=(
                    OsvRange(
                        type="ECOSYSTEM",
                        events=(
                            OsvRangeEvent(introduced="0"),
                            OsvRangeEvent(fixed=safe_fixed),
                        ),
                    ),
                ),
            ),
        ),
    )
    unmatched_advisory = OsvAdvisory(
        id="PRECVE-2026-00000003",
        modified=_CONFORMANCE_TS,
        published=_CONFORMANCE_TS,
        summary="Conformance unmatched nonexistent package",
        affected=(
            OsvAffected(
                package=OsvPackage(
                    ecosystem="PyPI",
                    name="zerobom-nonexistent-conformance-pkg",
                    purl="pkg:pypi/zerobom-nonexistent-conformance-pkg",
                ),
                ranges=(
                    OsvRange(
                        type="ECOSYSTEM",
                        events=(
                            OsvRangeEvent(introduced="0"),
                            OsvRangeEvent(fixed="9.9.9"),
                        ),
                    ),
                ),
            ),
        ),
    )
    return BackendConformanceCase(
        expected_backend_name=backend_name,
        vulnerable_advisory=vulnerable_advisory,
        safe_advisory=safe_advisory,
        unmatched_advisory=unmatched_advisory,
    )

derive_sbom_asset(data, *, asset_id, backend, location=None, scope=None, asset_type=None, extra_metadata=None)

Construct a cloud-agnostic :class:AssetRef enriched from SBOM document headers.

Parameters:

Name Type Description Default
data Mapping[str, Any]

Parsed CycloneDX or SPDX JSON mapping.

required
asset_id str

Unique asset identifier (file path, object URI, digest, or resource ID).

required
backend str

Registered zerobom.backends name owning the asset.

required
location str | None

Optional path, URI, digest, or region string.

None
scope str | None

Optional scope override; falls back to document root component or doc name.

None
asset_type str | None

Optional asset category override; falls back to metadata component type or "sbom".

None
extra_metadata Mapping[str, Any] | None

Optional plugin-supplied opaque metadata merged safely into metadata.

None

Returns:

Name Type Description
Validated AssetRef

class:AssetRef.

Raises:

Type Description
SbomParseError

If required asset fields violate :class:AssetRef validation.

Source code in src/zerobom/backends/sbom_parser.py
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
def derive_sbom_asset(
    data: Mapping[str, Any],
    *,
    asset_id: str,
    backend: str,
    location: str | None = None,
    scope: str | None = None,
    asset_type: str | None = None,
    extra_metadata: Mapping[str, Any] | None = None,
) -> AssetRef:
    """Construct a cloud-agnostic :class:`AssetRef` enriched from SBOM document headers.

    Args:
        data: Parsed CycloneDX or SPDX JSON mapping.
        asset_id: Unique asset identifier (file path, object URI, digest, or resource ID).
        backend: Registered ``zerobom.backends`` name owning the asset.
        location: Optional path, URI, digest, or region string.
        scope: Optional scope override; falls back to document root component or doc name.
        asset_type: Optional asset category override; falls back to metadata component type or
            ``"sbom"``.
        extra_metadata: Optional plugin-supplied opaque metadata merged safely into ``metadata``.

    Returns:
        Validated :class:`AssetRef`.

    Raises:
        SbomParseError: If required asset fields violate :class:`AssetRef` validation.
    """
    raw_meta: dict[str, Any] = {}
    inferred_type: str | None = None
    inferred_scope: str | None = None

    if is_cyclonedx_document(data):
        metadata = data.get("metadata")
        meta_comp = metadata.get("component") if isinstance(metadata, Mapping) else None
        if isinstance(meta_comp, Mapping):
            inferred_type = clean_optional_str(meta_comp.get("type"))
            inferred_scope = clean_optional_str(meta_comp.get("name"))
        raw_meta = {
            "format": "cyclonedx",
            "spec_version": data.get("specVersion"),
            "serial_number": data.get("serialNumber"),
        }
    elif is_spdx_document(data):
        inferred_scope = clean_optional_str(data.get("name")) or clean_optional_str(
            data.get("SPDXID")
        )
        raw_meta = {
            "format": "spdx",
            "spdx_version": data.get("spdxVersion"),
            "document_namespace": data.get("documentNamespace"),
        }

    if extra_metadata:
        raw_meta = {**raw_meta, **extra_metadata}

    try:
        return AssetRef(
            asset_id=asset_id,
            asset_type=clean_optional_str(asset_type) or inferred_type or "sbom",
            backend=backend,
            scope=clean_optional_str(scope) or inferred_scope,
            location=clean_optional_str(location),
            metadata=build_safe_metadata(raw_meta),
        )
    except (ValidationError, ValueError) as exc:
        raise SbomParseError(f"Invalid asset metadata for {asset_id}: {exc}") from exc

match_advisory_with_backend(advisory, backend, *, only_vulnerable=True)

Query an :class:InventoryBackend and evaluate hits deterministically with univers.

Parameters:

Name Type Description Default
advisory OsvAdvisory

Compiled OSV advisory containing affected package definitions.

required
backend InventoryBackend

Any local or plugin-supplied :class:InventoryBackend implementation.

required
only_vulnerable bool

When True, filter out patched/non-vulnerable components.

True

Returns:

Type Description
tuple[MatchResult, ...]

Deduplicated tuple of deterministic :class:MatchResult records.

Source code in src/zerobom/backends/base.py
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
def match_advisory_with_backend(
    advisory: OsvAdvisory,
    backend: InventoryBackend,
    *,
    only_vulnerable: bool = True,
) -> tuple[MatchResult, ...]:
    """Query an :class:`InventoryBackend` and evaluate hits deterministically with ``univers``.

    Args:
        advisory: Compiled OSV advisory containing affected package definitions.
        backend: Any local or plugin-supplied :class:`InventoryBackend` implementation.
        only_vulnerable: When ``True``, filter out patched/non-vulnerable components.

    Returns:
        Deduplicated tuple of deterministic :class:`MatchResult` records.
    """
    if advisory.withdrawn is not None:
        return ()

    queries = build_package_queries(advisory)
    if not queries:
        return ()

    candidates = backend.find_components(queries)
    results: list[MatchResult] = []
    seen: set[tuple[str, str, str, str, str]] = set()

    for component in candidates:
        match = evaluate_inventory_component(advisory, component)
        if match is None:
            continue
        if only_vulnerable and not match.is_vulnerable:
            continue
        dedup_key = (
            match.advisory_id,
            component.asset.asset_id,
            match.matched_purl,
            match.component_purl,
            match.installed_version,
        )
        if dedup_key not in seen:
            seen.add(dedup_key)
            results.append(match)

    return tuple(results)

parse_backend_options(raw_options=(), *, config_path=None, max_config_bytes=MAX_BACKEND_CONFIG_BYTES)

Parse backend plugin configuration from an optional YAML/JSON file and CLI flags.

CLI KEY=VALUE options override keys loaded from config_path. Repeated CLI keys are collected into a list of strings so plugins accepting sequences (such as multiple SBOM paths or namespaces) receive all supplied values cleanly.

Parameters:

Name Type Description Default
raw_options Sequence[str]

Sequence of KEY=VALUE strings supplied on the CLI.

()
config_path Path | None

Optional path to a YAML or JSON backend config file.

None
max_config_bytes int

Maximum allowed config file byte size.

MAX_BACKEND_CONFIG_BYTES

Returns:

Type Description
dict[str, Any]

Validated dictionary ready for :meth:BackendRegistry.create config=....

Raises:

Type Description
BackendConfigError

If the config file is missing/oversized/malformed, contains invalid keys, or any CLI KEY=VALUE option is malformed or contains control chars.

Source code in src/zerobom/backends/registry.py
 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
def parse_backend_options(
    raw_options: Sequence[str] = (),
    *,
    config_path: Path | None = None,
    max_config_bytes: int = MAX_BACKEND_CONFIG_BYTES,
) -> dict[str, Any]:
    """Parse backend plugin configuration from an optional YAML/JSON file and CLI flags.

    CLI ``KEY=VALUE`` options override keys loaded from ``config_path``. Repeated CLI keys
    are collected into a list of strings so plugins accepting sequences (such as multiple SBOM
    paths or namespaces) receive all supplied values cleanly.

    Args:
        raw_options: Sequence of ``KEY=VALUE`` strings supplied on the CLI.
        config_path: Optional path to a YAML or JSON backend config file.
        max_config_bytes: Maximum allowed config file byte size.

    Returns:
        Validated dictionary ready for :meth:`BackendRegistry.create` ``config=...``.

    Raises:
        BackendConfigError: If the config file is missing/oversized/malformed, contains
            invalid keys, or any CLI ``KEY=VALUE`` option is malformed or contains control chars.
    """
    if max_config_bytes < 1:
        raise ValueError("max_config_bytes must be >= 1")

    merged: dict[str, Any] = {}
    if config_path is not None:
        if not config_path.exists() or not config_path.is_file():
            raise BackendConfigError(f"Backend config file does not exist: {config_path}")
        try:
            size = config_path.stat().st_size
        except OSError as exc:
            raise BackendConfigError(f"Failed to stat backend config {config_path}: {exc}") from exc
        if size > max_config_bytes:
            raise BackendConfigError(
                f"Backend config {config_path} exceeds max size of {max_config_bytes} bytes."
            )
        try:
            raw_text = config_path.read_text(encoding="utf-8")
            parsed_yaml = yaml.safe_load(raw_text)
        except (OSError, UnicodeDecodeError, yaml.YAMLError) as exc:
            raise BackendConfigError(
                f"Invalid YAML/JSON in backend config {config_path}: {exc}"
            ) from exc

        if parsed_yaml is None:
            parsed_yaml = {}
        if not isinstance(parsed_yaml, dict):
            raise BackendConfigError(
                f"Backend config {config_path} root must be a YAML/JSON mapping."
            )

        if "options" in parsed_yaml:
            raw_section = parsed_yaml["options"]
            if not isinstance(raw_section, dict):
                raise BackendConfigError(
                    f"Backend config {config_path} 'options' section must be a mapping."
                )
            section: Mapping[Any, Any] = raw_section
        else:
            section = parsed_yaml

        for raw_key, raw_val in section.items():
            if not isinstance(raw_key, str):
                raise BackendConfigError("Backend config keys must be strings.")
            if _has_control_chars(raw_key):
                raise BackendConfigError(
                    f"Invalid backend config key {raw_key!r}; keys must not contain "
                    "control characters."
                )
            key = raw_key.strip()
            if not _CONFIG_KEY_RE.match(key):
                raise BackendConfigError(
                    f"Invalid backend config key {raw_key!r}; expected identifier "
                    "matching ^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$."
                )
            merged[key] = raw_val

    cli_values: dict[str, list[str]] = {}
    for entry in raw_options:
        if "=" not in entry:
            raise BackendConfigError(
                f"Invalid backend option {entry!r}; expected KEY=VALUE format."
            )
        raw_key, raw_val = entry.split("=", 1)
        if _has_control_chars(raw_key) or _has_control_chars(raw_val):
            raise BackendConfigError(
                f"Invalid backend option {entry!r}; options must not contain control characters."
            )
        key = raw_key.strip()
        if not _CONFIG_KEY_RE.match(key):
            raise BackendConfigError(
                f"Invalid backend option {entry!r}; keys must match "
                "^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$ and contain no control characters."
            )
        cli_values.setdefault(key, []).append(raw_val)

    for key, values in cli_values.items():
        merged[key] = values if len(values) > 1 else values[0]

    return merged

parse_cyclonedx_dict(data, *, asset, source_label='<sbom>', max_depth=MAX_CYCLONEDX_DEPTH)

Parse a CycloneDX (1.4-1.6) JSON mapping iteratively with bounded recursion depth.

Parameters:

Name Type Description Default
data Mapping[str, Any]

Decoded CycloneDX JSON object.

required
asset AssetRef

:class:AssetRef attached to every extracted component.

required
source_label str

Human-readable label included in depth-limit diagnostics.

'<sbom>'
max_depth int

Maximum nested components[] traversal depth permitted.

MAX_CYCLONEDX_DEPTH

Returns:

Type Description
tuple[InventoryComponent, ...]

Tuple of normalized :class:InventoryComponent entries.

Raises:

Type Description
ValueError

If max_depth < 1.

SbomParseError

If nesting exceeds max_depth.

Source code in src/zerobom/backends/sbom_parser.py
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
def parse_cyclonedx_dict(
    data: Mapping[str, Any],
    *,
    asset: AssetRef,
    source_label: str = "<sbom>",
    max_depth: int = MAX_CYCLONEDX_DEPTH,
) -> tuple[InventoryComponent, ...]:
    """Parse a CycloneDX (1.4-1.6) JSON mapping iteratively with bounded recursion depth.

    Args:
        data: Decoded CycloneDX JSON object.
        asset: :class:`AssetRef` attached to every extracted component.
        source_label: Human-readable label included in depth-limit diagnostics.
        max_depth: Maximum nested ``components[]`` traversal depth permitted.

    Returns:
        Tuple of normalized :class:`InventoryComponent` entries.

    Raises:
        ValueError: If ``max_depth < 1``.
        SbomParseError: If nesting exceeds ``max_depth``.
    """
    if max_depth < 1:
        raise ValueError("max_depth must be >= 1")

    metadata = data.get("metadata")
    meta_comp = metadata.get("component") if isinstance(metadata, Mapping) else None

    components: list[InventoryComponent] = []
    # Traverse component tree iteratively using an explicit stack to prevent stack overflow.
    stack: list[tuple[Mapping[str, Any], int]] = []

    if isinstance(meta_comp, Mapping):
        stack.append((meta_comp, 0))

    top_components = data.get("components")
    if isinstance(top_components, list):
        # Push in reverse so popped order preserves original document order.
        for item in reversed(top_components):
            if isinstance(item, Mapping):
                stack.append((item, 0))

    while stack:
        comp_dict, depth = stack.pop()
        if depth > max_depth:
            raise SbomParseError(
                f"CycloneDX component nesting in {source_label} exceeds max depth {max_depth}."
            )

        normalized = make_inventory_component(
            raw_name=comp_dict.get("name"),
            raw_version=comp_dict.get("version"),
            raw_purl=comp_dict.get("purl"),
            ecosystem_hint=None,
            namespace_hint=comp_dict.get("group"),
            asset=asset,
            bom_ref=comp_dict.get("bom-ref"),
        )
        if normalized is not None:
            components.append(normalized)

        children = comp_dict.get("components")
        if isinstance(children, list):
            for child in reversed(children):
                if isinstance(child, Mapping):
                    stack.append((child, depth + 1))

    return tuple(components)

parse_sbom_bytes(raw, *, asset_id, backend, location=None, scope=None, asset_type=None, extra_metadata=None, max_bytes=MAX_SBOM_FILE_BYTES, max_depth=MAX_CYCLONEDX_DEPTH)

Decode and parse bounded UTF-8 CycloneDX or SPDX JSON bytes from any storage source.

Parameters:

Name Type Description Default
raw bytes

Unparsed UTF-8 JSON bytes representing a CycloneDX or SPDX document.

required
asset_id str

Unique asset identifier (file path, object URI, image digest, etc.).

required
backend str

Registered zerobom.backends plugin name.

required
location str | None

Optional manifest location or region string.

None
scope str | None

Optional project/cluster/bucket scope override.

None
asset_type str | None

Optional asset category override.

None
extra_metadata Mapping[str, Any] | None

Optional extra metadata merged safely into the generated AssetRef.

None
max_bytes int

Maximum allowed raw payload size prior to UTF-8/JSON decoding.

MAX_SBOM_FILE_BYTES
max_depth int

Maximum permitted nested CycloneDX component depth.

MAX_CYCLONEDX_DEPTH

Returns:

Type Description
tuple[InventoryComponent, ...]

Tuple of normalized :class:InventoryComponent entries.

Raises:

Type Description
ValueError

If max_bytes < 1 or max_depth < 1.

SbomParseError

If size exceeds max_bytes, JSON is malformed, root is not a JSON object, or schema is neither CycloneDX nor SPDX 2.x.

Source code in src/zerobom/backends/sbom_parser.py
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
def parse_sbom_bytes(
    raw: bytes,
    *,
    asset_id: str,
    backend: str,
    location: str | None = None,
    scope: str | None = None,
    asset_type: str | None = None,
    extra_metadata: Mapping[str, Any] | None = None,
    max_bytes: int = MAX_SBOM_FILE_BYTES,
    max_depth: int = MAX_CYCLONEDX_DEPTH,
) -> tuple[InventoryComponent, ...]:
    """Decode and parse bounded UTF-8 CycloneDX or SPDX JSON bytes from any storage source.

    Args:
        raw: Unparsed UTF-8 JSON bytes representing a CycloneDX or SPDX document.
        asset_id: Unique asset identifier (file path, object URI, image digest, etc.).
        backend: Registered ``zerobom.backends`` plugin name.
        location: Optional manifest location or region string.
        scope: Optional project/cluster/bucket scope override.
        asset_type: Optional asset category override.
        extra_metadata: Optional extra metadata merged safely into the generated ``AssetRef``.
        max_bytes: Maximum allowed raw payload size prior to UTF-8/JSON decoding.
        max_depth: Maximum permitted nested CycloneDX component depth.

    Returns:
        Tuple of normalized :class:`InventoryComponent` entries.

    Raises:
        ValueError: If ``max_bytes < 1`` or ``max_depth < 1``.
        SbomParseError: If size exceeds ``max_bytes``, JSON is malformed, root is not a JSON
            object, or schema is neither CycloneDX nor SPDX 2.x.
    """
    if max_bytes < 1 or max_depth < 1:
        raise ValueError("max_bytes and max_depth must be >= 1")

    if len(raw) > max_bytes:
        raise SbomParseError(
            f"SBOM payload {asset_id} exceeds maximum size of {max_bytes} bytes ({len(raw)} bytes)."
        )

    try:
        data = json.loads(raw.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError, RecursionError) as exc:
        raise SbomParseError(f"Invalid JSON in SBOM payload {asset_id}: {exc}") from exc

    if not isinstance(data, dict):
        raise SbomParseError(f"SBOM root in {asset_id} must be a JSON object.")

    if not is_cyclonedx_document(data) and not is_spdx_document(data):
        raise SbomParseError(
            f"Unrecognized SBOM schema in {asset_id} (expected CycloneDX or SPDX 2.x JSON)."
        )

    asset = derive_sbom_asset(
        data,
        asset_id=asset_id,
        backend=backend,
        location=location,
        scope=scope,
        asset_type=asset_type,
        extra_metadata=extra_metadata,
    )
    if is_cyclonedx_document(data):
        return parse_cyclonedx_dict(data, asset=asset, source_label=asset_id, max_depth=max_depth)
    return parse_spdx_dict(data, asset=asset)

parse_spdx_dict(data, *, asset)

Parse an SPDX (2.2-2.3) JSON mapping into normalized components.

Parameters:

Name Type Description Default
data Mapping[str, Any]

Decoded SPDX JSON object.

required
asset AssetRef

:class:AssetRef attached to every extracted component.

required

Returns:

Type Description
tuple[InventoryComponent, ...]

Tuple of normalized :class:InventoryComponent entries.

Source code in src/zerobom/backends/sbom_parser.py
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
def parse_spdx_dict(
    data: Mapping[str, Any],
    *,
    asset: AssetRef,
) -> tuple[InventoryComponent, ...]:
    """Parse an SPDX (2.2-2.3) JSON mapping into normalized components.

    Args:
        data: Decoded SPDX JSON object.
        asset: :class:`AssetRef` attached to every extracted component.

    Returns:
        Tuple of normalized :class:`InventoryComponent` entries.
    """
    components: list[InventoryComponent] = []
    packages = data.get("packages")
    if not isinstance(packages, list):
        return ()

    for pkg in packages:
        if not isinstance(pkg, Mapping):
            continue
        raw_ver = clean_optional_str(pkg.get("versionInfo"))
        if raw_ver is not None and raw_ver.upper() in _SPDX_MISSING_SENTINELS:
            raw_ver = None
        raw_purl = _extract_spdx_purl(pkg)

        normalized = make_inventory_component(
            raw_name=pkg.get("name"),
            raw_version=raw_ver,
            raw_purl=raw_purl,
            ecosystem_hint=None,
            namespace_hint=None,
            asset=asset,
            bom_ref=pkg.get("SPDXID"),
        )
        if normalized is not None:
            components.append(normalized)

    return tuple(components)