Skip to content

Ingestion & State

SSRF-hardened HTTP/HTML article fetching, XML/sitemap/HTML feed discovery, SQLite ETag/SHA-256 deduplication store, and the pre-LLM deterministic vulnerability prefilter.

ingest

Hardened HTTP/RSS ingestion, SQLite state tracking, and pre-LLM filtering.

FetchError

Bases: RuntimeError

Raised when fetching or decoding a remote feed or article fails safely.

FetchResponse(final_url, status_code, content_type, body, etag=None, last_modified=None, not_modified=False) dataclass

Bounded HTTP response payload returned by :class:SafeHttpFetcher.

Attributes:

Name Type Description
final_url str

Final validated URL after any permitted redirects.

status_code int

HTTP status code.

content_type str

Normalized MIME type (without charset parameters).

body bytes

Raw response bytes (empty on 304 Not Modified).

etag str | None

Optional HTTP ETag response header.

last_modified str | None

Optional HTTP Last-Modified response header.

not_modified bool

True when the server responded with HTTP 304 Not Modified.

IngestStateStore(db_path)

SQLite-backed state tracking canonical article hashes, cache validators, and alert outbox.

Unlike naive URL-only deduplication, storing content_sha256 alongside ETag and Last-Modified headers allows zerobom watch to skip unchanged articles cheaply via HTTP 304 while automatically re-processing live advisories that receive post-publish edits (such as newly added fixed versions). Schema version 2 adds an at-least-once delivery_outbox table so transient sink outages never drop alerts.

Initialize the SQLite ingestion state store and ensure schema existence.

Parameters:

Name Type Description Default
db_path Path | str

Path to the SQLite database file (parent directories created if needed).

required
Source code in src/zerobom/ingest/state.py
49
50
51
52
53
54
55
56
57
def __init__(self, db_path: Path | str) -> None:
    """Initialize the SQLite ingestion state store and ensure schema existence.

    Args:
        db_path: Path to the SQLite database file (parent directories created if needed).
    """
    self._db_path = Path(db_path)
    self._db_path.parent.mkdir(parents=True, exist_ok=True)
    self._init_schema()

conditional_headers(url)

Build HTTP conditional request headers from persisted ETag / Last-Modified.

Source code in src/zerobom/ingest/state.py
159
160
161
162
163
164
165
166
167
168
169
def conditional_headers(self, url: str) -> dict[str, str]:
    """Build HTTP conditional request headers from persisted ``ETag`` / ``Last-Modified``."""
    existing = self.get(url)
    if existing is None:
        return {}
    headers: dict[str, str] = {}
    if existing.etag:
        headers["If-None-Match"] = existing.etag
    if existing.last_modified:
        headers["If-Modified-Since"] = existing.last_modified
    return headers

count()

Return total number of tracked canonical article URLs.

Source code in src/zerobom/ingest/state.py
231
232
233
234
235
236
237
238
def count(self) -> int:
    """Return total number of tracked canonical article URLs."""
    conn = self._connect()
    try:
        row = conn.execute("SELECT COUNT(*) FROM article_state").fetchone()
        return int(row[0]) if row is not None else 0
    finally:
        conn.close()

enqueue_delivery(advisory_id, content_sha256, sink_key, outcome, *, created_at=None)

Persist an idempotent pending outbound alert record for at-least-once delivery.

Source code in src/zerobom/ingest/state.py
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
def enqueue_delivery(
    self,
    advisory_id: str,
    content_sha256: str,
    sink_key: str,
    outcome: PipelineOutcome,
    *,
    created_at: datetime | None = None,
) -> None:
    """Persist an idempotent pending outbound alert record for at-least-once delivery."""
    now = created_at or datetime.now(UTC)
    outcome_json = outcome.model_dump_json()
    conn = self._connect()
    try:
        with conn:
            self._insert_outbox_row(
                conn,
                advisory_id=advisory_id,
                content_sha256=content_sha256,
                sink_key=sink_key,
                outcome_json=outcome_json,
                created_at=now,
            )
    finally:
        conn.close()

get(url)

Retrieve the persisted :class:ArticleStateRecord for a URL, if recorded.

Source code in src/zerobom/ingest/state.py
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
def get(self, url: str) -> ArticleStateRecord | None:
    """Retrieve the persisted :class:`ArticleStateRecord` for a URL, if recorded."""
    canonical = canonicalize_url(url)
    conn = self._connect()
    try:
        # Parameterized SQL (?) prevents injection regardless of URL query strings.
        row = conn.execute(
            """
            SELECT canonical_url, content_sha256, etag, last_modified,
                   last_seen_at, advisory_id, routing
            FROM article_state
            WHERE canonical_url = ?
            """,
            (canonical,),
        ).fetchone()
        if row is None:
            return None

        raw_routing = row[6]
        routing = RoutingDecision(str(raw_routing)) if raw_routing is not None else None
        return ArticleStateRecord(
            canonical_url=str(row[0]),
            content_sha256=str(row[1]),
            etag=str(row[2]) if row[2] is not None else None,
            last_modified=str(row[3]) if row[3] is not None else None,
            last_seen_at=datetime.fromisoformat(str(row[4])),
            advisory_id=str(row[5]) if row[5] is not None else None,
            routing=routing,
        )
    finally:
        conn.close()

has_changed(url, content_sha256)

Return True if url is unseen or its normalized content_sha256 changed.

Source code in src/zerobom/ingest/state.py
152
153
154
155
156
157
def has_changed(self, url: str, content_sha256: str) -> bool:
    """Return True if ``url`` is unseen or its normalized ``content_sha256`` changed."""
    existing = self.get(url)
    if existing is None:
        return True
    return existing.content_sha256 != content_sha256.strip().lower()

mark_delivered(advisory_id, content_sha256, sink_key, *, delivered_at=None)

Mark an outbox alert delivery acknowledged by its target sink.

Source code in src/zerobom/ingest/state.py
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
def mark_delivered(
    self,
    advisory_id: str,
    content_sha256: str,
    sink_key: str,
    *,
    delivered_at: datetime | None = None,
) -> None:
    """Mark an outbox alert delivery acknowledged by its target sink."""
    ts = (delivered_at or datetime.now(UTC)).isoformat()
    conn = self._connect()
    try:
        with conn:
            conn.execute(
                """
                UPDATE delivery_outbox
                SET status = 'delivered',
                    attempts = attempts + 1,
                    last_error = NULL,
                    delivered_at = ?
                WHERE advisory_id = ? AND content_sha256 = ? AND sink_key = ?
                """,
                (ts, advisory_id, content_sha256.strip().lower(), sink_key),
            )
    finally:
        conn.close()

mark_delivery_failed(advisory_id, content_sha256, sink_key, error)

Record a transient sink delivery failure so subsequent runs retry automatically.

Source code in src/zerobom/ingest/state.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def mark_delivery_failed(
    self,
    advisory_id: str,
    content_sha256: str,
    sink_key: str,
    error: str,
) -> None:
    """Record a transient sink delivery failure so subsequent runs retry automatically."""
    clean_err = _sanitize_error_summary(error)
    conn = self._connect()
    try:
        with conn:
            conn.execute(
                """
                UPDATE delivery_outbox
                SET status = 'failed',
                    attempts = attempts + 1,
                    last_error = ?
                WHERE advisory_id = ? AND content_sha256 = ? AND sink_key = ?
                """,
                (clean_err, advisory_id, content_sha256.strip().lower(), sink_key),
            )
    finally:
        conn.close()

mark_seen(url, content_sha256, *, etag=None, last_modified=None, advisory_id=None, routing=None, seen_at=None)

Convenience wrapper to build and persist an :class:ArticleStateRecord.

Source code in src/zerobom/ingest/state.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def mark_seen(
    self,
    url: str,
    content_sha256: str,
    *,
    etag: str | None = None,
    last_modified: str | None = None,
    advisory_id: str | None = None,
    routing: RoutingDecision | None = None,
    seen_at: datetime | None = None,
) -> ArticleStateRecord:
    """Convenience wrapper to build and persist an :class:`ArticleStateRecord`."""
    record = ArticleStateRecord(
        canonical_url=canonicalize_url(url),
        content_sha256=content_sha256,
        etag=etag,
        last_modified=last_modified,
        last_seen_at=seen_at or datetime.now(UTC),
        advisory_id=advisory_id,
        routing=routing,
    )
    self.upsert(record)
    return record

pending_deliveries(*, sink_key=None, limit=200)

Return undelivered (pending or failed) outbox items ordered oldest first.

Source code in src/zerobom/ingest/state.py
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
def pending_deliveries(
    self,
    *,
    sink_key: str | None = None,
    limit: int = 200,
) -> tuple[DeliveryOutboxRecord, ...]:
    """Return undelivered (``pending`` or ``failed``) outbox items ordered oldest first."""
    if limit < 1:
        raise ValueError("limit must be >= 1")
    conn = self._connect()
    try:
        if sink_key is not None:
            rows = conn.execute(
                """
                SELECT advisory_id, content_sha256, sink_key, outcome_json, status,
                       attempts, last_error, created_at, delivered_at
                FROM delivery_outbox
                WHERE status IN ('pending', 'failed') AND sink_key = ?
                ORDER BY created_at ASC
                LIMIT ?
                """,
                (sink_key, limit),
            ).fetchall()
        else:
            rows = conn.execute(
                """
                SELECT advisory_id, content_sha256, sink_key, outcome_json, status,
                       attempts, last_error, created_at, delivered_at
                FROM delivery_outbox
                WHERE status IN ('pending', 'failed')
                ORDER BY created_at ASC
                LIMIT ?
                """,
                (limit,),
            ).fetchall()
        records: list[DeliveryOutboxRecord] = []
        for row in rows:
            records.append(
                DeliveryOutboxRecord(
                    advisory_id=str(row[0]),
                    content_sha256=str(row[1]),
                    sink_key=str(row[2]),
                    outcome_json=str(row[3]),
                    status=row[4],
                    attempts=int(row[5]),
                    last_error=str(row[6]) if row[6] is not None else None,
                    created_at=datetime.fromisoformat(str(row[7])),
                    delivered_at=(
                        datetime.fromisoformat(str(row[8])) if row[8] is not None else None
                    ),
                )
            )
        return tuple(records)
    finally:
        conn.close()

record_processed_with_outbox(url, content_sha256, *, extra_urls=(), etag=None, last_modified=None, advisory_id=None, routing=None, sink_keys=(), outcome=None, seen_at=None)

Atomically persist article state (including redirects) and enqueue pending sink rows.

Source code in src/zerobom/ingest/state.py
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
def record_processed_with_outbox(
    self,
    url: str,
    content_sha256: str,
    *,
    extra_urls: Sequence[str] = (),
    etag: str | None = None,
    last_modified: str | None = None,
    advisory_id: str | None = None,
    routing: RoutingDecision | None = None,
    sink_keys: Sequence[str] = (),
    outcome: PipelineOutcome | None = None,
    seen_at: datetime | None = None,
) -> ArticleStateRecord:
    """Atomically persist article state (including redirects) and enqueue pending sink rows."""
    now = seen_at or datetime.now(UTC)
    primary_canonical = canonicalize_url(url)
    primary_record = ArticleStateRecord(
        canonical_url=primary_canonical,
        content_sha256=content_sha256,
        etag=etag,
        last_modified=last_modified,
        last_seen_at=now,
        advisory_id=advisory_id,
        routing=routing,
    )
    seen_urls: set[str] = {primary_canonical}
    records: list[ArticleStateRecord] = [primary_record]
    for raw_extra in extra_urls:
        canon_extra = canonicalize_url(raw_extra)
        if canon_extra in seen_urls:
            continue
        seen_urls.add(canon_extra)
        records.append(
            ArticleStateRecord(
                canonical_url=canon_extra,
                content_sha256=content_sha256,
                etag=etag,
                last_modified=last_modified,
                last_seen_at=now,
                advisory_id=advisory_id,
                routing=routing,
            )
        )

    outcome_json = (
        outcome.model_dump_json()
        if (advisory_id is not None and outcome is not None and sink_keys)
        else None
    )
    conn = self._connect()
    try:
        with conn:
            for rec in records:
                self._upsert_article_row(conn, rec)
            if advisory_id is not None and outcome_json is not None:
                for sink_key in dict.fromkeys(sink_keys):
                    self._insert_outbox_row(
                        conn,
                        advisory_id=advisory_id,
                        content_sha256=content_sha256,
                        sink_key=sink_key,
                        outcome_json=outcome_json,
                        created_at=now,
                    )
    finally:
        conn.close()
    return primary_record

schema_version()

Return the current SQLite PRAGMA user_version integer.

Source code in src/zerobom/ingest/state.py
111
112
113
114
115
116
117
118
def schema_version(self) -> int:
    """Return the current SQLite ``PRAGMA user_version`` integer."""
    conn = self._connect()
    try:
        row = conn.execute("PRAGMA user_version").fetchone()
        return int(row[0]) if row is not None else 0
    finally:
        conn.close()

upsert(record)

Insert or update an :class:ArticleStateRecord using parameterized SQL.

Source code in src/zerobom/ingest/state.py
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
def upsert(self, record: ArticleStateRecord) -> None:
    """Insert or update an :class:`ArticleStateRecord` using parameterized SQL."""
    canonical = canonicalize_url(record.canonical_url)
    conn = self._connect()
    try:
        with conn:
            conn.execute(
                """
                INSERT INTO article_state (
                    canonical_url, content_sha256, etag, last_modified,
                    last_seen_at, advisory_id, routing
                )
                VALUES (?, ?, ?, ?, ?, ?, ?)
                ON CONFLICT(canonical_url) DO UPDATE SET
                    content_sha256 = excluded.content_sha256,
                    etag = COALESCE(excluded.etag, article_state.etag),
                    last_modified = COALESCE(
                        excluded.last_modified, article_state.last_modified
                    ),
                    last_seen_at = excluded.last_seen_at,
                    advisory_id = COALESCE(excluded.advisory_id, article_state.advisory_id),
                    routing = COALESCE(excluded.routing, article_state.routing)
                """,
                (
                    canonical,
                    record.content_sha256,
                    record.etag,
                    record.last_modified,
                    record.last_seen_at.isoformat(),
                    record.advisory_id,
                    record.routing.value if record.routing is not None else None,
                ),
            )
    finally:
        conn.close()

PolledArticle(article, content_sha256, etag=None, last_modified=None, source_entry_url=None) dataclass

Fetched candidate article paired with HTTP cache validators and content digest.

Used by :func:poll_feed_items and :func:zerobom.pipeline.watch_feeds so callers can persist :class:IngestStateStore markers only after downstream extraction succeeds.

Attributes:

Name Type Description
article RawArticle

Ingested and cleaned :class:RawArticle.

content_sha256 str

Hexadecimal SHA-256 digest of article.body.

etag str | None

Optional HTTP ETag header from the article response.

last_modified str | None

Optional HTTP Last-Modified header from the article response.

SafeHttpFetcher(*, client=None, dns_resolver=None, max_bytes=MAX_RESPONSE_BYTES, max_redirects=MAX_REDIRECTS, timeout=DEFAULT_TIMEOUT_SECONDS)

SSRF-hardened, streaming-bounded HTTP fetcher with manual redirect verification.

Initialize the hardened HTTP fetcher.

Parameters:

Name Type Description Default
client Client | None

Optional pre-configured httpx.Client (e.g., MockTransport in tests).

None
dns_resolver DnsResolver | None

Optional DNS resolver callable for deterministic offline testing.

None
max_bytes int

Maximum allowed streamed response payload size in bytes.

MAX_RESPONSE_BYTES
max_redirects int

Maximum permitted HTTP redirect hops (each hop re-validated).

MAX_REDIRECTS
timeout float

Socket/request timeout in seconds for default client creation.

DEFAULT_TIMEOUT_SECONDS

Raises:

Type Description
ValueError

If max_bytes < 1 or max_redirects < 0.

Source code in src/zerobom/ingest/fetcher.py
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
def __init__(
    self,
    *,
    client: httpx.Client | None = None,
    dns_resolver: DnsResolver | None = None,
    max_bytes: int = MAX_RESPONSE_BYTES,
    max_redirects: int = MAX_REDIRECTS,
    timeout: float = DEFAULT_TIMEOUT_SECONDS,
) -> None:
    """Initialize the hardened HTTP fetcher.

    Args:
        client: Optional pre-configured ``httpx.Client`` (e.g., ``MockTransport`` in tests).
        dns_resolver: Optional DNS resolver callable for deterministic offline testing.
        max_bytes: Maximum allowed streamed response payload size in bytes.
        max_redirects: Maximum permitted HTTP redirect hops (each hop re-validated).
        timeout: Socket/request timeout in seconds for default client creation.

    Raises:
        ValueError: If ``max_bytes < 1`` or ``max_redirects < 0``.
    """
    if max_bytes < 1:
        raise ValueError("max_bytes must be >= 1")
    if max_redirects < 0:
        raise ValueError("max_redirects must be >= 0")

    self._owns_client = client is None
    self._dns_resolver: DnsResolver = dns_resolver or default_dns_resolver
    # Disable automatic redirects and pin resolved TCP IPs to defeat DNS rebinding.
    self._client = (
        client
        if client is not None
        else create_pinned_httpx_client(
            timeout=timeout,
            headers={"User-Agent": DEFAULT_USER_AGENT},
            dns_resolver=self._dns_resolver,
            on_blocked=SsrfBlockedError,
        )
    )
    self._max_bytes = max_bytes
    self._max_redirects = max_redirects

client property

Return the underlying httpx.Client instance.

close()

Close the underlying HTTP client when owned by this instance.

Source code in src/zerobom/ingest/fetcher.py
357
358
359
360
def close(self) -> None:
    """Close the underlying HTTP client when owned by this instance."""
    if self._owns_client:
        self._client.close()

fetch_article(url, *, source_name, source_tier=SourceTier.UNKNOWN, published_at=None, published_at_inferred=False, conditional_headers=None)

Fetch an HTML/text blog post and extract a normalized :class:RawArticle.

Parameters:

Name Type Description Default
url str

Source article HTTP/HTTPS URL.

required
source_name str

Human-readable feed/publisher name.

required
source_tier SourceTier

Source credibility tier.

UNKNOWN
published_at datetime | None

Optional publication timestamp (defaults to current UTC time).

None
published_at_inferred bool

Whether published_at was synthesized rather than stated in feed/sitemap metadata.

False
conditional_headers dict[str, str] | None

Optional If-None-Match / If-Modified-Since headers.

None

Returns:

Type Description
RawArticle | None

Tuple of (RawArticle | None, FetchResponse). The article is None when the

FetchResponse

server replies 304 Not Modified.

Raises:

Type Description
FetchError

On transport, SSRF, content-type, or empty-body failure.

Source code in src/zerobom/ingest/fetcher.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def fetch_article(
    self,
    url: str,
    *,
    source_name: str,
    source_tier: SourceTier = SourceTier.UNKNOWN,
    published_at: datetime | None = None,
    published_at_inferred: bool = False,
    conditional_headers: dict[str, str] | None = None,
) -> tuple[RawArticle | None, FetchResponse]:
    """Fetch an HTML/text blog post and extract a normalized :class:`RawArticle`.

    Args:
        url: Source article HTTP/HTTPS URL.
        source_name: Human-readable feed/publisher name.
        source_tier: Source credibility tier.
        published_at: Optional publication timestamp (defaults to current UTC time).
        published_at_inferred: Whether ``published_at`` was synthesized rather than stated in
            feed/sitemap metadata.
        conditional_headers: Optional ``If-None-Match`` / ``If-Modified-Since`` headers.

    Returns:
        Tuple of ``(RawArticle | None, FetchResponse)``. The article is ``None`` when the
        server replies ``304 Not Modified``.

    Raises:
        FetchError: On transport, SSRF, content-type, or empty-body failure.
    """
    resp = self.fetch_bytes(url, headers=conditional_headers)
    if resp.not_modified:
        return None, resp

    title, body, html_published_at = extract_article_metadata_and_text(
        resp.body,
        resp.content_type,
    )
    if not body:
        raise FetchError(f"Extracted article body was empty for {resp.final_url}.")

    now = datetime.now(UTC)
    resolved_published_at = published_at
    resolved_inferred = published_at_inferred
    if (published_at is None or published_at_inferred) and html_published_at is not None:
        resolved_published_at = html_published_at
        resolved_inferred = False
    elif resolved_published_at is None:
        resolved_published_at = now
        resolved_inferred = True

    article = RawArticle(
        url=resp.final_url,
        title=title,
        body=body,
        source_name=source_name,
        source_tier=source_tier,
        published_at=resolved_published_at,
        published_at_inferred=resolved_inferred,
        fetched_at=now,
    )
    return article, resp

fetch_bytes(url, *, headers=None, allowed_content_types=ALLOWED_CONTENT_TYPES)

Fetch raw response bytes with per-hop SSRF validation and streaming size limits.

Parameters:

Name Type Description Default
url str

Target HTTP or HTTPS URL.

required
headers dict[str, str] | None

Optional extra request headers (e.g., If-None-Match).

None
allowed_content_types frozenset[str]

Permitted normalized MIME media types.

ALLOWED_CONTENT_TYPES

Returns:

Name Type Description
A FetchResponse

class:FetchResponse containing validated payload bytes and cache headers.

Raises:

Type Description
SsrfBlockedError

If the initial URL or any redirect resolves to a non-public IP.

FetchError

On HTTP error status, disallowed Content-Type, redirect loop, or size cap.

Source code in src/zerobom/ingest/fetcher.py
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
def fetch_bytes(
    self,
    url: str,
    *,
    headers: dict[str, str] | None = None,
    allowed_content_types: frozenset[str] = ALLOWED_CONTENT_TYPES,
) -> FetchResponse:
    """Fetch raw response bytes with per-hop SSRF validation and streaming size limits.

    Args:
        url: Target HTTP or HTTPS URL.
        headers: Optional extra request headers (e.g., ``If-None-Match``).
        allowed_content_types: Permitted normalized MIME media types.

    Returns:
        A :class:`FetchResponse` containing validated payload bytes and cache headers.

    Raises:
        SsrfBlockedError: If the initial URL or any redirect resolves to a non-public IP.
        FetchError: On HTTP error status, disallowed Content-Type, redirect loop, or size cap.
    """
    current_url = url
    request_headers = dict(headers) if headers else {}

    for hop in range(self._max_redirects + 1):
        validated_url = validate_fetch_url(current_url, dns_resolver=self._dns_resolver)

        try:
            with self._client.stream(
                "GET",
                validated_url,
                headers=request_headers if hop == 0 else {},
            ) as response:
                etag = response.headers.get("etag")
                last_modified = response.headers.get("last-modified")

                if response.status_code == 304:
                    return FetchResponse(
                        final_url=validated_url,
                        status_code=304,
                        content_type="",
                        body=b"",
                        etag=etag,
                        last_modified=last_modified,
                        not_modified=True,
                    )

                if response.status_code in _REDIRECT_STATUS_CODES:
                    location = response.headers.get("location")
                    if not location:
                        raise FetchError(
                            f"Redirect ({response.status_code}) missing Location header."
                        )
                    if any(ord(ch) < 32 or ord(ch) == 127 for ch in location):
                        raise FetchError("Redirect Location header contains control chars.")
                    if hop >= self._max_redirects:
                        raise FetchError(
                            f"Exceeded maximum redirect limit ({self._max_redirects})."
                        )
                    current_url = urljoin(validated_url, location.strip())
                    continue

                if response.status_code >= 400:
                    raise FetchError(
                        f"HTTP {response.status_code} returned while fetching {validated_url}."
                    )

                raw_ct = response.headers.get("content-type", "")
                media_type = raw_ct.split(";", 1)[0].strip().lower()
                if allowed_content_types and media_type not in allowed_content_types:
                    raise FetchError(
                        f"Disallowed Content-Type {media_type or 'missing'!r} "
                        f"from {validated_url}."
                    )

                content_len = response.headers.get("content-length")
                if content_len is not None:
                    try:
                        declared = int(content_len)
                    except ValueError as exc:
                        raise FetchError(
                            f"Invalid Content-Length header {content_len!r}."
                        ) from exc
                    if declared > self._max_bytes:
                        raise FetchError(
                            f"Declared Content-Length ({declared} bytes) exceeds limit "
                            f"({self._max_bytes} bytes)."
                        )

                chunks: list[bytes] = []
                total_bytes = 0
                for chunk in response.iter_bytes():
                    total_bytes += len(chunk)
                    if total_bytes > self._max_bytes:
                        raise FetchError(
                            f"Response stream exceeded max_bytes={self._max_bytes}."
                        )
                    chunks.append(chunk)

                return FetchResponse(
                    final_url=validated_url,
                    status_code=response.status_code,
                    content_type=media_type,
                    body=b"".join(chunks),
                    etag=etag,
                    last_modified=last_modified,
                    not_modified=False,
                )
        except FetchError:
            raise
        except httpx.HTTPError as exc:
            raise FetchError(f"HTTP transport error fetching {validated_url}: {exc}") from exc

    raise FetchError(f"Exceeded maximum redirect limit ({self._max_redirects}).")

SsrfBlockedError

Bases: FetchError

Raised when a URL or redirect target resolves to a non-public IP address.

compute_content_sha256(text)

Compute a deterministic SHA-256 hex digest over whitespace-normalized text.

Parameters:

Name Type Description Default
text str

Extracted article body text.

required

Returns:

Type Description
str

Lowercase 64-character hexadecimal SHA-256 digest.

Source code in src/zerobom/ingest/fetcher.py
294
295
296
297
298
299
300
301
302
303
304
def compute_content_sha256(text: str) -> str:
    """Compute a deterministic SHA-256 hex digest over whitespace-normalized text.

    Args:
        text: Extracted article body text.

    Returns:
        Lowercase 64-character hexadecimal SHA-256 digest.
    """
    normalized = _WHITESPACE_RE.sub(" ", text).strip().encode("utf-8")
    return hashlib.sha256(normalized).hexdigest()

discover_feed_entries(body_bytes, feed, *, base_url=None, content_type='', max_entries=MAX_FEED_ENTRIES)

Discover candidate :class:FeedEntry items according to feed.kind.

Dispatches explicitly to RSS/Atom, XML sitemap, or generic same-origin HTML index parsing; in FeedKind.AUTO mode, tries RSS/Atom -> XML sitemap -> prefix-filtered HTML index.

Parameters:

Name Type Description Default
body_bytes bytes

Raw fetched bytes from the source endpoint.

required
feed SourceFeedConfig

Source configuration specifying kind and optional url_prefix.

required
base_url str | None

Final fetched URL used for resolving relative links on HTML index pages.

None
content_type str

HTTP response Content-Type header value.

''
max_entries int

Maximum entries to discover per source.

MAX_FEED_ENTRIES

Returns:

Type Description
tuple[FeedEntry, ...]

Deduplicated tuple of :class:FeedEntry items.

Raises:

Type Description
FetchError

If XML policy (DOCTYPE/ENTITY), invalid format, or invalid limits occur.

Source code in src/zerobom/ingest/rss.py
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
def discover_feed_entries(
    body_bytes: bytes,
    feed: SourceFeedConfig,
    *,
    base_url: str | None = None,
    content_type: str = "",
    max_entries: int = MAX_FEED_ENTRIES,
) -> tuple[FeedEntry, ...]:
    """Discover candidate :class:`FeedEntry` items according to ``feed.kind``.

    Dispatches explicitly to RSS/Atom, XML sitemap, or generic same-origin HTML index parsing;
    in ``FeedKind.AUTO`` mode, tries RSS/Atom -> XML sitemap -> prefix-filtered HTML index.

    Args:
        body_bytes: Raw fetched bytes from the source endpoint.
        feed: Source configuration specifying ``kind`` and optional ``url_prefix``.
        base_url: Final fetched URL used for resolving relative links on HTML index pages.
        content_type: HTTP response Content-Type header value.
        max_entries: Maximum entries to discover per source.

    Returns:
        Deduplicated tuple of :class:`FeedEntry` items.

    Raises:
        FetchError: If XML policy (DOCTYPE/ENTITY), invalid format, or invalid limits occur.
    """
    if feed.kind == FeedKind.RSS:
        return parse_feed_entries(body_bytes, feed, max_entries=max_entries)
    if feed.kind == FeedKind.SITEMAP:
        return parse_sitemap_entries(body_bytes, feed, max_entries=max_entries)
    if feed.kind == FeedKind.HTML_INDEX:
        return parse_html_index_entries(
            body_bytes,
            feed,
            base_url=base_url,
            max_entries=max_entries,
        )

    # FeedKind.AUTO fallback chain: HTML index when MIME/signature is HTML; else RSS -> sitemap.
    has_safe_html_prefix = feed.url_prefix is not None and _is_same_origin(
        feed.url, feed.url_prefix
    )
    if _looks_like_html(body_bytes, content_type):
        if has_safe_html_prefix:
            return parse_html_index_entries(
                body_bytes,
                feed,
                base_url=base_url,
                max_entries=max_entries,
            )
        return ()

    _reject_xml_xxe(body_bytes, feed.name)

    rss_entries = parse_feed_entries(body_bytes, feed, max_entries=max_entries)
    if rss_entries:
        return rss_entries

    try:
        sitemap_entries = parse_sitemap_entries(body_bytes, feed, max_entries=max_entries)
        if sitemap_entries:
            return sitemap_entries
    except _XmlPolicyError:
        raise
    except FetchError:
        # Malformed XML fallback falls through cleanly to guarded HTML index check below.
        pass

    if has_safe_html_prefix:
        return parse_html_index_entries(
            body_bytes,
            feed,
            base_url=base_url,
            max_entries=max_entries,
        )
    return ()

extract_article_metadata_and_text(raw_bytes, content_type, *, fallback_title='Untitled Advisory')

Extract sanitized title, plain-text body, and optional publication date.

Parameters:

Name Type Description Default
raw_bytes bytes

Raw downloaded document payload.

required
content_type str

Normalized HTTP Content-Type media type.

required
fallback_title str

Title used when extraction yields no usable title.

'Untitled Advisory'

Returns:

Type Description
tuple[str, str, datetime | None]

Tuple of (clean_title, clean_body, extracted_published_at).

Source code in src/zerobom/ingest/fetcher.py
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
def extract_article_metadata_and_text(
    raw_bytes: bytes,
    content_type: str,
    *,
    fallback_title: str = "Untitled Advisory",
) -> tuple[str, str, datetime | None]:
    """Extract sanitized title, plain-text body, and optional publication date.

    Args:
        raw_bytes: Raw downloaded document payload.
        content_type: Normalized HTTP Content-Type media type.
        fallback_title: Title used when extraction yields no usable title.

    Returns:
        Tuple of ``(clean_title, clean_body, extracted_published_at)``.
    """
    decoded = raw_bytes.decode("utf-8", errors="replace")
    media_type = content_type.split(";", 1)[0].strip().lower()

    if media_type == "text/plain":
        return fallback_title, _strip_disallowed_control_chars(decoded), None

    # Lazy-import trafilatura here to keep CLI startup fast and suppress urllib3's benign
    # PySocks DependencyWarning emitted on module import.
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", message=".*SOCKS support in urllib3.*")
        import trafilatura

    extracted = trafilatura.extract(
        decoded,
        include_comments=False,
        include_tables=True,
        favor_recall=True,
    )
    body = extracted if extracted and extracted.strip() else _fallback_html_to_text(decoded)

    title: str | None = None
    metadata = trafilatura.extract_metadata(decoded)
    meta_title = getattr(metadata, "title", None) if metadata is not None else None
    meta_date = getattr(metadata, "date", None) if metadata is not None else None
    extracted_published_at = _parse_html_metadata_date(meta_date)
    if isinstance(meta_title, str) and meta_title.strip():
        title = meta_title.strip()
    elif title_match := _TITLE_TAG_RE.search(decoded):
        candidate = _WHITESPACE_RE.sub(" ", html_lib.unescape(title_match.group(1))).strip()
        if candidate:
            title = candidate

    raw_title = _WHITESPACE_RE.sub(" ", _strip_disallowed_control_chars(title or fallback_title))
    clean_title = raw_title.strip() or fallback_title
    clean_body = _strip_disallowed_control_chars(body)
    return clean_title, clean_body, extracted_published_at

extract_article_text(raw_bytes, content_type, *, fallback_title='Untitled Advisory')

Extract clean (title, body) text from fetched HTML or plain-text bytes.

Parameters:

Name Type Description Default
raw_bytes bytes

Downloaded response bytes.

required
content_type str

Normalized MIME content type.

required
fallback_title str

Title used when HTML lacks extractable title metadata.

'Untitled Advisory'

Returns:

Type Description
tuple[str, str]

Tuple of (title, cleaned_body).

Source code in src/zerobom/ingest/fetcher.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def extract_article_text(
    raw_bytes: bytes,
    content_type: str,
    *,
    fallback_title: str = "Untitled Advisory",
) -> tuple[str, str]:
    """Extract clean ``(title, body)`` text from fetched HTML or plain-text bytes.

    Args:
        raw_bytes: Downloaded response bytes.
        content_type: Normalized MIME content type.
        fallback_title: Title used when HTML lacks extractable title metadata.

    Returns:
        Tuple of ``(title, cleaned_body)``.
    """
    title, body, _ = extract_article_metadata_and_text(
        raw_bytes,
        content_type,
        fallback_title=fallback_title,
    )
    return title, body

extract_known_aliases(text)

Extract normalized advisory identifiers (CVE, GHSA, ZDI, TALOS, VU#, OSV) from text.

Parameters:

Name Type Description Default
text str

Combined article title and body text.

required

Returns:

Type Description
tuple[str, ...]

Deduplicated tuple of canonical advisory identifiers.

Source code in src/zerobom/ingest/prefilter.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def extract_known_aliases(text: str) -> tuple[str, ...]:
    """Extract normalized advisory identifiers (CVE, GHSA, ZDI, TALOS, VU#, OSV) from text.

    Args:
        text: Combined article title and body text.

    Returns:
        Deduplicated tuple of canonical advisory identifiers.
    """
    aliases: list[str] = []
    seen: set[str] = set()

    for pattern, is_ghsa in _ALIAS_EXTRACTORS:
        for match in pattern.findall(text):
            canonical = _canonicalize_alias(match, is_ghsa=is_ghsa)
            if canonical not in seen:
                seen.add(canonical)
                aliases.append(canonical)

    return tuple(aliases)

is_public_ip(ip_str)

Return True only when ip_str is a globally routable public IP address.

Unwraps IPv4-mapped IPv6 addresses (e.g., ::ffff:169.254.169.254) and blocks private, loopback, link-local (cloud IMDS), multicast, reserved, and unspecified ranges.

Parameters:

Name Type Description Default
ip_str str

IPv4 or IPv6 literal string.

required

Returns:

Type Description
bool

True if globally routable; False otherwise.

Source code in src/zerobom/_net.py
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
def is_public_ip(ip_str: str) -> bool:
    """Return True only when ``ip_str`` is a globally routable public IP address.

    Unwraps IPv4-mapped IPv6 addresses (e.g., ``::ffff:169.254.169.254``) and blocks private,
    loopback, link-local (cloud IMDS), multicast, reserved, and unspecified ranges.

    Args:
        ip_str: IPv4 or IPv6 literal string.

    Returns:
        ``True`` if globally routable; ``False`` otherwise.
    """
    cleaned = ip_str.strip().split("%", 1)[0]
    try:
        ip = ipaddress.ip_address(cleaned)
    except ValueError:
        return False

    if isinstance(ip, ipaddress.IPv6Address):
        if ip.ipv4_mapped is not None:
            ip = ip.ipv4_mapped
        elif ip.sixtofour is not None and not ip.sixtofour.is_global:
            return False

    return bool(
        ip.is_global
        and not (
            ip.is_private
            or ip.is_loopback
            or ip.is_link_local
            or ip.is_multicast
            or ip.is_reserved
            or ip.is_unspecified
        )
    )

is_valid_advisory_alias(alias)

Validate and canonicalize a candidate advisory identifier against strict patterns.

Supports CVE-*, GHSA-*, ZDI-CAN-*, ZDI-*, TALOS-*, VU#*, RUSTSEC-*, GO-*, and PYSEC-* identifiers.

Parameters:

Name Type Description Default
alias str

Candidate identifier string returned by pre-filtering or an LLM.

required

Returns:

Type Description
str | None

Canonical identifier string if strictly valid, otherwise None.

Source code in src/zerobom/ingest/prefilter.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def is_valid_advisory_alias(alias: str) -> str | None:
    """Validate and canonicalize a candidate advisory identifier against strict patterns.

    Supports ``CVE-*``, ``GHSA-*``, ``ZDI-CAN-*``, ``ZDI-*``, ``TALOS-*``, ``VU#*``,
    ``RUSTSEC-*``, ``GO-*``, and ``PYSEC-*`` identifiers.

    Args:
        alias: Candidate identifier string returned by pre-filtering or an LLM.

    Returns:
        Canonical identifier string if strictly valid, otherwise ``None``.
    """
    cleaned = alias.strip()
    if not cleaned or len(cleaned) > 64:
        return None
    for pattern, is_ghsa in _ALIAS_EXTRACTORS:
        # Compare strict full-string pattern without word-boundary quirks on '#'.
        match = pattern.search(cleaned)
        if match is not None and match.group(0) == cleaned:
            return _canonicalize_alias(cleaned, is_ghsa=is_ghsa)
    return None

load_sources_config(path)

Load and strictly validate a sources.yaml feed allowlist using yaml.safe_load.

Parameters:

Name Type Description Default
path Path | str

Path to the YAML sources configuration file.

required

Returns:

Name Type Description
Validated SourcesConfig

class:SourcesConfig object.

Raises:

Type Description
ValueError

If the file is missing, exceeds MAX_SOURCES_YAML_BYTES, contains invalid YAML, or fails strict Pydantic schema validation.

Source code in src/zerobom/ingest/rss.py
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
def load_sources_config(path: Path | str) -> SourcesConfig:
    """Load and strictly validate a ``sources.yaml`` feed allowlist using ``yaml.safe_load``.

    Args:
        path: Path to the YAML sources configuration file.

    Returns:
        Validated :class:`SourcesConfig` object.

    Raises:
        ValueError: If the file is missing, exceeds ``MAX_SOURCES_YAML_BYTES``, contains invalid
            YAML, or fails strict Pydantic schema validation.
    """
    yaml_path = Path(path)
    if not yaml_path.is_file():
        raise ValueError(f"Sources configuration file does not exist: {yaml_path}")

    size = yaml_path.stat().st_size
    if size > MAX_SOURCES_YAML_BYTES:
        raise ValueError(
            f"Sources file {yaml_path} exceeds max size of {MAX_SOURCES_YAML_BYTES} bytes."
        )

    try:
        raw_text = yaml_path.read_text(encoding="utf-8")
        loaded = yaml.safe_load(raw_text)
    except (OSError, UnicodeDecodeError, yaml.YAMLError) as exc:
        raise ValueError(f"Failed to parse YAML in {yaml_path}: {exc}") from exc

    if not isinstance(loaded, dict):
        raise ValueError(f"Root of {yaml_path} must be a YAML mapping.")

    raw_feeds = loaded.get("feeds", [])
    if not isinstance(raw_feeds, list):
        raise ValueError("'feeds' must be a list in sources.yaml.")

    parsed_feeds: list[SourceFeedConfig] = []
    for item in raw_feeds:
        if not isinstance(item, dict):
            raise ValueError("Each entry in 'feeds' must be a YAML mapping.")

        raw_tier = item.get("tier", SourceTier.TIER_2.value)
        try:
            tier = raw_tier if isinstance(raw_tier, SourceTier) else SourceTier(str(raw_tier))
        except ValueError as exc:
            raise ValueError(f"Invalid source tier {raw_tier!r} in {yaml_path}.") from exc

        raw_kind = item.get("kind", FeedKind.RSS.value)
        try:
            kind = (
                raw_kind
                if isinstance(raw_kind, FeedKind)
                else FeedKind(str(raw_kind).strip().lower())
            )
        except ValueError as exc:
            raise ValueError(f"Invalid source feed kind {raw_kind!r} in {yaml_path}.") from exc

        raw_prefix = item.get("url_prefix")
        if raw_prefix is not None and not isinstance(raw_prefix, str):
            raise ValueError(f"'url_prefix' must be a string in {yaml_path}.")

        raw_tags = item.get("tags", [])
        if not isinstance(raw_tags, list) or not all(isinstance(t, str) for t in raw_tags):
            raise ValueError("'tags' in sources.yaml feed entry must be a list of strings.")

        feed_kwargs: dict[str, Any] = {
            "name": item.get("name"),
            "url": item.get("url"),
            "tier": tier,
            "kind": kind,
            "url_prefix": raw_prefix,
            "enabled": item.get("enabled", True),
            "tags": tuple(raw_tags),
        }
        try:
            parsed_feeds.append(SourceFeedConfig(**feed_kwargs))
        except ValidationError as exc:
            raise ValueError(f"Invalid feed configuration in {yaml_path}: {exc}") from exc

    version = loaded.get("version", 1)
    return SourcesConfig(version=version, feeds=tuple(parsed_feeds))

parse_feed_entries(feed_bytes, feed, *, max_entries=MAX_FEED_ENTRIES)

Parse RSS or Atom XML bytes into validated, deduplicated :class:FeedEntry records.

Parameters:

Name Type Description Default
feed_bytes bytes

Raw XML bytes fetched from an RSS/Atom endpoint.

required
feed SourceFeedConfig

Source feed configuration providing publisher name, tier, and optional prefix.

required
max_entries int

Maximum number of entries returned from a single feed.

MAX_FEED_ENTRIES

Returns:

Type Description
tuple[FeedEntry, ...]

Deduplicated tuple of validated :class:FeedEntry items.

Raises:

Type Description
FetchError

If XML contains <!DOCTYPE or <!ENTITY, or max_entries < 1.

Source code in src/zerobom/ingest/rss.py
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
def parse_feed_entries(
    feed_bytes: bytes,
    feed: SourceFeedConfig,
    *,
    max_entries: int = MAX_FEED_ENTRIES,
) -> tuple[FeedEntry, ...]:
    """Parse RSS or Atom XML bytes into validated, deduplicated :class:`FeedEntry` records.

    Args:
        feed_bytes: Raw XML bytes fetched from an RSS/Atom endpoint.
        feed: Source feed configuration providing publisher name, tier, and optional prefix.
        max_entries: Maximum number of entries returned from a single feed.

    Returns:
        Deduplicated tuple of validated :class:`FeedEntry` items.

    Raises:
        FetchError: If XML contains ``<!DOCTYPE`` or ``<!ENTITY``, or ``max_entries < 1``.
    """
    if max_entries < 1:
        raise FetchError("max_entries must be >= 1")

    _reject_xml_xxe(feed_bytes, feed.name)

    parsed_feed = feedparser.parse(feed_bytes)
    entries = getattr(parsed_feed, "entries", []) or []

    results: list[FeedEntry] = []
    seen_urls: set[str] = set()

    for raw_entry in entries:
        if len(results) >= max_entries:
            break
        raw_link = raw_entry.get("link")
        raw_title = raw_entry.get("title") or "Untitled Advisory"
        raw_summary = raw_entry.get("summary") or raw_entry.get("description") or ""
        if not isinstance(raw_link, str):
            continue

        raw_published = raw_entry.get("published_parsed") or raw_entry.get("updated_parsed")
        published_at_inferred = True
        if (
            raw_published is not None
            and isinstance(raw_published, tuple)
            and len(raw_published) >= 6
        ):
            try:
                datetime(
                    int(raw_published[0]),
                    int(raw_published[1]),
                    int(raw_published[2]),
                    int(raw_published[3]),
                    int(raw_published[4]),
                    min(int(raw_published[5]), 59),
                    tzinfo=UTC,
                )
                published_at_inferred = False
            except (TypeError, ValueError):
                published_at_inferred = True
        published_at = _parse_struct_time(raw_published)
        try:
            entry = FeedEntry(
                url=raw_link,
                title=str(raw_title),
                summary=str(raw_summary),
                published_at=published_at,
                published_at_inferred=published_at_inferred,
                source_name=feed.name,
                source_tier=feed.tier,
            )
        except ValidationError:
            # Skip individual entries with unsafe schemes (e.g., javascript:) or malformed titles.
            continue

        if feed.url_prefix is not None and not _matches_url_prefix(entry.url, feed.url_prefix):
            continue

        canonical = canonicalize_url(entry.url)
        if canonical in seen_urls:
            continue
        seen_urls.add(canonical)
        results.append(entry)

    return tuple(results)

parse_html_index_entries(html_bytes, feed, *, base_url=None, max_entries=MAX_FEED_ENTRIES)

Extract same-origin prefix-filtered links from a blog HTML index page.

Resolves relative links strictly against base_url (or feed.url), requires a configured same-origin feed.url_prefix, strips URI fragments, excludes index URLs themselves, and deduplicates canonical URLs cleanly.

Parameters:

Name Type Description Default
html_bytes bytes

Raw HTML bytes of the index listing page.

required
feed SourceFeedConfig

Source feed configuration specifying url and required same-origin url_prefix.

required
base_url str | None

Final response URL used for relative link resolution (defaults to feed.url).

None
max_entries int

Maximum number of entries returned.

MAX_FEED_ENTRIES

Returns:

Type Description
tuple[FeedEntry, ...]

Deduplicated tuple of validated :class:FeedEntry items.

Raises:

Type Description
FetchError

If max_entries < 1 or feed.url_prefix is missing/cross-origin.

Source code in src/zerobom/ingest/rss.py
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
def parse_html_index_entries(
    html_bytes: bytes,
    feed: SourceFeedConfig,
    *,
    base_url: str | None = None,
    max_entries: int = MAX_FEED_ENTRIES,
) -> tuple[FeedEntry, ...]:
    """Extract same-origin prefix-filtered links from a blog HTML index page.

    Resolves relative links strictly against ``base_url`` (or ``feed.url``), requires a configured
    same-origin ``feed.url_prefix``, strips URI fragments, excludes index URLs themselves, and
    deduplicates canonical URLs cleanly.

    Args:
        html_bytes: Raw HTML bytes of the index listing page.
        feed: Source feed configuration specifying ``url`` and required same-origin ``url_prefix``.
        base_url: Final response URL used for relative link resolution (defaults to ``feed.url``).
        max_entries: Maximum number of entries returned.

    Returns:
        Deduplicated tuple of validated :class:`FeedEntry` items.

    Raises:
        FetchError: If ``max_entries < 1`` or ``feed.url_prefix`` is missing/cross-origin.
    """
    if max_entries < 1:
        raise FetchError("max_entries must be >= 1")
    if feed.url_prefix is None or not _is_same_origin(feed.url, feed.url_prefix):
        raise FetchError(
            f"HTML index discovery for {feed.name!r} requires an explicit same-origin url_prefix."
        )

    effective_base = base_url or feed.url
    parser = _AnchorLinkExtractor()
    parser.feed(html_bytes.decode("utf-8", errors="replace"))
    parser.close()

    excluded_canonicals = {
        canonicalize_url(feed.url),
        canonicalize_url(effective_base),
        canonicalize_url(feed.url_prefix),
    }

    now = datetime.now(UTC)
    results: list[FeedEntry] = []
    seen_urls: set[str] = set()

    for href, anchor_text in parser.links:
        if len(results) >= max_entries:
            break
        joined = urljoin(effective_base, href)
        defragged, _ = urldefrag(joined)

        parsed_scheme = urlparse(defragged).scheme.lower()
        if parsed_scheme not in {"http", "https"}:
            continue
        if not _matches_url_prefix(defragged, feed.url_prefix):
            continue

        path_segments = [seg.lower() for seg in urlparse(defragged).path.split("/") if seg]
        if path_segments and (
            path_segments[-1] in {"feed", "rss", "rss.xml", "atom.xml", "feed.xml", "sitemap.xml"}
            or any(
                seg in {"tag", "tags", "category", "categories", "author", "authors", "page"}
                for seg in path_segments
            )
        ):
            continue

        canonical = canonicalize_url(defragged)
        if canonical in excluded_canonicals or canonical in seen_urls:
            continue

        try:
            entry = FeedEntry(
                url=defragged,
                title=_clean_anchor_title(anchor_text, defragged),
                summary="",
                published_at=now,
                published_at_inferred=True,
                source_name=feed.name,
                source_tier=feed.tier,
            )
        except ValidationError:
            continue

        seen_urls.add(canonical)
        results.append(entry)

    return tuple(results)

parse_sitemap_entries(xml_bytes, feed, *, max_entries=MAX_FEED_ENTRIES)

Parse an XML sitemap (<urlset>) into validated, date-sorted :class:FeedEntry items.

Rejects XML DOCTYPE/ENTITY directives, applies optional feed.url_prefix filtering, deduplicates canonical URLs, and sorts entries carrying <lastmod> newest-first prior to enforcing max_entries.

Parameters:

Name Type Description Default
xml_bytes bytes

Raw XML sitemap payload bytes.

required
feed SourceFeedConfig

Source feed configuration providing name, tier, and optional url_prefix.

required
max_entries int

Maximum number of entries returned.

MAX_FEED_ENTRIES

Returns:

Type Description
tuple[FeedEntry, ...]

Deduplicated tuple of validated :class:FeedEntry items.

Raises:

Type Description
FetchError

If XML contains DOCTYPE/ENTITY, is malformed, or max_entries < 1.

Source code in src/zerobom/ingest/rss.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
def parse_sitemap_entries(
    xml_bytes: bytes,
    feed: SourceFeedConfig,
    *,
    max_entries: int = MAX_FEED_ENTRIES,
) -> tuple[FeedEntry, ...]:
    """Parse an XML sitemap (``<urlset>``) into validated, date-sorted :class:`FeedEntry` items.

    Rejects XML DOCTYPE/ENTITY directives, applies optional ``feed.url_prefix`` filtering,
    deduplicates canonical URLs, and sorts entries carrying ``<lastmod>`` newest-first prior
    to enforcing ``max_entries``.

    Args:
        xml_bytes: Raw XML sitemap payload bytes.
        feed: Source feed configuration providing name, tier, and optional ``url_prefix``.
        max_entries: Maximum number of entries returned.

    Returns:
        Deduplicated tuple of validated :class:`FeedEntry` items.

    Raises:
        FetchError: If XML contains DOCTYPE/ENTITY, is malformed, or ``max_entries < 1``.
    """
    if max_entries < 1:
        raise FetchError("max_entries must be >= 1")

    _reject_xml_xxe(xml_bytes, feed.name)

    raw_items: list[tuple[str, str | None]] = []
    in_url = False
    active_field: str | None = None
    loc_buf: list[str] = []
    lastmod_buf: list[str] = []

    def _local_name(tag_name: str) -> str:
        return tag_name.rsplit(" ", 1)[-1].lower()

    def _on_doctype(*_args: Any) -> None:
        raise _XmlPolicyError(
            f"Feed {feed.name!r} rejected: XML contains disallowed DOCTYPE declaration."
        )

    def _on_entity(*_args: Any) -> None:
        raise _XmlPolicyError(
            f"Feed {feed.name!r} rejected: XML contains disallowed ENTITY declaration."
        )

    def _on_start(name: str, _attrs: dict[str, str]) -> None:
        nonlocal in_url, active_field
        local = _local_name(name)
        if local == "url" and len(raw_items) < MAX_SITEMAP_URLS:
            in_url = True
            active_field = None
            loc_buf.clear()
            lastmod_buf.clear()
        elif in_url and local in {"loc", "lastmod"}:
            active_field = local

    def _on_char(data: str) -> None:
        if not in_url or active_field is None:
            return
        if active_field == "loc":
            loc_buf.append(data)
        elif active_field == "lastmod":
            lastmod_buf.append(data)

    def _on_end(name: str) -> None:
        nonlocal in_url, active_field
        local = _local_name(name)
        if in_url and local == active_field:
            active_field = None
        elif local == "url" and in_url:
            loc_val = "".join(loc_buf).strip()
            lastmod_val = "".join(lastmod_buf).strip() or None
            if loc_val:
                raw_items.append((loc_val, lastmod_val))
            in_url = False
            active_field = None

    parser = expat.ParserCreate(namespace_separator=" ")
    parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER)
    parser.StartDoctypeDeclHandler = _on_doctype
    parser.EntityDeclHandler = _on_entity
    parser.StartElementHandler = _on_start
    parser.CharacterDataHandler = _on_char
    parser.EndElementHandler = _on_end

    try:
        parser.Parse(xml_bytes, True)
    except expat.ExpatError as exc:
        raise FetchError(f"Invalid XML sitemap for {feed.name!r}: {exc}") from exc

    fallback_now = datetime.now(UTC)
    dated_candidates: list[tuple[int, datetime, FeedEntry]] = []
    undated_candidates: list[FeedEntry] = []
    seen_urls: set[str] = set()

    for idx, (loc_url, lastmod_raw) in enumerate(raw_items):
        if feed.url_prefix is not None and not _matches_url_prefix(loc_url, feed.url_prefix):
            continue

        parsed_dt = _parse_iso_datetime(lastmod_raw)
        try:
            entry = FeedEntry(
                url=loc_url,
                title=_title_from_url_slug(loc_url),
                summary="",
                published_at=parsed_dt or fallback_now,
                published_at_inferred=parsed_dt is None,
                source_name=feed.name,
                source_tier=feed.tier,
            )
        except ValidationError:
            continue

        canonical = canonicalize_url(entry.url)
        if canonical in seen_urls:
            continue
        seen_urls.add(canonical)

        if parsed_dt is not None:
            dated_candidates.append((idx, parsed_dt, entry))
        else:
            undated_candidates.append(entry)

    dated_candidates.sort(key=lambda item: (-item[1].timestamp(), item[0]))
    ordered = [item[2] for item in dated_candidates] + undated_candidates
    return tuple(ordered[:max_entries])

poll_feed_items(feeds, *, fetcher, state_store=None, max_entries_per_feed=MAX_FEED_ENTRIES, mark_seen=False)

Poll enabled source endpoints and fetch new or updated articles securely.

By default (mark_seen=False), newly discovered or modified articles are NOT marked seen in state_store until the downstream pipeline finishes processing them, preventing transient extraction failures from permanently skipping advisories. Unchanged articles refresh HTTP validators (ETag / Last-Modified) immediately.

Parameters:

Name Type Description Default
feeds Sequence[SourceFeedConfig]

Sequence of allowlisted :class:SourceFeedConfig entries.

required
fetcher SafeHttpFetcher

SSRF-hardened :class:SafeHttpFetcher instance.

required
state_store IngestStateStore | None

Optional :class:IngestStateStore for 304 and edit-hash deduplication.

None
max_entries_per_feed int

Maximum entries inspected per feed poll.

MAX_FEED_ENTRIES
mark_seen bool

When True, immediately mark newly discovered/edited articles seen.

False

Returns:

Type Description
tuple[PolledArticle, ...]

Tuple of :class:PolledArticle payloads carrying normalized articles and validators.

Source code in src/zerobom/ingest/rss.py
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
def poll_feed_items(
    feeds: Sequence[SourceFeedConfig],
    *,
    fetcher: SafeHttpFetcher,
    state_store: IngestStateStore | None = None,
    max_entries_per_feed: int = MAX_FEED_ENTRIES,
    mark_seen: bool = False,
) -> tuple[PolledArticle, ...]:
    """Poll enabled source endpoints and fetch new or updated articles securely.

    By default (``mark_seen=False``), newly discovered or modified articles are NOT marked seen in
    ``state_store`` until the downstream pipeline finishes processing them, preventing transient
    extraction failures from permanently skipping advisories. Unchanged articles refresh HTTP
    validators (``ETag`` / ``Last-Modified``) immediately.

    Args:
        feeds: Sequence of allowlisted :class:`SourceFeedConfig` entries.
        fetcher: SSRF-hardened :class:`SafeHttpFetcher` instance.
        state_store: Optional :class:`IngestStateStore` for ``304`` and edit-hash deduplication.
        max_entries_per_feed: Maximum entries inspected per feed poll.
        mark_seen: When ``True``, immediately mark newly discovered/edited articles seen.

    Returns:
        Tuple of :class:`PolledArticle` payloads carrying normalized articles and validators.
    """
    polled: list[PolledArticle] = []

    for feed in feeds:
        if not feed.enabled:
            continue

        feed_resp = fetcher.fetch_bytes(feed.url)
        if feed_resp.not_modified:
            continue

        entries = discover_feed_entries(
            feed_resp.body,
            feed,
            base_url=feed_resp.final_url,
            content_type=feed_resp.content_type,
            max_entries=max_entries_per_feed,
        )
        for entry in entries:
            cond_headers = (
                state_store.conditional_headers(entry.url) if state_store is not None else None
            )
            article, resp = fetcher.fetch_article(
                entry.url,
                source_name=feed.name,
                source_tier=feed.tier,
                published_at=entry.published_at,
                published_at_inferred=entry.published_at_inferred,
                conditional_headers=cond_headers,
            )
            if article is None:
                continue

            content_sha = compute_content_sha256(article.body)
            if state_store is not None:
                changed = state_store.has_changed(article.url, content_sha)
                if not changed:
                    state_store.mark_seen(
                        article.url,
                        content_sha,
                        etag=resp.etag,
                        last_modified=resp.last_modified,
                    )
                    continue
                if mark_seen:
                    state_store.mark_seen(
                        article.url,
                        content_sha,
                        etag=resp.etag,
                        last_modified=resp.last_modified,
                    )

            polled.append(
                PolledArticle(
                    article=article,
                    content_sha256=content_sha,
                    etag=resp.etag,
                    last_modified=resp.last_modified,
                )
            )

    return tuple(polled)

poll_feed_items_isolated(feeds, *, fetcher, state_store=None, max_entries_per_feed=MAX_FEED_ENTRIES, mark_seen=False)

Poll enabled feeds with per-feed and per-entry error isolation.

Unlike :func:poll_feed_items, a network error, HTTP 4xx/5xx status, or XML policy violation on one feed or article records a structured error and continues polling remaining feeds and items. Tracks both discovered entry.url and resolved redirect target article.url in state_store when refreshing validators or marking entries seen.

Parameters:

Name Type Description Default
feeds Sequence[SourceFeedConfig]

Sequence of allowlisted :class:SourceFeedConfig entries.

required
fetcher SafeHttpFetcher

SSRF-hardened :class:SafeHttpFetcher instance.

required
state_store IngestStateStore | None

Optional :class:IngestStateStore for 304 and edit-hash deduplication.

None
max_entries_per_feed int

Maximum entries inspected per feed poll.

MAX_FEED_ENTRIES
mark_seen bool

When True, immediately mark newly discovered/edited articles seen.

False

Returns:

Type Description
tuple[tuple[PolledArticle, ...], tuple[FeedPollResult, ...], tuple[WatchItemError, ...]]

Tuple of (polled_articles, per_feed_results, isolated_errors).

Source code in src/zerobom/ingest/rss.py
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
def poll_feed_items_isolated(
    feeds: Sequence[SourceFeedConfig],
    *,
    fetcher: SafeHttpFetcher,
    state_store: IngestStateStore | None = None,
    max_entries_per_feed: int = MAX_FEED_ENTRIES,
    mark_seen: bool = False,
) -> tuple[tuple[PolledArticle, ...], tuple[FeedPollResult, ...], tuple[WatchItemError, ...]]:
    """Poll enabled feeds with per-feed and per-entry error isolation.

    Unlike :func:`poll_feed_items`, a network error, HTTP 4xx/5xx status, or XML policy violation on
    one feed or article records a structured error and continues polling remaining feeds and items.
    Tracks both discovered ``entry.url`` and resolved redirect target ``article.url`` in
    ``state_store`` when refreshing validators or marking entries seen.

    Args:
        feeds: Sequence of allowlisted :class:`SourceFeedConfig` entries.
        fetcher: SSRF-hardened :class:`SafeHttpFetcher` instance.
        state_store: Optional :class:`IngestStateStore` for ``304`` and edit-hash deduplication.
        max_entries_per_feed: Maximum entries inspected per feed poll.
        mark_seen: When ``True``, immediately mark newly discovered/edited articles seen.

    Returns:
        Tuple of ``(polled_articles, per_feed_results, isolated_errors)``.
    """
    polled: list[PolledArticle] = []
    feed_results: list[FeedPollResult] = []
    errors: list[WatchItemError] = []

    for feed in feeds:
        if not feed.enabled:
            continue

        try:
            feed_resp = fetcher.fetch_bytes(feed.url)
            if feed_resp.not_modified:
                feed_results.append(
                    FeedPollResult(
                        feed_name=feed.name,
                        feed_url=feed.url,
                        status=FeedPollStatus.NOT_MODIFIED,
                    )
                )
                continue

            entries = discover_feed_entries(
                feed_resp.body,
                feed,
                base_url=feed_resp.final_url,
                content_type=feed_resp.content_type,
                max_entries=max_entries_per_feed,
            )
        except (FetchError, ValueError) as exc:
            err_msg = str(exc)
            feed_results.append(
                FeedPollResult(
                    feed_name=feed.name,
                    feed_url=feed.url,
                    status=FeedPollStatus.ERROR,
                    error=err_msg,
                )
            )
            errors.append(
                WatchItemError(
                    stage="feed",
                    source_name=feed.name,
                    target=feed.url,
                    error=err_msg,
                )
            )
            continue

        feed_polled_count = 0
        for entry in entries:
            try:
                cond_headers = (
                    state_store.conditional_headers(entry.url) if state_store is not None else None
                )
                article, resp = fetcher.fetch_article(
                    entry.url,
                    source_name=feed.name,
                    source_tier=feed.tier,
                    published_at=entry.published_at,
                    published_at_inferred=entry.published_at_inferred,
                    conditional_headers=cond_headers,
                )
            except (FetchError, ValueError) as exc:
                errors.append(
                    WatchItemError(
                        stage="article_fetch",
                        source_name=feed.name,
                        target=entry.url,
                        error=str(exc),
                    )
                )
                continue

            if article is None:
                continue

            content_sha = compute_content_sha256(article.body)
            redirected = canonicalize_url(entry.url) != canonicalize_url(article.url)
            if state_store is not None:
                changed = state_store.has_changed(article.url, content_sha)
                if not changed:
                    state_store.mark_seen(
                        article.url,
                        content_sha,
                        etag=resp.etag,
                        last_modified=resp.last_modified,
                    )
                    if redirected:
                        state_store.mark_seen(
                            entry.url,
                            content_sha,
                            etag=resp.etag,
                            last_modified=resp.last_modified,
                        )
                    continue
                if mark_seen:
                    state_store.mark_seen(
                        article.url,
                        content_sha,
                        etag=resp.etag,
                        last_modified=resp.last_modified,
                    )
                    if redirected:
                        state_store.mark_seen(
                            entry.url,
                            content_sha,
                            etag=resp.etag,
                            last_modified=resp.last_modified,
                        )

            feed_polled_count += 1
            polled.append(
                PolledArticle(
                    article=article,
                    content_sha256=content_sha,
                    etag=resp.etag,
                    last_modified=resp.last_modified,
                    source_entry_url=entry.url,
                )
            )

        feed_results.append(
            FeedPollResult(
                feed_name=feed.name,
                feed_url=feed.url,
                status=FeedPollStatus.OK,
                entries_discovered=len(entries),
                articles_polled=feed_polled_count,
            )
        )

    return tuple(polled), tuple(feed_results), tuple(errors)

poll_feeds(feeds, *, fetcher, state_store=None, max_entries_per_feed=MAX_FEED_ENTRIES, mark_seen=False)

Poll enabled feeds and return newly discovered or updated :class:RawArticle objects.

Parameters:

Name Type Description Default
feeds Sequence[SourceFeedConfig]

Sequence of allowlisted :class:SourceFeedConfig entries.

required
fetcher SafeHttpFetcher

SSRF-hardened :class:SafeHttpFetcher instance.

required
state_store IngestStateStore | None

Optional :class:IngestStateStore for 304 and edit-hash deduplication.

None
max_entries_per_feed int

Maximum entries inspected per feed poll.

MAX_FEED_ENTRIES
mark_seen bool

Whether to record unseen/changed articles immediately in state_store.

False

Returns:

Type Description
tuple[RawArticle, ...]

Tuple of newly discovered or content-modified :class:RawArticle objects.

Source code in src/zerobom/ingest/rss.py
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
def poll_feeds(
    feeds: Sequence[SourceFeedConfig],
    *,
    fetcher: SafeHttpFetcher,
    state_store: IngestStateStore | None = None,
    max_entries_per_feed: int = MAX_FEED_ENTRIES,
    mark_seen: bool = False,
) -> tuple[RawArticle, ...]:
    """Poll enabled feeds and return newly discovered or updated :class:`RawArticle` objects.

    Args:
        feeds: Sequence of allowlisted :class:`SourceFeedConfig` entries.
        fetcher: SSRF-hardened :class:`SafeHttpFetcher` instance.
        state_store: Optional :class:`IngestStateStore` for ``304`` and edit-hash deduplication.
        max_entries_per_feed: Maximum entries inspected per feed poll.
        mark_seen: Whether to record unseen/changed articles immediately in ``state_store``.

    Returns:
        Tuple of newly discovered or content-modified :class:`RawArticle` objects.
    """
    polled = poll_feed_items(
        feeds,
        fetcher=fetcher,
        state_store=state_store,
        max_entries_per_feed=max_entries_per_feed,
        mark_seen=mark_seen,
    )
    return tuple(item.article for item in polled)

prefilter_article(article)

Gate out pure marketing/non-vulnerability posts deterministically before LLM calls.

Preserves disclosures mentioning newly reserved CVE- or GHSA- identifiers (since blogs frequently publish days before NVD/OSV assigns ranges) and records them as extracted_aliases.

Parameters:

Name Type Description Default
article RawArticle

Ingested :class:RawArticle candidate.

required

Returns:

Name Type Description
A PrefilterResult

class:PrefilterResult containing pass decision, heuristic score, and matched tags.

Source code in src/zerobom/ingest/prefilter.py
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
def prefilter_article(article: RawArticle) -> PrefilterResult:
    """Gate out pure marketing/non-vulnerability posts deterministically before LLM calls.

    Preserves disclosures mentioning newly reserved ``CVE-`` or ``GHSA-`` identifiers (since
    blogs frequently publish days before NVD/OSV assigns ranges) and records them as
    ``extracted_aliases``.

    Args:
        article: Ingested :class:`RawArticle` candidate.

    Returns:
        A :class:`PrefilterResult` containing pass decision, heuristic score, and matched tags.
    """
    combined = f"{article.title}\n{article.body}"
    extracted_aliases = extract_known_aliases(combined)

    vuln_signals = [name for name, pat in _VULN_SIGNAL_PATTERNS if pat.search(combined)]
    if any(alias.startswith("CVE-") for alias in extracted_aliases):
        vuln_signals.append("cve")
    if any(alias.startswith("GHSA-") for alias in extracted_aliases):
        vuln_signals.append("ghsa")
    if any(not alias.startswith(("CVE-", "GHSA-")) for alias in extracted_aliases):
        vuln_signals.append("precve_id")

    software_signals = [name for name, pat in _SOFTWARE_SIGNAL_PATTERNS if pat.search(combined)]
    marketing_signals = [name for name, pat in _MARKETING_SIGNAL_PATTERNS if pat.search(combined)]
    title_marketing = [
        name for name, pat in _MARKETING_SIGNAL_PATTERNS if pat.search(article.title)
    ]
    has_concrete_flaw = bool(_CONCRETE_FLAW_EVIDENCE_RE.search(combined))
    has_version_evidence = bool(_ADVISORY_VERSION_EVIDENCE_RE.search(combined))

    has_pair = len(vuln_signals) >= 1 and len(software_signals) >= 1
    strong_vuln_only = len(vuln_signals) >= 2 and len(marketing_signals) <= len(vuln_signals)
    passed = has_pair or strong_vuln_only
    dropped_title_noise = False
    if passed and title_marketing and not extracted_aliases:
        if any(sig in _STRONG_NON_ADVISORY_TITLE_SIGNALS for sig in title_marketing):
            if not has_version_evidence:
                passed = False
                dropped_title_noise = True
        elif not has_concrete_flaw:
            passed = False
            dropped_title_noise = True

    raw_score = (
        min(0.50, 0.25 * len(vuln_signals))
        + min(0.40, 0.20 * len(software_signals))
        + (0.10 if extracted_aliases else 0.0)
        - min(0.40, 0.10 * len(marketing_signals))
    )
    score = round(max(0.0, min(1.0, raw_score)), 4)

    reasons: list[str] = []
    if not passed:
        if dropped_title_noise:
            reasons.append(
                "Dropped marketing/benchmark/announcement article lacking concrete flaw evidence."
            )
        elif marketing_signals and not vuln_signals:
            reasons.append("Dropped promotional/marketing article lacking vulnerability signals.")
        else:
            reasons.append(
                "Dropped article lacking coupled vulnerability and software/version signals."
            )

    return PrefilterResult(
        passed=passed,
        score=score,
        vuln_signals=tuple(vuln_signals),
        software_signals=tuple(software_signals),
        marketing_signals=tuple(marketing_signals),
        extracted_aliases=extracted_aliases,
        reasons=tuple(reasons),
    )

validate_fetch_url(url, *, dns_resolver=default_dns_resolver)

Validate URL syntax, scheme, absence of credentials, and DNS-resolved IPs.

Parameters:

Name Type Description Default
url str

Untrusted HTTP or HTTPS URL candidate.

required
dns_resolver DnsResolver

Callable mapping (hostname, port) to resolved IP strings.

default_dns_resolver

Returns:

Type Description
str

Validated trimmed URL string.

Raises:

Type Description
FetchError

If URL syntax, scheme, credentials, or DNS resolution fails.

SsrfBlockedError

If the host or any resolved IP is non-global/internal.

Source code in src/zerobom/ingest/fetcher.py
 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
def validate_fetch_url(
    url: str,
    *,
    dns_resolver: DnsResolver = default_dns_resolver,
) -> str:
    """Validate URL syntax, scheme, absence of credentials, and DNS-resolved IPs.

    Args:
        url: Untrusted HTTP or HTTPS URL candidate.
        dns_resolver: Callable mapping ``(hostname, port)`` to resolved IP strings.

    Returns:
        Validated trimmed URL string.

    Raises:
        FetchError: If URL syntax, scheme, credentials, or DNS resolution fails.
        SsrfBlockedError: If the host or any resolved IP is non-global/internal.
    """
    if any(ord(ch) < 32 or ord(ch) == 127 for ch in url):
        raise FetchError("Fetch URL must not contain control characters.")

    stripped = url.strip()
    if not stripped or len(stripped) > MAX_FETCH_URL_LENGTH:
        raise FetchError("Fetch URL is empty or exceeds maximum length.")
    if any(ch.isspace() for ch in stripped):
        raise FetchError("Fetch URL must not contain whitespace.")

    parsed = urlparse(stripped)
    scheme = parsed.scheme.lower()
    if scheme not in ALLOWED_FETCH_SCHEMES:
        raise FetchError(f"Disallowed URL scheme {parsed.scheme!r}; only http/https permitted.")
    if parsed.username is not None or parsed.password is not None:
        raise FetchError("URLs containing embedded credentials are forbidden.")

    hostname = parsed.hostname
    if not hostname:
        raise FetchError("Fetch URL must contain a valid hostname.")

    try:
        port = parsed.port or (443 if scheme == "https" else 80)
    except ValueError as exc:
        raise FetchError(f"Invalid port in URL {stripped!r}: {exc}") from exc

    # Fail immediately on literal non-public IP hosts before invoking DNS.
    try:
        ipaddress.ip_address(hostname)
    except ValueError:
        pass
    else:
        if not is_public_ip(hostname):
            raise SsrfBlockedError(f"Blocked non-public literal IP host {hostname!r}.")

    resolved_ips = dns_resolver(hostname, port)
    if not resolved_ips:
        raise FetchError(f"DNS resolution returned no addresses for {hostname!r}.")

    for ip_str in resolved_ips:
        if not is_public_ip(ip_str):
            raise SsrfBlockedError(
                f"Blocked SSRF target: host {hostname!r} resolved to non-public IP {ip_str!r}."
            )

    return stripped