Skip to content

Models & Contracts

Canonical immutable Pydantic v2 contracts (strict=True, extra="forbid", frozen=True) shared across ingestion, extraction, verification, inventory backends, and alerting outputs.

models

Canonical strict Pydantic v2 data contracts for zerobom.

All models in this module inherit from :class:StrictModel, which enforces:

  • strict=True: rejects implicit type coercion across module boundaries.
  • extra="forbid": fails closed on unexpected or prompt-injected fields.
  • frozen=True: guarantees immutability once constructed.

ArticleStateRecord

Bases: StrictModel

Persisted ingestion and processing state for a canonical article URL.

Attributes:

Name Type Description
canonical_url str

Canonicalized article URI used as primary key.

content_sha256 str

Lowercase 64-character SHA-256 hex digest of normalized body text.

etag str | None

Optional HTTP ETag header from the last fetch.

last_modified str | None

Optional HTTP Last-Modified header from the last fetch.

last_seen_at datetime

Timestamp when the article was last processed.

advisory_id str | None

Compiled PRECVE advisory ID if produced.

routing RoutingDecision | None

Last verification routing decision if evaluated.

ArticleType

Bases: StrEnum

Classification of a fetched article's disclosure role prior to routing.

AssetRef

Bases: StrictModel

Cloud-agnostic reference identifying where an inventory component was observed.

Core models deliberately exclude provider-specific fields (e.g., cloud account IDs or regions). Plugins may attach opaque display attributes via metadata.

Attributes:

Name Type Description
asset_id str

Unique identifier (file path, repo slug, digest, or resource ID).

asset_type str

Normalized category (e.g., "sbom", "container_image", "compute").

backend str

Registered inventory backend name (e.g., "local_sbom").

scope str | None

Optional organizational, project, cluster, or environment boundary.

location str | None

Optional manifest path, layer, or regional location string.

metadata dict[str, str]

Bounded opaque key-value attributes attached by a backend plugin.

ClaimVerificationResult

Bases: StrictModel

Per-claim verification and two-axis credibility scoring outcome.

Attributes:

Name Type Description
claim ExtractedPackageClaim

Original extracted claim being evaluated.

grounding GroundingResult

Two-stage verbatim quote grounding outcome.

purl PurlResolutionResult

Canonical PURL resolution and registry verification outcome.

has_valid_version_range bool

True if all version constraints parsed cleanly.

has_bounded_version_range bool

True if at least one valid bounded/exact range was present.

extraction_specificity float

Normalized extraction quality score in [0.0, 1.0].

composite_score float

Two-axis source_tier_weight * extraction_specificity score.

routing RoutingDecision

Deterministic routing action (AUTO, TRIAGE, or DROP).

reasons tuple[str, ...]

Aggregated diagnostics across PURL, grounding, versions, and caps.

CredibilityReport

Bases: StrictModel

Advisory-level credibility report aggregating verified and dropped claims.

Attributes:

Name Type Description
article_url str

Source article URI.

source_tier SourceTier

Publisher credibility tier.

source_tier_weight float

Numeric weight derived from source_tier.

extraction_specificity float

Highest specificity among accepted claims (or all if all dropped).

composite_score float

Highest composite score across evaluated claims.

routing RoutingDecision

Advisory-level routing outcome.

claim_results tuple[ClaimVerificationResult, ...]

Every evaluated claim result in input order.

accepted_claims tuple[ClaimVerificationResult, ...]

Claims routed to AUTO or TRIAGE.

dropped_claims tuple[ClaimVerificationResult, ...]

Claims routed to DROP.

reasons tuple[str, ...]

Advisory-level summary diagnostics.

DeliveryOutboxRecord

Bases: StrictModel

Persistent at-least-once outbound alert delivery record stored in SQLite.

Attributes:

Name Type Description
advisory_id str

Compiled OSV advisory identifier (e.g., PRECVE-2026-...).

content_sha256 str

Normalized article body digest associated with the outcome.

sink_key str

Deterministic identifier of the target sink (webhook, Slack, GitHub, triage).

outcome_json str

Serialized :class:PipelineOutcome JSON payload for retry delivery.

status Literal['pending', 'delivered', 'failed']

Current delivery state (pending, delivered, or failed).

attempts int

Total delivery attempts recorded so far.

last_error str | None

Sanitized summary of the most recent delivery failure, if any.

created_at datetime

UTC timestamp when the outbox entry was enqueued.

delivered_at datetime | None

UTC timestamp when the sink acknowledged delivery, if delivered.

ExtractedAdvisory

Bases: StrictModel

Structured advisory candidate extracted from a :class:RawArticle.

Attributes:

Name Type Description
article_url str

Canonical URI of the source article.

title str

Non-empty advisory title.

summary str

Concise vulnerability summary.

details str

Extended technical writeup.

article_type ArticleType | None

Optional disclosure-role classification emitted by the extractor.

claims tuple[ExtractedPackageClaim, ...]

Zero or more package vulnerability claims (empty for non-vuln posts).

severity VulnerabilitySeverity

Qualitative severity rating.

cwe_ids tuple[str, ...]

Associated CWE identifiers.

references tuple[str, ...]

Additional validated external reference URIs.

known_aliases tuple[str, ...]

Optional CVE/GHSA aliases if mentioned.

published_at datetime | None

Optional publication timestamp override.

prompt_version str | None

Optional version tag of the extraction prompt used.

extractor_model str | None

Optional LLM identifier that produced the candidate advisory.

ExtractedPackageClaim

Bases: StrictModel

Single affected package claim produced by an upstream extractor.

Attributes:

Name Type Description
raw_package_name str

Unnormalized package identifier or PURL string.

ecosystem str | None

Optional ecosystem hint (e.g., "pypi", "npm", "Maven").

namespace str | None

Optional package namespace/scope/groupId.

distro_release str | None

Optional OS distro release or stream qualifier (e.g., "8", "9").

version_constraints tuple[VersionConstraint, ...]

Tuple of extracted version constraints.

evidence_quote str

Verbatim supporting quote copied from the source article.

supporting_quotes tuple[str, ...]

Optional additional verbatim quotes for multi-update advisories.

claim_aliases tuple[str, ...]

Optional per-claim advisory aliases (e.g., CVE/GHSA IDs for multi-flaw posts).

fix_commit_url str | None

Optional validated URI to a fix commit or PR.

poc_url str | None

Optional validated URI to a proof-of-concept or exploit writeup.

FeedEntry

Bases: StrictModel

Single item discovered from an RSS or Atom feed.

Attributes:

Name Type Description
url str

HTTP/HTTPS URL of the linked blog post.

title str

Post title.

summary str

Feed-level snippet/summary text.

published_at datetime

Publication timestamp.

published_at_inferred bool

True when the feed/index lacked a timestamp and fell back to now.

source_name str

Name of the parent feed.

source_tier SourceTier

Credibility tier inherited from the parent feed.

FeedKind

Bases: StrEnum

Discovery format configured for an allowlisted source endpoint.

FeedPollResult

Bases: StrictModel

Polling telemetry and optional error details for one source feed.

Attributes:

Name Type Description
feed_name str

Human-readable feed name.

feed_url str

Configured HTTP/HTTPS feed URL.

status FeedPollStatus

Poll outcome status (ok, not_modified, or error).

entries_discovered int

Number of candidate feed/sitemap/index links discovered.

articles_polled int

Number of new or edited articles queued for processing.

error str | None

Diagnostic error summary when status is error.

FeedPollStatus

Bases: StrEnum

Per-feed outcome status recorded during an isolated watch poll.

GroundingMatchType

Bases: StrEnum

How the evidence quote matched the raw article body.

GroundingResult

Bases: StrictModel

Verification output of two-stage verbatim quote grounding.

Attributes:

Name Type Description
status GroundingStatus

Overall grounding verdict (VERIFIED, QUOTE_ONLY_WEAK, or UNGROUNDED).

match_type GroundingMatchType

Whether Stage 1 matched verbatim or via Unicode/whitespace normalization.

quote_found_in_article bool

True if the quote matched inside the article body.

package_token_found bool

True if a normalized package identifier appeared inside the quote.

version_tokens_found bool

True if a claimed version token appeared inside the quote (or none were claimed).

matched_span tuple[int, int] | None

Optional (start, end) slice offsets within exact or normalized body.

reasons tuple[str, ...]

Diagnostic messages explaining any grounding degradation or failure.

GroundingStatus

Bases: StrEnum

Outcome of two-stage verbatim quote grounding.

InventoryComponent

Bases: StrictModel

Normalized software package entry returned by an inventory backend.

Attributes:

Name Type Description
name str

Raw or normalized component package name.

version str

Installed package version string.

purl str | None

Full raw Package URL string if present in the inventory source.

canonical_purl str | None

Versionless canonical PURL if resolved cleanly.

ecosystem str | None

Normalized PURL ecosystem type, if known.

namespace str | None

Package namespace/scope/groupId, if known.

distro_qualifier str | None

Raw ?distro= qualifier extracted from PURL or SBOM metadata.

upstream_package str | None

Source package name from ?upstream= qualifier, if any.

upstream_version str | None

Source package version embedded in ?upstream=, if any.

asset AssetRef

Cloud-agnostic :class:AssetRef identifying where the component resides.

bom_ref str | None

Optional CycloneDX bom-ref or SPDX SPDXID identifier.

LenientOsvModel

Bases: BaseModel

Base contract for reading external OSV v1.x JSON documents safely (extra='ignore').

MatchResult

Bases: StrictModel

Deterministic match evaluation of an SBOM component against an OSV advisory.

Attributes:

Name Type Description
advisory_id str

Compiled OSV advisory identifier (e.g., PRECVE-2026-A3F91C04).

component_purl str

Original SBOM component PURL (or synthetic fallback identifier).

installed_version str

Installed version string checked against OSV ranges.

matched_purl str

Canonical package PURL from the advisory that matched.

ecosystem str

OSV ecosystem string used for version math.

is_vulnerable bool

True when installed_version falls within an affected range/version.

matched_range str | None

Human-readable summary of evaluated ranges/versions.

fixed_versions tuple[str, ...]

Deduplicated fixed version strings from the advisory.

evidence_quote str | None

Grounded quote supporting the matched advisory claim.

sbom_source str | None

Optional filename or backend location for the evaluated component.

asset AssetRef | None

Optional cloud-agnostic :class:AssetRef associated with the component.

matched_via Literal['purl', 'upstream', 'name_fallback']

Mechanism used to link component to advisory (purl, upstream, or name_fallback).

OsvAdvisory

Bases: StrictModel

Standard OSV v1.6.7 JSON advisory contract.

Attributes:

Name Type Description
schema_version str

OSV schema version string (defaults to "1.6.7").

id str

Unique advisory identifier (e.g., PRECVE-2026-A3F91C04).

modified datetime

Last modification timestamp.

published datetime

Initial publication timestamp.

summary str

Short vulnerability summary.

details str

Detailed writeup text.

aliases tuple[str, ...]

Known upstream CVE/GHSA identifiers, if any.

affected tuple[OsvAffected, ...]

Non-empty tuple of affected packages and version ranges.

references tuple[OsvReference, ...]

Supporting article, fix, PoC, and web URLs.

database_specific dict[str, Any]

Extension metadata (stores zerobom credibility context).

to_osv_dict()

Serialize this advisory to an OSV v1.6 JSON-compatible dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary conforming to the OSV v1.6 JSON schema with RFC 3339 UTC Z

dict[str, Any]

timestamps and empty optional collections omitted.

Source code in src/zerobom/models.py
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
def to_osv_dict(self) -> dict[str, Any]:
    """Serialize this advisory to an OSV v1.6 JSON-compatible dictionary.

    Returns:
        Dictionary conforming to the OSV v1.6 JSON schema with RFC 3339 UTC ``Z``
        timestamps and empty optional collections omitted.
    """
    data: dict[str, Any] = self.model_dump(mode="json", exclude_none=True)
    data["modified"] = _format_rfc3339_utc(self.modified)
    data["published"] = _format_rfc3339_utc(self.published)
    if self.withdrawn is not None:
        data["withdrawn"] = _format_rfc3339_utc(self.withdrawn)

    for opt_key in (
        "aliases",
        "related",
        "upstream",
        "severity",
        "references",
        "database_specific",
    ):
        if not data.get(opt_key):
            data.pop(opt_key, None)

    cleaned_affected: list[dict[str, Any]] = []
    for item in data.get("affected", []):
        if not item.get("ranges"):
            item.pop("ranges", None)
        if not item.get("versions"):
            item.pop("versions", None)
        cleaned_affected.append(item)
    data["affected"] = cleaned_affected

    return data

OsvAdvisoryInput

Bases: LenientOsvModel

Spec-compliant external OSV v1.x consumer contract for zerobom scan --osv.

Accepts optional and extension fields defined by the OSV schema (severity, withdrawn, related, upstream, credits, ecosystem_specific, GIT repo, and omitted published or summary) while keeping full control-character and URI-scheme sanitization enforced.

OsvAffected

Bases: StrictModel

OSV schema affected[] package entry.

OsvAffectedInput

Bases: LenientOsvModel

External OSV affected[] entry accepting ecosystem_specific & severity.

OsvCredit

Bases: LenientOsvModel

Optional credit attribution entry defined by OSV v1.x.

OsvPackage

Bases: StrictModel

OSV schema affected[].package object.

OsvPackageInput

Bases: LenientOsvModel

External OSV affected[].package entry allowing optional purl.

OsvRange

Bases: StrictModel

OSV schema affected[].ranges[] object.

OsvRangeEvent

Bases: StrictModel

OSV schema range event object containing exactly one boundary key.

OsvRangeEventInput

Bases: LenientOsvModel

External OSV range event allowing arbitrary extra event metadata cleanly.

OsvRangeInput

Bases: LenientOsvModel

External OSV affected[].ranges[] entry supporting GIT repo & extra metadata.

OsvReference

Bases: StrictModel

OSV schema references[] entry.

OsvReferenceInput

Bases: LenientOsvModel

External OSV references[] entry with scheme-checked URI.

OsvSeverity

Bases: StrictModel

OSV schema severity vector entry (e.g., CVSS_V3 / CVSS_V4).

PackageQuery

Bases: StrictModel

Query descriptor derived from an OSV affected entry for inventory backends.

Attributes:

Name Type Description
canonical_purl str

Versionless canonical Package URL to search for.

ecosystem str

Canonical PURL ecosystem type (e.g., "pypi", "deb").

osv_ecosystem str

Original OSV ecosystem string (e.g., "Debian:11", "PyPI").

namespace str | None

Normalized package namespace/scope/groupId, if any.

name str

Normalized package name.

distro_release str | None

Normalized OS distro release (e.g., "debian-11"), if qualified.

PipelineOutcome

Bases: StrictModel

End-to-end result of running an article or OSV advisory through the zerobom pipeline.

Attributes:

Name Type Description
article RawArticle | None

Ingested source article, if applicable (None in pure scan mode).

prefilter PrefilterResult | None

Deterministic pre-filter result when pre-filtering executed.

advisory ExtractedAdvisory | None

Extracted advisory candidate when extraction executed.

credibility CredibilityReport | None

Verification and two-axis credibility report.

osv OsvAdvisory | None

Compiled OSV v1.6.7 advisory if at least one claim survived verification.

matches tuple[MatchResult, ...]

Inventory match evaluations returned by the configured backend.

skipped_reason str | None

Diagnostic reason when an article stopped early (e.g., prefilter drop).

has_vulnerable_hits property

Return True if at least one vulnerable inventory component matched.

vulnerable_matches property

Return only vulnerable :class:MatchResult entries.

PrefilterResult

Bases: StrictModel

Output of deterministic keyword/regex filtering prior to LLM extraction.

Attributes:

Name Type Description
passed bool

True when the article warrants LLM extraction.

score float

Heuristic relevance score in [0.0, 1.0].

vuln_signals tuple[str, ...]

Matched vulnerability indicator tags.

software_signals tuple[str, ...]

Matched package/version/ecosystem indicator tags.

marketing_signals tuple[str, ...]

Matched promotional/non-vulnerability indicator tags.

extracted_aliases tuple[str, ...]

Reserved CVE/GHSA identifiers extracted deterministically.

reasons tuple[str, ...]

Diagnostic messages explaining pass/drop rationale.

PurlResolutionResult

Bases: StrictModel

Deterministic canonical Package URL resolution and optional registry check output.

Attributes:

Name Type Description
canonical_purl str | None

Canonical Package URL string, or None if resolution failed.

ecosystem str | None

Canonical PURL ecosystem type (e.g., "pypi", "deb").

osv_ecosystem str | None

Canonical OSV ecosystem name (e.g., "PyPI", "Debian").

namespace str | None

Resolved package namespace/scope/groupId, if any.

name str | None

Normalized package name.

is_valid bool

True when resolution succeeded, name is non-generic, and not 404 in registry.

is_blocked_generic bool

True if rejected by the generic-name blocklist.

registry_status RegistryStatus

Upstream registry existence verification outcome.

reasons tuple[str, ...]

Diagnostic explanations for failures or non-fatal registry errors.

RawArticle

Bases: StrictModel

Normalized ingested security blog article prior to extraction and verification.

Attributes:

Name Type Description
url str

Canonical source URI of the ingested article.

title str

Non-empty article headline.

body str

Cleaned plain-text article body used for verbatim quote grounding.

source_name str

Human-readable publisher name (e.g., "Project Zero").

source_tier SourceTier

Credibility tier weight category of the publisher.

published_at datetime

Publication timestamp.

published_at_inferred bool

True when published_at fell back to fetch time rather than an explicit feed or HTML metadata date.

fetched_at datetime | None

Optional retrieval timestamp.

author str | None

Optional author attribution.

RegistryStatus

Bases: StrEnum

Result of checking package existence against an upstream registry.

RoutingDecision

Bases: StrEnum

Credibility routing outcome based on the two-axis composite score.

SourceFeedConfig

Bases: StrictModel

Configuration entry for an allowlisted security blog discovery source.

Attributes:

Name Type Description
name str

Human-readable publisher name.

url str

HTTP/HTTPS feed, sitemap, or blog index URL.

tier SourceTier

Source credibility tier assigned to articles from this feed.

kind FeedKind

Discovery format (rss, sitemap, html_index, or auto).

url_prefix str | None

Optional same-origin URL prefix used to filter sitemap or HTML index links.

enabled bool

Whether the feed is active during polling.

tags tuple[str, ...]

Optional descriptive tags for filtering/reporting.

SourcesConfig

Bases: StrictModel

Top-level configuration parsed from sources.yaml.

Attributes:

Name Type Description
version int

Schema version integer (must be >= 1).

feeds tuple[SourceFeedConfig, ...]

Configured RSS/Atom source feeds.

StrictModel

Bases: BaseModel

Base model enforcing strict validation, immutability, and no extra fields.

VersionConstraint

Bases: StrictModel

Structured raw affected version bounds prior to deterministic compilation.

Attributes:

Name Type Description
introduced str | None

Inclusive lower bound (or "0" when unknown/since origin).

fixed str | None

Exclusive upper bound representing the first patched version.

last_affected str | None

Inclusive upper bound representing the last vulnerable version.

exact str | None

Single vulnerable version string (mutually exclusive with range bounds).

raw_specifier str | None

Raw range expression (e.g., ">= 1.2.0, < 1.5.4").

is_unbounded bool

Whether all versions from introduced onward are claimed vulnerable.

VulnerabilitySeverity

Bases: StrEnum

Normalized qualitative vulnerability severity.

WatchItemError

Bases: StrictModel

Non-fatal isolated failure captured during zerobom watch execution.

Attributes:

Name Type Description
stage Literal['feed', 'article_fetch', 'extract', 'backend', 'alert']

Pipeline stage where the failure occurred.

source_name str

Source feed or sink identifier associated with the failure.

target str

Failing feed URL, article URL, or delivery sink identifier.

error str

Sanitized diagnostic error message.

WatchReport

Bases: StrictModel

Fault-isolated summary returned by :func:zerobom.pipeline.watch_feeds_report.

Attributes:

Name Type Description
per_feed tuple[FeedPollResult, ...]

Per-feed discovery and poll status records.

outcomes tuple[PipelineOutcome, ...]

Successfully evaluated :class:PipelineOutcome objects.

errors tuple[WatchItemError, ...]

Isolated non-fatal errors encountered across feeds, articles, or sinks.

has_errors property

Return True if any feed, article, or sink recorded an isolated error.