Skip to content

Outputs & Alerting

Output serializers (Rich terminal, JSON, SARIF 2.1.0) and noise-gated outbound notifiers (HMAC webhooks, Slack Block Kit, idempotent GitHub Issues).

outputs

Output formatters and outbound alerting (Rich, JSON, SARIF, Webhook, Slack, GitHub).

AlertDeliveryError

Bases: RuntimeError

Raised when outbound alert validation, signing, or HTTP delivery fails.

AlertDeliveryResult

Bases: StrictModel

Outcome summary returned for each evaluated outbound alert notification.

GitHubIssueError

Bases: AlertDeliveryError

Raised when GitHub repository validation or REST issue synchronization fails.

GitHubIssueSyncer(repo, token, *, api_base_url=DEFAULT_GITHUB_API_URL, labels=DEFAULT_ISSUE_LABELS, include_triage=False, dry_run=False, timeout_seconds=15.0, http_client=None)

Idempotent GitHub REST API v3 client for creating and updating zerobom issues.

Deduplicates issues across repeated CI runs using the hidden HTML marker <!-- zerobom:advisory-id:<id> --> rather than brittle issue titles.

Initialize a GitHub issue syncer targeting a single repository.

Parameters:

Name Type Description Default
repo str

Target repository in owner/name format.

required
token str

GitHub bearer credential with issues: write scope.

required
api_base_url str

GitHub REST API base URL (HTTPS enforced).

DEFAULT_GITHUB_API_URL
labels Sequence[str]

Labels attached when creating new issues.

DEFAULT_ISSUE_LABELS
include_triage bool

Also sync issues for pending TRIAGE review items.

False
dry_run bool

Compute create/update decisions without mutating GitHub state.

False
timeout_seconds float

Bounded per-request timeout in seconds.

15.0
http_client Client | None

Optional injected httpx.Client for unit testing.

None

Raises:

Type Description
GitHubIssueError

If repo, token, or api_base_url is invalid.

Source code in src/zerobom/outputs/github_issue.py
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
def __init__(
    self,
    repo: str,
    token: str,
    *,
    api_base_url: str = DEFAULT_GITHUB_API_URL,
    labels: Sequence[str] = DEFAULT_ISSUE_LABELS,
    include_triage: bool = False,
    dry_run: bool = False,
    timeout_seconds: float = 15.0,
    http_client: httpx.Client | None = None,
) -> None:
    """Initialize a GitHub issue syncer targeting a single repository.

    Args:
        repo: Target repository in ``owner/name`` format.
        token: GitHub bearer credential with ``issues: write`` scope.
        api_base_url: GitHub REST API base URL (HTTPS enforced).
        labels: Labels attached when creating new issues.
        include_triage: Also sync issues for pending ``TRIAGE`` review items.
        dry_run: Compute create/update decisions without mutating GitHub state.
        timeout_seconds: Bounded per-request timeout in seconds.
        http_client: Optional injected ``httpx.Client`` for unit testing.

    Raises:
        GitHubIssueError: If ``repo``, ``token``, or ``api_base_url`` is invalid.
    """
    self._owner, self._name = validate_github_repo(repo)
    self._repo = f"{self._owner}/{self._name}"
    cleaned_cred = _validate_safe_text(token, field_name="github_token").strip()
    if not cleaned_cred:
        raise GitHubIssueError("GitHub token must not be empty.")
    self._cred = cleaned_cred

    try:
        self._api_base_url = validate_api_base_url(
            api_base_url,
            allow_insecure_http=False,
            field_name="github_api_url",
            allow_query=False,
        )
        self._timeout_seconds = validate_timeout_seconds(timeout_seconds)
    except (BackendError, ValueError) as exc:
        raise GitHubIssueError(str(exc)) from exc

    self._labels = _normalize_labels(labels)
    self._include_triage = bool(include_triage)
    self._dry_run = bool(dry_run)
    self._owns_client = http_client is None
    self._client = (
        http_client
        if http_client is not None
        else httpx.Client(
            timeout=httpx.Timeout(self._timeout_seconds),
            follow_redirects=False,
        )
    )
    # Cached open issues indexed by marker; populated lazily on first actionable issue.
    self._open_issues_by_marker: dict[str, tuple[int, str, str, str]] | None = None

close()

Close the underlying httpx.Client if owned by this instance.

Source code in src/zerobom/outputs/github_issue.py
496
497
498
499
def close(self) -> None:
    """Close the underlying ``httpx.Client`` if owned by this instance."""
    if self._owns_client:
        self._client.close()

sync_outcome(outcome)

Create, update, or leave unchanged the GitHub issue for one pipeline outcome.

Parameters:

Name Type Description Default
outcome PipelineOutcome

Evaluated :class:PipelineOutcome instance.

required

Returns:

Name Type Description
Structured IssueSyncResult

class:IssueSyncResult describing the sync decision.

Raises:

Type Description
GitHubIssueError

If issue rendering or GitHub API synchronization fails.

Source code in src/zerobom/outputs/github_issue.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
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
712
713
714
def sync_outcome(self, outcome: PipelineOutcome) -> IssueSyncResult:
    """Create, update, or leave unchanged the GitHub issue for one pipeline outcome.

    Args:
        outcome: Evaluated :class:`PipelineOutcome` instance.

    Returns:
        Structured :class:`IssueSyncResult` describing the sync decision.

    Raises:
        GitHubIssueError: If issue rendering or GitHub API synchronization fails.
    """
    fallback_id = outcome.osv.id if outcome.osv is not None else "unknown"
    rendered = render_github_issue(
        outcome,
        labels=self._labels,
        include_triage=self._include_triage,
    )
    if rendered is None:
        return IssueSyncResult(
            advisory_id=fallback_id,
            action="skipped",
            reason="Outcome did not meet GitHub issue notification criteria.",
        )

    open_issues = self._ensure_open_issues()
    existing = open_issues.get(rendered.marker)

    if existing is None:
        if self._dry_run:
            return IssueSyncResult(advisory_id=rendered.advisory_id, action="dry_run_create")
        status, created = self._request_json(
            "POST",
            self._issues_url(),
            json_body={
                "title": rendered.title,
                "body": rendered.body,
                "labels": list(rendered.labels),
            },
        )
        if status not in (200, 201) or not isinstance(created, dict):
            raise GitHubIssueError(
                f"Unexpected GitHub issue creation response status {status}."
            )
        issue_num = created.get("number")
        html_url = created.get("html_url")
        num_int = (
            issue_num
            if isinstance(issue_num, int) and not isinstance(issue_num, bool) and issue_num > 0
            else None
        )
        url_str = html_url if isinstance(html_url, str) else None
        if num_int is not None:
            open_issues[rendered.marker] = (
                num_int,
                url_str or "",
                rendered.title,
                rendered.body,
            )
        return IssueSyncResult(
            advisory_id=rendered.advisory_id,
            action="created",
            issue_number=num_int,
            issue_url=url_str,
        )

    issue_num, issue_url, current_title, current_body = existing
    if current_title == rendered.title and current_body == rendered.body:
        return IssueSyncResult(
            advisory_id=rendered.advisory_id,
            action="unchanged",
            issue_number=issue_num,
            issue_url=issue_url or None,
        )

    if self._dry_run:
        return IssueSyncResult(
            advisory_id=rendered.advisory_id,
            action="dry_run_update",
            issue_number=issue_num,
            issue_url=issue_url or None,
        )

    patch_url = f"{self._issues_url()}/{issue_num}"
    status, updated = self._request_json(
        "PATCH",
        patch_url,
        json_body={"title": rendered.title, "body": rendered.body},
    )
    if status != 200 or not isinstance(updated, dict):
        raise GitHubIssueError(f"Unexpected GitHub issue update response status {status}.")
    updated_url = updated.get("html_url")
    final_url = updated_url if isinstance(updated_url, str) else (issue_url or None)
    open_issues[rendered.marker] = (
        issue_num,
        final_url or "",
        rendered.title,
        rendered.body,
    )
    return IssueSyncResult(
        advisory_id=rendered.advisory_id,
        action="updated",
        issue_number=issue_num,
        issue_url=final_url,
    )

sync_outcomes(outcomes)

Synchronize GitHub issues across a sequence of pipeline outcomes.

Parameters:

Name Type Description Default
outcomes Sequence[PipelineOutcome]

Sequence of evaluated :class:PipelineOutcome instances.

required

Returns:

Type Description
tuple[IssueSyncResult, ...]

Tuple of :class:IssueSyncResult instances in input order.

Source code in src/zerobom/outputs/github_issue.py
716
717
718
719
720
721
722
723
724
725
def sync_outcomes(self, outcomes: Sequence[PipelineOutcome]) -> tuple[IssueSyncResult, ...]:
    """Synchronize GitHub issues across a sequence of pipeline outcomes.

    Args:
        outcomes: Sequence of evaluated :class:`PipelineOutcome` instances.

    Returns:
        Tuple of :class:`IssueSyncResult` instances in input order.
    """
    return tuple(self.sync_outcome(outcome) for outcome in outcomes)

IssueSyncResult

Bases: StrictModel

Outcome summary returned by :meth:GitHubIssueSyncer.sync_outcome.

Attributes:

Name Type Description
advisory_id str

Advisory identifier evaluated during sync (or unknown if absent).

action Literal['created', 'updated', 'unchanged', 'skipped', 'dry_run_create', 'dry_run_update']

Sync action taken (created, updated, unchanged, skipped, or dry-run).

issue_number int | None

GitHub issue number if created, updated, or matched.

issue_url str | None

Web URL (html_url) of the GitHub issue if available.

reason str | None

Optional human-readable explanation when skipped.

RenderedGitHubIssue

Bases: StrictModel

Deterministic, sanitized GitHub Issue payload derived from a verified outcome.

Attributes:

Name Type Description
advisory_id str

Canonical OSV/PRECVE advisory identifier.

event_type Literal['auto_hit', 'triage_review']

Actionable event classification (auto_hit or triage_review).

marker str

Hidden HTML comment marker used for idempotent issue lookup.

title str

Bounded single-line GitHub issue title.

body str

Sanitized GitHub Flavored Markdown body ending with marker.

labels tuple[str, ...]

Issue labels applied when creating a new issue.

SlackNotifier(webhook_url, *, allowed_hosts=SLACK_WEBHOOK_HOSTS, timeout_seconds=10.0, dns_resolver=default_dns_resolver, http_client=None)

Host-pinned Slack Incoming Webhook client sending sanitized Block Kit payloads.

Initialize a Slack Incoming Webhook notifier pinned to Slack webhook hosts.

Source code in src/zerobom/outputs/slack.py
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
def __init__(
    self,
    webhook_url: str,
    *,
    allowed_hosts: frozenset[str] = SLACK_WEBHOOK_HOSTS,
    timeout_seconds: float = 10.0,
    dns_resolver: DnsResolver = default_dns_resolver,
    http_client: httpx.Client | None = None,
) -> None:
    """Initialize a Slack Incoming Webhook notifier pinned to Slack webhook hosts."""
    self._webhook_url = validate_webhook_url(
        webhook_url,
        allow_insecure_http=False,
        allow_private_targets=False,
        allowed_hosts=allowed_hosts,
        dns_resolver=dns_resolver,
    )
    try:
        self._timeout_seconds = validate_timeout_seconds(timeout_seconds)
    except (BackendError, ValueError) as exc:
        raise AlertDeliveryError(str(exc)) from exc
    self._allowed_hosts = allowed_hosts
    self._dns_resolver = dns_resolver
    if http_client is not None:
        self._client = http_client
        self._owns_client = False
    else:
        self._client = create_pinned_httpx_client(
            timeout=self._timeout_seconds,
            dns_resolver=self._dns_resolver,
            allowed_hosts=self._allowed_hosts,
            on_blocked=AlertDeliveryError,
        )
        self._owns_client = True

close()

Close the internally managed HTTP client connection pool.

Source code in src/zerobom/outputs/slack.py
376
377
378
379
def close(self) -> None:
    """Close the internally managed HTTP client connection pool."""
    if self._owns_client:
        self._client.close()

send_outcome(outcome, *, triage_id=None, include_interactive_buttons=True, dedup_check=None, on_sent=None)

Send a consolidated AUTO or interactive TRIAGE notification to Slack.

Source code in src/zerobom/outputs/slack.py
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
def send_outcome(
    self,
    outcome: PipelineOutcome,
    *,
    triage_id: str | None = None,
    include_interactive_buttons: bool = True,
    dedup_check: Callable[[str, str], bool] | None = None,
    on_sent: Callable[[str, str], None] | None = None,
) -> AlertDeliveryResult:
    """Send a consolidated AUTO or interactive TRIAGE notification to Slack."""
    event_type = classify_alert_event(outcome)
    advisory_id = outcome.osv.id if outcome.osv is not None else None
    if event_type is None:
        return AlertDeliveryResult(
            advisory_id=advisory_id,
            event_type="skipped",
            delivered=False,
            reason="Outcome did not meet Slack alerting thresholds.",
        )

    if event_type == "auto_hit":
        payload = build_slack_auto_payload(outcome)
    else:
        payload = build_slack_triage_payload(
            outcome,
            triage_id=triage_id,
            include_interactive_buttons=include_interactive_buttons,
        )

    digest = hashlib.sha256(
        json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
    ).hexdigest()

    if (
        event_type == "triage_review"
        and triage_id is not None
        and dedup_check is not None
        and not dedup_check(triage_id, digest)
    ):
        return AlertDeliveryResult(
            advisory_id=advisory_id,
            event_type="skipped",
            delivered=False,
            digest=digest,
            reason=f"Duplicate Slack triage alert suppressed for {triage_id}.",
        )

    validate_webhook_url(
        self._webhook_url,
        allow_insecure_http=False,
        allow_private_targets=False,
        allowed_hosts=self._allowed_hosts,
        dns_resolver=self._dns_resolver,
    )

    status = _post_json_webhook(
        self._client,
        self._webhook_url,
        payload,
        backend_name="slack",
    )

    if event_type == "triage_review" and triage_id is not None and on_sent is not None:
        on_sent(triage_id, digest)

    return AlertDeliveryResult(
        advisory_id=advisory_id,
        event_type=event_type,
        delivered=True,
        status_code=status,
        digest=digest,
    )

send_outcomes(outcomes, *, triage_ids=None, include_interactive_buttons=True, dedup_check=None, on_sent=None)

Deliver Slack notifications across a sequence of :class:PipelineOutcome entries.

Source code in src/zerobom/outputs/slack.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
def send_outcomes(
    self,
    outcomes: Sequence[PipelineOutcome],
    *,
    triage_ids: Mapping[str, str] | None = None,
    include_interactive_buttons: bool = True,
    dedup_check: Callable[[str, str], bool] | None = None,
    on_sent: Callable[[str, str], None] | None = None,
) -> tuple[AlertDeliveryResult, ...]:
    """Deliver Slack notifications across a sequence of :class:`PipelineOutcome` entries."""
    results: list[AlertDeliveryResult] = []
    for outcome in outcomes:
        adv_id = outcome.osv.id if outcome.osv is not None else None
        triage_id = triage_ids.get(adv_id) if (triage_ids and adv_id) else None
        results.append(
            self.send_outcome(
                outcome,
                triage_id=triage_id,
                include_interactive_buttons=include_interactive_buttons,
                dedup_check=dedup_check,
                on_sent=on_sent,
            )
        )
    return tuple(results)

WebhookNotifier(url, *, signing_secret=None, timeout_seconds=_DEFAULT_WEBHOOK_TIMEOUT_SECONDS, allow_insecure_http=False, allow_private_targets=False, allowed_hosts=None, dns_resolver=default_dns_resolver, http_client=None)

Stateless SSRF-hardened JSON webhook alert client with optional HMAC signing.

Initialize an SSRF-validated generic webhook alert client.

Source code in src/zerobom/outputs/webhook.py
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
def __init__(
    self,
    url: str,
    *,
    signing_secret: str | None = None,
    timeout_seconds: float = _DEFAULT_WEBHOOK_TIMEOUT_SECONDS,
    allow_insecure_http: bool = False,
    allow_private_targets: bool = False,
    allowed_hosts: frozenset[str] | None = None,
    dns_resolver: DnsResolver = default_dns_resolver,
    http_client: httpx.Client | None = None,
) -> None:
    """Initialize an SSRF-validated generic webhook alert client."""
    self._url = validate_webhook_url(
        url,
        allow_insecure_http=allow_insecure_http,
        allow_private_targets=allow_private_targets,
        allowed_hosts=allowed_hosts,
        dns_resolver=dns_resolver,
    )
    if signing_secret is not None and (
        any(ord(ch) < 32 or ord(ch) == 127 for ch in signing_secret)
        or not signing_secret.strip()
    ):
        raise AlertDeliveryError(
            "Webhook signing_secret must be non-empty without control chars."
        )
    self._signing_secret = signing_secret
    try:
        self._timeout_seconds = validate_timeout_seconds(timeout_seconds)
    except (BackendError, ValueError) as exc:
        raise AlertDeliveryError(str(exc)) from exc

    self._allow_insecure_http = allow_insecure_http
    self._allow_private_targets = allow_private_targets
    self._allowed_hosts = allowed_hosts
    self._dns_resolver = dns_resolver

    if http_client is not None:
        self._client = http_client
        self._owns_client = False
    else:
        self._client = create_pinned_httpx_client(
            timeout=self._timeout_seconds,
            dns_resolver=self._dns_resolver,
            allow_private_targets=self._allow_private_targets,
            block_link_local=not self._allow_private_targets,
            allowed_hosts=self._allowed_hosts,
            on_blocked=AlertDeliveryError,
        )
        self._owns_client = True

close()

Close the internally managed HTTP client connection pool.

Source code in src/zerobom/outputs/webhook.py
414
415
416
417
def close(self) -> None:
    """Close the internally managed HTTP client connection pool."""
    if self._owns_client:
        self._client.close()

send_outcome(outcome, *, triage_id=None, dedup_check=None, on_sent=None)

Evaluate routing rules and deliver a consolidated alert if warranted.

Source code in src/zerobom/outputs/webhook.py
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def send_outcome(
    self,
    outcome: PipelineOutcome,
    *,
    triage_id: str | None = None,
    dedup_check: Callable[[str, str], bool] | None = None,
    on_sent: Callable[[str, str], None] | None = None,
) -> AlertDeliveryResult:
    """Evaluate routing rules and deliver a consolidated alert if warranted."""
    event_type = classify_alert_event(outcome)
    advisory_id = outcome.osv.id if outcome.osv is not None else None
    if event_type is None:
        return AlertDeliveryResult(
            advisory_id=advisory_id,
            event_type="skipped",
            delivered=False,
            reason="Outcome did not meet outbound alerting thresholds.",
        )

    payload, digest = build_webhook_payload(
        outcome,
        event_type=event_type,
        triage_id=triage_id,
    )
    if (
        event_type == "triage_review"
        and triage_id is not None
        and dedup_check is not None
        and not dedup_check(triage_id, digest)
    ):
        return AlertDeliveryResult(
            advisory_id=advisory_id,
            event_type="skipped",
            delivered=False,
            digest=digest,
            reason=f"Duplicate triage notification suppressed for {triage_id}.",
        )

    # Re-validate DNS before connecting to block DNS-rebinding TOCTOU on long-lived workers.
    validate_webhook_url(
        self._url,
        allow_insecure_http=self._allow_insecure_http,
        allow_private_targets=self._allow_private_targets,
        allowed_hosts=self._allowed_hosts,
        dns_resolver=self._dns_resolver,
    )

    headers: dict[str, str] = {}
    if self._signing_secret is not None:
        timestamp = int(time.time())
        raw_body = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
        headers["X-ZeroBOM-Timestamp"] = str(timestamp)
        headers["X-ZeroBOM-Signature"] = sign_webhook_body(
            raw_body, self._signing_secret, timestamp
        )
        status = self._post_signed_bytes(raw_body, headers)
    else:
        status = _post_json_webhook(
            self._client,
            self._url,
            payload,
            headers=headers,
            backend_name="webhook",
        )

    if event_type == "triage_review" and triage_id is not None and on_sent is not None:
        on_sent(triage_id, digest)

    return AlertDeliveryResult(
        advisory_id=advisory_id,
        event_type=event_type,
        delivered=True,
        status_code=status,
        digest=digest,
    )

send_outcomes(outcomes, *, triage_ids=None, dedup_check=None, on_sent=None)

Deliver alerts across a sequence of :class:PipelineOutcome entries.

Source code in src/zerobom/outputs/webhook.py
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
def send_outcomes(
    self,
    outcomes: Sequence[PipelineOutcome],
    *,
    triage_ids: Mapping[str, str] | None = None,
    dedup_check: Callable[[str, str], bool] | None = None,
    on_sent: Callable[[str, str], None] | None = None,
) -> tuple[AlertDeliveryResult, ...]:
    """Deliver alerts across a sequence of :class:`PipelineOutcome` entries."""
    results: list[AlertDeliveryResult] = []
    for outcome in outcomes:
        adv_id = outcome.osv.id if outcome.osv is not None else None
        triage_id = triage_ids.get(adv_id) if (triage_ids and adv_id) else None
        results.append(
            self.send_outcome(
                outcome,
                triage_id=triage_id,
                dedup_check=dedup_check,
                on_sent=on_sent,
            )
        )
    return tuple(results)

build_issue_marker(advisory_id)

Build the deterministic HTML comment marker used for issue deduplication.

Parameters:

Name Type Description Default
advisory_id str

Advisory identifier (e.g. PRECVE-2026-AA11BB22).

required

Returns:

Type Description
str

Comment marker <!-- zerobom:advisory-id:<id> -->.

Raises:

Type Description
GitHubIssueError

If advisory_id contains unsupported or unsafe characters.

Source code in src/zerobom/outputs/github_issue.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def build_issue_marker(advisory_id: str) -> str:
    """Build the deterministic HTML comment marker used for issue deduplication.

    Args:
        advisory_id: Advisory identifier (e.g. ``PRECVE-2026-AA11BB22``).

    Returns:
        Comment marker ``<!-- zerobom:advisory-id:<id> -->``.

    Raises:
        GitHubIssueError: If ``advisory_id`` contains unsupported or unsafe characters.
    """
    cleaned = _validate_safe_text(advisory_id, field_name="advisory_id").strip()
    if not _SAFE_ADVISORY_ID_RE.fullmatch(cleaned):
        raise GitHubIssueError(
            f"Advisory ID {advisory_id!r} contains disallowed characters for issue marker."
        )
    return f"<!-- zerobom:advisory-id:{cleaned} -->"

build_json_report(outcomes)

Convert pipeline outcomes into a schema-stable JSON-serializable report dictionary.

Parameters:

Name Type Description Default
outcomes Sequence[PipelineOutcome]

Sequence of evaluated :class:PipelineOutcome instances.

required

Returns:

Type Description
dict[str, Any]

Dictionary containing schema, aggregate summary counts, and per-outcome

dict[str, Any]

results with embedded standard OSV v1.6.7 dictionaries.

Source code in src/zerobom/outputs/json_out.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def build_json_report(outcomes: Sequence[PipelineOutcome]) -> dict[str, Any]:
    """Convert pipeline outcomes into a schema-stable JSON-serializable report dictionary.

    Args:
        outcomes: Sequence of evaluated :class:`PipelineOutcome` instances.

    Returns:
        Dictionary containing ``schema``, aggregate ``summary`` counts, and per-outcome
        ``results`` with embedded standard OSV v1.6.7 dictionaries.
    """
    auto_count = 0
    triage_count = 0
    drop_count = 0
    vulnerable_hits = 0
    results: list[dict[str, Any]] = []

    for outcome in outcomes:
        if outcome.credibility is not None:
            if outcome.credibility.routing == RoutingDecision.AUTO:
                auto_count += 1
            elif outcome.credibility.routing == RoutingDecision.TRIAGE:
                triage_count += 1
            else:
                drop_count += 1
        elif outcome.skipped_reason is not None:
            drop_count += 1

        vulnerable_hits += len(outcome.vulnerable_matches)

        results.append(
            {
                "article_url": outcome.article.url if outcome.article is not None else None,
                "skipped_reason": outcome.skipped_reason,
                "prefilter": (
                    outcome.prefilter.model_dump(mode="json")
                    if outcome.prefilter is not None
                    else None
                ),
                "credibility": (
                    outcome.credibility.model_dump(mode="json")
                    if outcome.credibility is not None
                    else None
                ),
                "osv": outcome.osv.to_osv_dict() if outcome.osv is not None else None,
                "matches": [match.model_dump(mode="json") for match in outcome.matches],
            }
        )

    return {
        "schema": "zerobom.report/v1",
        "summary": {
            "total_analyzed": len(outcomes),
            "auto_count": auto_count,
            "triage_count": triage_count,
            "drop_count": drop_count,
            "vulnerable_hits": vulnerable_hits,
        },
        "results": results,
    }

build_sarif_log(outcomes, *, repo_root=None)

Build a GitHub Code Scanning-compatible SARIF 2.1.0 log dictionary.

Emits tool.driver.rules[] definitions with numeric security-severity tags, repo-relative artifactLocation.uri values, cloud-agnostic asset properties, and deterministic partialFingerprints.

Parameters:

Name Type Description Default
outcomes Sequence[PipelineOutcome]

Sequence of evaluated :class:PipelineOutcome entries.

required
repo_root Path | None

Optional repository root directory used to relativize SBOM paths.

None

Returns:

Type Description
dict[str, Any]

SARIF 2.1.0 dictionary ready for JSON serialization and upload.

Source code in src/zerobom/outputs/sarif.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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
def build_sarif_log(
    outcomes: Sequence[PipelineOutcome],
    *,
    repo_root: Path | None = None,
) -> dict[str, Any]:
    """Build a GitHub Code Scanning-compatible SARIF 2.1.0 log dictionary.

    Emits ``tool.driver.rules[]`` definitions with numeric ``security-severity`` tags,
    repo-relative ``artifactLocation.uri`` values, cloud-agnostic asset properties, and
    deterministic ``partialFingerprints``.

    Args:
        outcomes: Sequence of evaluated :class:`PipelineOutcome` entries.
        repo_root: Optional repository root directory used to relativize SBOM paths.

    Returns:
        SARIF 2.1.0 dictionary ready for JSON serialization and upload.
    """
    rules_by_id: dict[str, dict[str, Any]] = {}
    results: list[dict[str, Any]] = []

    for outcome in outcomes:
        vulnerable = outcome.vulnerable_matches
        if not vulnerable:
            continue

        severity_key = _extract_severity(outcome)
        sarif_level, security_severity = _SEVERITY_TO_SARIF.get(
            severity_key,
            _SEVERITY_TO_SARIF["UNKNOWN"],
        )

        osv = outcome.osv
        help_uri = _extract_help_uri(osv)

        for match in vulnerable:
            rule_id = match.advisory_id
            if rule_id not in rules_by_id:
                summary = osv.summary if osv is not None else f"Pre-CVE advisory {rule_id}"
                details = (osv.details or summary) if osv is not None else summary
                rule_obj: dict[str, Any] = {
                    "id": rule_id,
                    "name": rule_id,
                    "shortDescription": {"text": summary},
                    "fullDescription": {"text": details},
                    "defaultConfiguration": {"level": sarif_level},
                    "properties": {
                        "security-severity": security_severity,
                        "tags": ["security", "sbom", "pre-cve", "zerobom"],
                    },
                }
                if help_uri is not None:
                    rule_obj["helpUri"] = help_uri
                rules_by_id[rule_id] = rule_obj

            raw_location = match.sbom_source or (
                match.asset.location if match.asset is not None else None
            )
            artifact_uri = _to_repo_relative_uri(raw_location, repo_root)
            fixed_hint = (
                f" (fixed in {', '.join(match.fixed_versions)})" if match.fixed_versions else ""
            )
            quote_hint = f' Evidence: "{match.evidence_quote}"' if match.evidence_quote else ""
            message = (
                f"Vulnerable component {match.component_purl} ({match.installed_version}) "
                f"matched {rule_id} [{match.matched_purl}]{fixed_hint}.{quote_hint}"
            )

            result_obj: dict[str, Any] = {
                "ruleId": rule_id,
                "level": sarif_level,
                "message": {"text": message},
                "locations": [
                    {
                        "physicalLocation": {
                            "artifactLocation": {
                                "uri": artifact_uri,
                                "uriBaseId": "%SRCROOT%",
                            },
                            "region": {"startLine": 1},
                        }
                    }
                ],
                "partialFingerprints": {
                    "primaryLocationLineHash": _stable_fingerprint(
                        rule_id,
                        artifact_uri,
                        match.matched_purl,
                        match.installed_version,
                        backend=match.asset.backend if match.asset is not None else None,
                        asset_id=match.asset.asset_id if match.asset is not None else None,
                    )
                },
            }
            if match.asset is not None:
                # Never leak local host filesystem paths into SARIF properties for local_sbom.
                safe_asset_id = (
                    artifact_uri if match.asset.backend == "local_sbom" else match.asset.asset_id
                )
                asset_props: dict[str, str] = {
                    "backend": match.asset.backend,
                    "assetId": safe_asset_id,
                    "assetType": match.asset.asset_type,
                }
                if match.asset.scope is not None:
                    asset_props["scope"] = match.asset.scope
                result_obj["properties"] = asset_props
            results.append(result_obj)

    return {
        "$schema": SARIF_SCHEMA_URI,
        "version": SARIF_VERSION,
        "runs": [
            {
                "tool": {
                    "driver": {
                        "name": "zerobom",
                        "version": _driver_version(),
                        "informationUri": REPOSITORY_URL,
                        "rules": list(rules_by_id.values()),
                    }
                },
                "results": results,
            }
        ],
    }

build_slack_auto_payload(outcome)

Build a consolidated Slack Block Kit alert payload for matched vulnerabilities.

Source code in src/zerobom/outputs/slack.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def build_slack_auto_payload(outcome: PipelineOutcome) -> dict[str, Any]:
    """Build a consolidated Slack Block Kit alert payload for matched vulnerabilities."""
    osv = outcome.osv
    advisory_id = escape_slack_mrkdwn(
        _strip_backticks(osv.id if osv is not None else "unknown"),
        max_length=120,
    )
    summary = escape_slack_mrkdwn(
        osv.summary
        if osv is not None
        else (outcome.advisory.summary if outcome.advisory is not None else "Pre-CVE advisory"),
        max_length=500,
    )
    cred = outcome.credibility
    score_label = f"{cred.composite_score:.2f} ({cred.routing.value.upper()})" if cred else "SCAN"

    vulnerable = outcome.vulnerable_matches
    asset_lines: list[str] = []
    header_prefix = "*Affected Assets:*\n"
    reserve_overflow_chars = 80
    used_chars = len(header_prefix)

    for match in vulnerable[:_MAX_SLACK_ASSETS_SHOWN]:
        backend_name = _strip_backticks(
            match.asset.backend if match.asset is not None else "local_sbom"
        )
        asset_id = _strip_backticks(
            match.asset.asset_id if match.asset is not None else (match.sbom_source or "sbom")
        )
        comp_purl = _strip_backticks(match.component_purl)
        installed_ver = _strip_backticks(match.installed_version)
        fixed_str = (
            f" (fixed: {_strip_backticks(', '.join(match.fixed_versions))})"
            if match.fixed_versions
            else ""
        )
        raw_line = f"• `[{backend_name}]` `{asset_id}` — `{comp_purl}` `{installed_ver}`{fixed_str}"
        safe_line = escape_slack_mrkdwn(raw_line, max_length=250)
        line_cost = len(safe_line) + (1 if asset_lines else 0)
        if used_chars + line_cost + reserve_overflow_chars > _MAX_SLACK_SECTION_CHARS:
            break
        asset_lines.append(safe_line)
        used_chars += line_cost

    overflow = len(vulnerable) - len(asset_lines)
    if overflow > 0:
        asset_lines.append(f"• _... and {overflow} more vulnerable asset hit(s)._")

    header_text = _truncate_plain_text(
        f"zerobom ALERT: {advisory_id} ({len(vulnerable)} hit(s))",
        _MAX_SLACK_HEADER_CHARS,
    )
    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {
                "type": "plain_text",
                "text": header_text,
                "emoji": False,
            },
        },
        {
            "type": "section",
            "fields": [
                {"type": "mrkdwn", "text": f"*Advisory:*\n`{advisory_id}`"},
                {"type": "mrkdwn", "text": f"*Credibility:*\n`{score_label}`"},
            ],
        },
        {
            "type": "section",
            "text": {"type": "mrkdwn", "text": f"*Summary:*\n{summary}"},
        },
    ]

    if asset_lines:
        blocks.append(
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": "*Affected Assets:*\n" + "\n".join(asset_lines),
                },
            }
        )

    quotes = extract_verified_quotes(outcome)
    if quotes:
        safe_quote = escape_slack_mrkdwn(quotes[0], max_length=700)
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": f"*Verified Quote:*\n> {safe_quote}"},
            }
        )

    source_url = extract_safe_source_url(outcome)
    if source_url is not None:
        safe_url = escape_slack_mrkdwn(source_url, max_length=1000)
        blocks.append(
            {
                "type": "context",
                "elements": [{"type": "mrkdwn", "text": f"Source: {safe_url}"}],
            }
        )

    return {
        "text": f"zerobom ALERT: {advisory_id} matched {len(vulnerable)} vulnerable asset(s).",
        "blocks": blocks,
    }

build_slack_triage_decision_payload(*, advisory_id, status, actor, match_count=0, already_decided=False, note=None)

Build a Block Kit replace_original update payload after human triage decision.

Source code in src/zerobom/outputs/slack.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def build_slack_triage_decision_payload(
    *,
    advisory_id: str,
    status: str,
    actor: str,
    match_count: int = 0,
    already_decided: bool = False,
    note: str | None = None,
) -> dict[str, Any]:
    """Build a Block Kit ``replace_original`` update payload after human triage decision."""
    safe_adv = escape_slack_mrkdwn(advisory_id, max_length=120)
    safe_actor = escape_slack_mrkdwn(actor, max_length=120)
    safe_status = escape_slack_mrkdwn(status.upper(), max_length=32)

    if already_decided:
        summary_line = (
            f"*{safe_adv}* was already `{safe_status}` previously (no duplicate action taken)."
        )
    elif status.lower() == "approved":
        summary_line = (
            f"*{safe_adv}* marked *APPROVED* by `{safe_actor}` — "
            f"inventory scan found *{match_count}* vulnerable asset(s)."
        )
    else:
        summary_line = f"*{safe_adv}* marked *REJECTED* by `{safe_actor}`."

    if note:
        summary_line += f"\nNote: {escape_slack_mrkdwn(note, max_length=300)}"

    return {
        "replace_original": True,
        "text": summary_line,
        "blocks": [
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": summary_line},
            }
        ],
    }

build_slack_triage_payload(outcome, *, triage_id=None, include_interactive_buttons=True)

Build a Slack Block Kit review notification for TRIAGE advisories.

Source code in src/zerobom/outputs/slack.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def build_slack_triage_payload(
    outcome: PipelineOutcome,
    *,
    triage_id: str | None = None,
    include_interactive_buttons: bool = True,
) -> dict[str, Any]:
    """Build a Slack Block Kit review notification for ``TRIAGE`` advisories."""
    osv = outcome.osv
    advisory_id = escape_slack_mrkdwn(
        _strip_backticks(osv.id if osv is not None else "unknown"),
        max_length=120,
    )
    summary = escape_slack_mrkdwn(
        osv.summary
        if osv is not None
        else (outcome.advisory.summary if outcome.advisory is not None else "Pre-CVE review"),
        max_length=500,
    )
    cred = outcome.credibility
    score_val = f"{cred.composite_score:.2f}" if cred is not None else "N/A"
    tier_val = cred.source_tier.value if cred is not None else "unknown"

    pkg_list = (
        ", ".join(f"`{_strip_backticks(aff.package.purl)}`" for aff in osv.affected[:5])
        if osv is not None
        else "`unknown`"
    )
    safe_pkg_list = escape_slack_mrkdwn(pkg_list, max_length=400)

    cli_approve = (
        f"zerobom triage approve {_strip_backticks(triage_id)}"
        if triage_id
        else f"zerobom scan --osv {advisory_id}.osv.json --sbom <path-to-sbom>"
    )
    safe_cmd = escape_slack_mrkdwn(_strip_backticks(cli_approve), max_length=250)

    triage_header = _truncate_plain_text(
        f"zerobom TRIAGE Review: {advisory_id}",
        _MAX_SLACK_HEADER_CHARS,
    )
    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {
                "type": "plain_text",
                "text": triage_header,
                "emoji": False,
            },
        },
        {
            "type": "section",
            "fields": [
                {"type": "mrkdwn", "text": f"*Score / Tier:*\n`{score_val}` (`{tier_val}`)"},
                {"type": "mrkdwn", "text": f"*Packages:*\n{safe_pkg_list}"},
            ],
        },
        {
            "type": "section",
            "text": {"type": "mrkdwn", "text": f"*Summary:*\n{summary}"},
        },
    ]

    quotes = extract_verified_quotes(outcome)
    if quotes:
        safe_quote = escape_slack_mrkdwn(quotes[0], max_length=700)
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": f"*Verified Quote:*\n> {safe_quote}"},
            }
        )

    blocks.append(
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": f"*Review Command:*\n`{safe_cmd}`",
            },
        }
    )

    if triage_id is not None and include_interactive_buttons:
        blocks.append(
            {
                "type": "actions",
                "elements": [
                    {
                        "type": "button",
                        "text": {"type": "plain_text", "text": "Approve & Scan", "emoji": False},
                        "style": "primary",
                        "action_id": "zerobom_triage_approve",
                        "value": triage_id,
                    },
                    {
                        "type": "button",
                        "text": {"type": "plain_text", "text": "Reject", "emoji": False},
                        "style": "danger",
                        "action_id": "zerobom_triage_reject",
                        "value": triage_id,
                    },
                ],
            }
        )

    source_url = extract_safe_source_url(outcome)
    if source_url is not None:
        safe_url = escape_slack_mrkdwn(source_url, max_length=1000)
        blocks.append(
            {
                "type": "context",
                "elements": [{"type": "mrkdwn", "text": f"Source: {safe_url}"}],
            }
        )

    return {
        "text": f"zerobom TRIAGE Review required for {advisory_id}.",
        "blocks": blocks,
    }

build_webhook_payload(outcome, *, event_type, triage_id=None)

Build a canonical JSON webhook payload and its deterministic SHA-256 digest.

Parameters:

Name Type Description Default
outcome PipelineOutcome

Evaluated :class:PipelineOutcome.

required
event_type Literal['auto_hit', 'triage_review']

Classified notification category ("auto_hit" or "triage_review").

required
triage_id str | None

Optional persisted triage queue ID included for review workflows.

None

Returns:

Type Description
tuple[dict[str, Any], str]

Tuple of (payload_dict, payload_sha256_hex).

Source code in src/zerobom/outputs/webhook.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def build_webhook_payload(
    outcome: PipelineOutcome,
    *,
    event_type: Literal["auto_hit", "triage_review"],
    triage_id: str | None = None,
) -> tuple[dict[str, Any], str]:
    """Build a canonical JSON webhook payload and its deterministic SHA-256 digest.

    Args:
        outcome: Evaluated :class:`PipelineOutcome`.
        event_type: Classified notification category (``"auto_hit"`` or ``"triage_review"``).
        triage_id: Optional persisted triage queue ID included for review workflows.

    Returns:
        Tuple of ``(payload_dict, payload_sha256_hex)``.
    """
    osv = outcome.osv
    credibility = outcome.credibility
    advisory_id = osv.id if osv is not None else "unknown"
    summary = (
        osv.summary
        if osv is not None
        else (outcome.advisory.summary if outcome.advisory is not None else "")
    )

    affected_packages: list[dict[str, str]] = []
    if osv is not None:
        for aff in osv.affected:
            affected_packages.append(
                {
                    "ecosystem": aff.package.ecosystem,
                    "name": aff.package.name,
                    "purl": aff.package.purl,
                }
            )

    matches_list: list[dict[str, Any]] = []
    for match in outcome.vulnerable_matches:
        match_obj: dict[str, Any] = {
            "advisory_id": match.advisory_id,
            "component_purl": match.component_purl,
            "installed_version": match.installed_version,
            "matched_purl": match.matched_purl,
            "ecosystem": match.ecosystem,
            "fixed_versions": list(match.fixed_versions),
            "sbom_source": match.sbom_source,
        }
        if match.asset is not None:
            match_obj["asset"] = {
                "asset_id": match.asset.asset_id,
                "asset_type": match.asset.asset_type,
                "backend": match.asset.backend,
                "scope": match.asset.scope,
                "location": match.asset.location,
            }
        matches_list.append(match_obj)

    if event_type == "triage_review":
        approve_cmd = (
            f"zerobom triage approve {triage_id}"
            if triage_id
            else f"zerobom scan --osv {advisory_id}.osv.json --sbom <path-to-sbom>"
        )
        triage_info: dict[str, Any] | None = {
            "triage_id": triage_id,
            "approve_command": approve_cmd,
            "reject_command": f"zerobom triage reject {triage_id}" if triage_id else None,
        }
    else:
        triage_info = None

    zb_meta = osv.database_specific.get("zerobom") if osv is not None else None
    source_name = (
        outcome.article.source_name
        if outcome.article is not None
        else (zb_meta.get("source_name") if isinstance(zb_meta, Mapping) else None)
    )

    payload: dict[str, Any] = {
        "schema_version": "1.0",
        "event": event_type,
        "advisory_id": advisory_id,
        "summary": summary,
        "source_url": extract_safe_source_url(outcome),
        "source_name": source_name,
        "source_tier": credibility.source_tier.value if credibility is not None else None,
        "composite_score": round(credibility.composite_score, 4) if credibility else None,
        "routing": credibility.routing.value if credibility is not None else "scan",
        "affected_packages": affected_packages,
        "evidence_quotes": list(extract_verified_quotes(outcome)),
        "vulnerable_matches": matches_list,
        "triage": triage_info,
    }
    canonical_bytes = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
    digest = hashlib.sha256(canonical_bytes).hexdigest()
    return payload, digest

classify_alert_event(outcome)

Determine outbound alerting policy for a :class:PipelineOutcome.

Policy: - DROP -> None (silent). - TRIAGE -> "triage_review" when a compiled OSV advisory is present. - AUTO or pure scan (credibility is None) -> "auto_hit" ONLY when at least one vulnerable inventory component matched.

Source code in src/zerobom/outputs/webhook.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def classify_alert_event(
    outcome: PipelineOutcome,
) -> Literal["auto_hit", "triage_review"] | None:
    """Determine outbound alerting policy for a :class:`PipelineOutcome`.

    Policy:
    - ``DROP`` -> ``None`` (silent).
    - ``TRIAGE`` -> ``"triage_review"`` when a compiled OSV advisory is present.
    - ``AUTO`` or pure ``scan`` (``credibility is None``) -> ``"auto_hit"`` ONLY when
      at least one vulnerable inventory component matched.
    """
    if outcome.credibility is not None:
        if outcome.credibility.routing == RoutingDecision.DROP:
            return None
        if outcome.credibility.routing == RoutingDecision.TRIAGE:
            return "triage_review" if outcome.osv is not None else None

    if outcome.osv is not None and outcome.vulnerable_matches:
        return "auto_hit"
    return None

escape_slack_mrkdwn(text, *, max_length=2800)

Sanitize untrusted text for Slack mrkdwn to neutralize mention/link injection.

Strips ASCII control characters (except \n and \t), escapes &, <, and > (blocking <!channel>, <!here>, <@U...>, and spoofed links), and bounds rendered length.

Source code in src/zerobom/outputs/slack.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def escape_slack_mrkdwn(text: str, *, max_length: int = 2800) -> str:
    r"""Sanitize untrusted text for Slack mrkdwn to neutralize mention/link injection.

    Strips ASCII control characters (except ``\n`` and ``\t``), escapes ``&``, ``<``, and
    ``>`` (blocking ``<!channel>``, ``<!here>``, ``<@U...>``, and spoofed links), and bounds
    rendered length.
    """
    cleaned = "".join(ch for ch in text if ch in {"\n", "\t"} or (ord(ch) >= 32 and ord(ch) != 127))
    escaped = cleaned.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
    if max_length < 4:
        return escaped[:max_length]
    if len(escaped) > max_length:
        return escaped[: max_length - 3].rstrip() + "..."
    return escaped

render_github_issue(outcome, *, labels=DEFAULT_ISSUE_LABELS, include_triage=False)

Render an actionable :class:PipelineOutcome into a sanitized GitHub issue payload.

Noise suppression matches zerobom alerting invariants:

  • DROP advisories and AUTO advisories with zero vulnerable matches return None.
  • AUTO advisories with vulnerable inventory hits always render.
  • TRIAGE advisories render only when include_triage=True.

Parameters:

Name Type Description Default
outcome PipelineOutcome

Evaluated pipeline outcome.

required
labels Sequence[str]

Issue labels attached on creation.

DEFAULT_ISSUE_LABELS
include_triage bool

When True, also render pending TRIAGE review issues.

False

Returns:

Type Description
RenderedGitHubIssue | None

Rendered issue payload, or None if no issue should be created/updated.

Raises:

Type Description
GitHubIssueError

If an actionable outcome lacks an OSV advisory or valid labels.

Source code in src/zerobom/outputs/github_issue.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
def render_github_issue(
    outcome: PipelineOutcome,
    *,
    labels: Sequence[str] = DEFAULT_ISSUE_LABELS,
    include_triage: bool = False,
) -> RenderedGitHubIssue | None:
    """Render an actionable :class:`PipelineOutcome` into a sanitized GitHub issue payload.

    Noise suppression matches ``zerobom`` alerting invariants:

    - ``DROP`` advisories and ``AUTO`` advisories with zero vulnerable matches return ``None``.
    - ``AUTO`` advisories with vulnerable inventory hits always render.
    - ``TRIAGE`` advisories render only when ``include_triage=True``.

    Args:
        outcome: Evaluated pipeline outcome.
        labels: Issue labels attached on creation.
        include_triage: When ``True``, also render pending ``TRIAGE`` review issues.

    Returns:
        Rendered issue payload, or ``None`` if no issue should be created/updated.

    Raises:
        GitHubIssueError: If an actionable outcome lacks an OSV advisory or valid labels.
    """
    event_type = classify_alert_event(outcome)
    if event_type is None:
        return None
    if event_type == "triage_review" and not include_triage:
        return None
    if outcome.osv is None:
        raise GitHubIssueError("Actionable outcome cannot render a GitHub issue without OSV data.")

    advisory = outcome.osv
    marker = build_issue_marker(advisory.id)
    pkg_summary = _sanitize_plain_title(_format_package_summary(advisory.affected), max_length=120)
    vulnerable = outcome.vulnerable_matches

    if event_type == "auto_hit":
        match_word = "vulnerable match" if len(vulnerable) == 1 else "vulnerable matches"
        raw_title = f"[zerobom] {advisory.id}: {pkg_summary} ({len(vulnerable)} {match_word})"
        status_heading = "Pre-CVE Vulnerability Hit Detected (Auto-Verified)"
    else:
        raw_title = f"[zerobom][TRIAGE] {advisory.id}: {pkg_summary} (review required)"
        status_heading = "Pre-CVE Advisory Pending Human Triage"

    title = _sanitize_plain_title(raw_title, max_length=240)
    clean_labels = _normalize_labels(labels)

    lines: list[str] = [f"## {status_heading}", ""]
    lines.append(f"- **Advisory ID:** `{advisory.id}`")
    if advisory.aliases:
        alias_list = ", ".join(sanitize_github_markdown(a, max_length=64) for a in advisory.aliases)
        lines.append(f"- **Aliases:** {alias_list}")
    if outcome.credibility is not None:
        cred = outcome.credibility
        tier = cred.source_tier.value
        zb_meta = advisory.database_specific.get("zerobom")
        fallback_source = (
            str(zb_meta.get("source_name"))
            if isinstance(zb_meta, dict) and zb_meta.get("source_name")
            else "unknown"
        )
        raw_source = outcome.article.source_name if outcome.article is not None else fallback_source
        source_name = sanitize_github_markdown(raw_source, max_length=100)
        lines.append(
            f"- **Credibility Score:** `{cred.composite_score:.4f}` "
            f"(`{cred.routing.value.upper()}` | source: {source_name} `{tier}`)"
        )
    lines.append(f"- **Source Reference:** {_format_safe_source_markdown(outcome)}")
    summary_text = advisory.summary.strip() or (
        outcome.article.title if outcome.article is not None else ""
    )
    if summary_text:
        lines.append(f"- **Summary:** {sanitize_github_markdown(summary_text, max_length=500)}")

    quotes = extract_verified_quotes(outcome)
    if quotes:
        lines.extend(["", "### Verified Evidence Quotes", ""])
        for quote in quotes:
            safe_quote = sanitize_github_markdown(quote, max_length=1000)
            for q_line in safe_quote.splitlines() or [safe_quote]:
                lines.append(f"> {q_line}")
            lines.append("")

    if advisory.affected:
        lines.extend(["### Affected Packages & Deterministic Ranges", ""])
        for affected in advisory.affected:
            pkg_label = sanitize_github_markdown(
                affected.package.purl or affected.package.name,
                max_length=180,
            )
            range_str = _format_affected_ranges(affected)
            range_suffix = (
                f" (`{sanitize_github_markdown(range_str, max_length=160)}`)" if range_str else ""
            )
            lines.append(f"- `{pkg_label}`{range_suffix}")

    if vulnerable:
        lines.extend(
            [
                "",
                "### Matched Vulnerable Inventory",
                "",
                "| Matched PURL | Installed | Fixed In | Match Path | Asset / SBOM |",
                "| --- | --- | --- | --- | --- |",
            ]
        )
        for match in vulnerable[:MAX_RENDERED_MATCHES]:
            fixed = ", ".join(match.fixed_versions) if match.fixed_versions else "-"
            asset_loc = match.sbom_source or (
                match.asset.asset_id if match.asset is not None else "-"
            )
            lines.append(
                f"| `{sanitize_table_cell(match.matched_purl)}` "
                f"| `{sanitize_table_cell(match.installed_version)}` "
                f"| `{sanitize_table_cell(fixed)}` "
                f"| {sanitize_table_cell(match.matched_via)} "
                f"| {sanitize_table_cell(asset_loc)} |"
            )
        if len(vulnerable) > MAX_RENDERED_MATCHES:
            remaining = len(vulnerable) - MAX_RENDERED_MATCHES
            lines.append(f"\n_... and {remaining} additional vulnerable matches omitted._")

    if event_type == "triage_review":
        lines.extend(
            [
                "",
                "### Required Action",
                "",
                "Verify the quoted evidence above against the source article, then run:",
                "",
                f"    zerobom triage approve {advisory.id}",
            ]
        )

    lines.extend(["", marker])
    body = _truncate_body_preserving_marker("\n".join(lines), marker, MAX_ISSUE_BODY_CHARS)

    return RenderedGitHubIssue(
        advisory_id=advisory.id,
        event_type=event_type,
        marker=marker,
        title=title,
        body=body,
        labels=clean_labels,
    )

render_json_outcomes(outcomes, *, indent=2)

Render pipeline outcomes as formatted JSON text.

Parameters:

Name Type Description Default
outcomes Sequence[PipelineOutcome]

Sequence of evaluated :class:PipelineOutcome instances.

required
indent int

JSON indentation spaces.

2

Returns:

Type Description
str

Formatted UTF-8 JSON report string.

Source code in src/zerobom/outputs/json_out.py
73
74
75
76
77
78
79
80
81
82
83
def render_json_outcomes(outcomes: Sequence[PipelineOutcome], *, indent: int = 2) -> str:
    """Render pipeline outcomes as formatted JSON text.

    Args:
        outcomes: Sequence of evaluated :class:`PipelineOutcome` instances.
        indent: JSON indentation spaces.

    Returns:
        Formatted UTF-8 JSON report string.
    """
    return json.dumps(build_json_report(outcomes), indent=indent)

render_sarif(outcomes, *, repo_root=None, indent=2)

Serialize pipeline outcomes as formatted SARIF 2.1.0 JSON.

Parameters:

Name Type Description Default
outcomes Sequence[PipelineOutcome]

Sequence of evaluated :class:PipelineOutcome entries.

required
repo_root Path | None

Optional repository root for relativizing SBOM paths.

None
indent int

JSON indentation spaces.

2

Returns:

Type Description
str

Formatted UTF-8 SARIF 2.1.0 JSON string.

Source code in src/zerobom/outputs/sarif.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def render_sarif(
    outcomes: Sequence[PipelineOutcome],
    *,
    repo_root: Path | None = None,
    indent: int = 2,
) -> str:
    """Serialize pipeline outcomes as formatted SARIF 2.1.0 JSON.

    Args:
        outcomes: Sequence of evaluated :class:`PipelineOutcome` entries.
        repo_root: Optional repository root for relativizing SBOM paths.
        indent: JSON indentation spaces.

    Returns:
        Formatted UTF-8 SARIF 2.1.0 JSON string.
    """
    return json.dumps(build_sarif_log(outcomes, repo_root=repo_root), indent=indent)

render_terminal_outcomes(outcomes, *, console=None)

Render advisory verification, grounded quotes, and SBOM hits cleanly to the terminal.

All untrusted strings (article titles, URLs, evidence quotes, PURLs, versions) are wrapped in rich.text.Text objects to prevent terminal markup-injection vulnerabilities.

Parameters:

Name Type Description Default
outcomes Sequence[PipelineOutcome]

Sequence of evaluated :class:PipelineOutcome entries.

required
console Console | None

Optional rich.console.Console target (defaults to stdout console).

None
Source code in src/zerobom/outputs/terminal.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def render_terminal_outcomes(
    outcomes: Sequence[PipelineOutcome],
    *,
    console: Console | None = None,
) -> None:
    """Render advisory verification, grounded quotes, and SBOM hits cleanly to the terminal.

    All untrusted strings (article titles, URLs, evidence quotes, PURLs, versions) are wrapped
    in ``rich.text.Text`` objects to prevent terminal markup-injection vulnerabilities.

    Args:
        outcomes: Sequence of evaluated :class:`PipelineOutcome` entries.
        console: Optional ``rich.console.Console`` target (defaults to stdout console).
    """
    out = console if console is not None else Console()
    if not outcomes:
        out.print(Text("No articles or advisories processed.", style="dim"))
        return

    for outcome in outcomes:
        header_lines = Text()
        if outcome.article is not None:
            header_lines.append("Source: ", style="bold")
            safe_source = _safe_terminal_text(outcome.article.source_name)
            header_lines.append(f"{safe_source} ({outcome.article.source_tier.value})\n")
            header_lines.append("Title: ", style="bold")
            header_lines.append(f"{_safe_terminal_text(outcome.article.title)}\n")
            header_lines.append("URL: ", style="bold")
            header_lines.append(f"{_safe_terminal_text(outcome.article.url)}\n")

        if outcome.osv is not None:
            header_lines.append("OSV ID: ", style="bold")
            header_lines.append(f"{_safe_terminal_text(outcome.osv.id)}\n", style="cyan")
            if outcome.osv.aliases:
                header_lines.append("Aliases: ", style="bold")
                safe_aliases = ", ".join(_safe_terminal_text(a) for a in outcome.osv.aliases)
                header_lines.append(f"{safe_aliases}\n")
            for affected in outcome.osv.affected:
                header_lines.append("Affected: ", style="bold magenta")
                pkg_label = _safe_terminal_text(affected.package.purl or affected.package.name)
                if ":" in affected.package.ecosystem:
                    pkg_label = f"{pkg_label} [{_safe_terminal_text(affected.package.ecosystem)}]"
                range_summary = _format_affected_ranges(affected)
                if range_summary:
                    pkg_label = f"{pkg_label} ({_safe_terminal_text(range_summary)})"
                header_lines.append(f"{pkg_label}\n")

        if outcome.credibility is not None:
            cred = outcome.credibility
            header_lines.append("Credibility Score: ", style="bold")
            header_lines.append(f"{cred.composite_score:.4f} ")
            header_lines.append(
                f"[{cred.routing.value.upper()}]",
                style=_routing_style(cred.routing),
            )
            header_lines.append(
                f" (accepted={len(cred.accepted_claims)}, dropped={len(cred.dropped_claims)})\n"
            )
            seen_quotes: set[str] = set()
            for claim_res in cred.accepted_claims:
                for quote in (claim_res.claim.evidence_quote, *claim_res.claim.supporting_quotes):
                    safe_quote = _safe_terminal_text(quote)
                    if safe_quote in seen_quotes:
                        continue
                    seen_quotes.add(safe_quote)
                    header_lines.append("Verified Quote: ", style="bold green")
                    header_lines.append(f'"{safe_quote}"\n')
            for dropped_res in cred.dropped_claims:
                raw_reason = "; ".join(dropped_res.reasons) if dropped_res.reasons else "dropped"
                reason_text = _safe_terminal_text(raw_reason)
                raw_pkg = _safe_terminal_text(dropped_res.claim.raw_package_name)
                header_lines.append("Dropped Claim: ", style="bold red")
                header_lines.append(f"{raw_pkg} ({reason_text})\n")

        if outcome.skipped_reason is not None:
            header_lines.append("Status: ", style="bold yellow")
            header_lines.append(f"{_safe_terminal_text(outcome.skipped_reason)}\n")

        header_lines.rstrip()
        panel_title = (
            _safe_terminal_text(outcome.osv.id) if outcome.osv is not None else "zerobom Advisory"
        )
        out.print(Panel(header_lines, title=Text(panel_title, style="bold cyan"), expand=False))

        vulnerable = outcome.vulnerable_matches
        if vulnerable:
            table = Table(title="Matched Vulnerable Inventory Assets", show_lines=False)
            table.add_column("Matched PURL", style="magenta", no_wrap=True)
            table.add_column("Installed", style="red", overflow="fold")
            table.add_column("Fixed In", style="green", overflow="fold")
            table.add_column("Via", style="dim", no_wrap=True)
            table.add_column("Asset / SBOM", overflow="fold")

            for match in vulnerable:
                fixed = (
                    ", ".join(_safe_terminal_text(v) for v in match.fixed_versions)
                    if match.fixed_versions
                    else "-"
                )
                asset_loc = match.sbom_source or (
                    match.asset.asset_id if match.asset is not None else "-"
                )
                table.add_row(
                    Text(_safe_terminal_text(match.matched_purl)),
                    Text(_safe_terminal_text(match.installed_version)),
                    Text(fixed),
                    Text(_safe_terminal_text(match.matched_via)),
                    Text(_safe_terminal_text(_compact_asset_label(asset_loc))),
                )
            out.print(table)
        else:
            out.print(Text("No vulnerable inventory matches found.", style="green"))

sanitize_github_markdown(text, *, max_length=2000)

Sanitize untrusted text before embedding it into GitHub Flavored Markdown.

Defends against raw HTML/XSS injection, HTML comment breakouts, automatic image rendering (![alt](url) pixel/SSRF vectors), and unintended mass @mention pings.

Parameters:

Name Type Description Default
text str

Untrusted text extracted from security blogs, SBOMs, or package metadata.

required
max_length int

Maximum output character length before truncation.

2000

Returns:

Type Description
str

Escaped, length-bounded Markdown-safe string.

Source code in src/zerobom/outputs/github_issue.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
def sanitize_github_markdown(text: str, *, max_length: int = 2000) -> str:
    """Sanitize untrusted text before embedding it into GitHub Flavored Markdown.

    Defends against raw HTML/XSS injection, HTML comment breakouts, automatic image
    rendering (``![alt](url)`` pixel/SSRF vectors), and unintended mass ``@mention`` pings.

    Args:
        text: Untrusted text extracted from security blogs, SBOMs, or package metadata.
        max_length: Maximum output character length before truncation.

    Returns:
        Escaped, length-bounded Markdown-safe string.
    """
    cleaned = _CONTROL_CHARS_RE.sub("", text).replace("\r\n", "\n").replace("\r", "\n")
    # Neutralize HTML/comment tags first so attacker text cannot break comment markers or XSS.
    cleaned = cleaned.replace("<!--", "&lt;!--").replace("-->", "--&gt;")
    cleaned = cleaned.replace("<", "&lt;").replace(">", "&gt;")
    # Break Markdown image auto-fetch syntax (`![` -> `!\[`).
    cleaned = cleaned.replace("![", "!\\[")
    # Break `@mention` notifications without introducing raw backtick imbalance.
    cleaned = _MENTION_RE.sub("@\u200b\\1", cleaned)
    cleaned = cleaned.strip()
    if len(cleaned) > max_length:
        cutoff = max(0, max_length - 3)
        cleaned = f"{cleaned[:cutoff]}..."
    return cleaned

sanitize_table_cell(text, *, max_length=200)

Sanitize untrusted text for safe single-line rendering inside a GFM table cell.

Parameters:

Name Type Description Default
text str

Untrusted cell string.

required
max_length int

Maximum cell length.

200

Returns:

Type Description
str

Single-line, pipe-escaped Markdown cell string.

Source code in src/zerobom/outputs/github_issue.py
194
195
196
197
198
199
200
201
202
203
204
205
206
def sanitize_table_cell(text: str, *, max_length: int = 200) -> str:
    """Sanitize untrusted text for safe single-line rendering inside a GFM table cell.

    Args:
        text: Untrusted cell string.
        max_length: Maximum cell length.

    Returns:
        Single-line, pipe-escaped Markdown cell string.
    """
    single_line = _WHITESPACE_RUN_RE.sub(" ", text).strip()
    sanitized = sanitize_github_markdown(single_line, max_length=max_length)
    return sanitized.replace("|", "&#124;")

sign_webhook_body(body, secret, timestamp)

Compute sha256=<hex> HMAC signature over {timestamp}.{body}.

Source code in src/zerobom/outputs/webhook.py
146
147
148
149
150
def sign_webhook_body(body: bytes, secret: str, timestamp: int) -> str:
    """Compute ``sha256=<hex>`` HMAC signature over ``{timestamp}.{body}``."""
    signed_payload = f"{timestamp}.".encode("ascii") + body
    digest = hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256).hexdigest()
    return f"sha256={digest}"

validate_github_repo(repo)

Validate and split a owner/repo GitHub repository slug.

Parameters:

Name Type Description Default
repo str

Repository slug in owner/name format.

required

Returns:

Type Description
tuple[str, str]

Validated (owner, name) tuple free of traversal or control characters.

Raises:

Type Description
GitHubIssueError

If repo is malformed or contains unsafe characters.

Source code in src/zerobom/outputs/github_issue.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
def validate_github_repo(repo: str) -> tuple[str, str]:
    """Validate and split a ``owner/repo`` GitHub repository slug.

    Args:
        repo: Repository slug in ``owner/name`` format.

    Returns:
        Validated ``(owner, name)`` tuple free of traversal or control characters.

    Raises:
        GitHubIssueError: If ``repo`` is malformed or contains unsafe characters.
    """
    cleaned = _validate_safe_text(repo, field_name="github_repo").strip()
    if len(cleaned) > 205 or "\\" in cleaned or "/" not in cleaned:
        raise GitHubIssueError(f"Invalid GitHub repository slug: {repo!r} (expected owner/repo).")
    parts = cleaned.split("/")
    if len(parts) != 2:
        raise GitHubIssueError(f"Invalid GitHub repository slug: {repo!r} (expected owner/repo).")
    owner, name = parts
    if not _OWNER_RE.fullmatch(owner):
        raise GitHubIssueError(f"Invalid GitHub repository owner: {owner!r}.")
    if name in {".", ".."} or not _REPO_NAME_RE.fullmatch(name):
        raise GitHubIssueError(f"Invalid GitHub repository name: {name!r}.")
    return owner, name

validate_webhook_url(url, *, allow_insecure_http=False, allow_private_targets=False, allowed_hosts=None, dns_resolver=default_dns_resolver)

Validate an outbound webhook/callback URL against scheme, host, and SSRF policies.

Parameters:

Name Type Description Default
url str

Candidate webhook or Slack callback URL.

required
allow_insecure_http bool

Explicit opt-in for plain http:// URLs (dev/local only).

False
allow_private_targets bool

Explicit opt-in to skip public-IP checks (internal relays only).

False
allowed_hosts frozenset[str] | None

Optional exact lowercase hostname allowlist (e.g. Slack webhook hosts).

None
dns_resolver DnsResolver

DNS resolution callable returning IP strings for host/port pairs.

default_dns_resolver

Returns:

Type Description
str

Normalized trimmed webhook URL.

Raises:

Type Description
AlertDeliveryError

If syntax, scheme, credentials, host allowlist, or IP checks fail.

Source code in src/zerobom/outputs/webhook.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def validate_webhook_url(
    url: str,
    *,
    allow_insecure_http: bool = False,
    allow_private_targets: bool = False,
    allowed_hosts: frozenset[str] | None = None,
    dns_resolver: DnsResolver = default_dns_resolver,
) -> str:
    """Validate an outbound webhook/callback URL against scheme, host, and SSRF policies.

    Args:
        url: Candidate webhook or Slack callback URL.
        allow_insecure_http: Explicit opt-in for plain ``http://`` URLs (dev/local only).
        allow_private_targets: Explicit opt-in to skip public-IP checks (internal relays only).
        allowed_hosts: Optional exact lowercase hostname allowlist (e.g. Slack webhook hosts).
        dns_resolver: DNS resolution callable returning IP strings for host/port pairs.

    Returns:
        Normalized trimmed webhook URL.

    Raises:
        AlertDeliveryError: If syntax, scheme, credentials, host allowlist, or IP checks fail.
    """
    if not isinstance(url, str):
        raise AlertDeliveryError("Webhook URL must be a string.")
    if any(ord(ch) < 32 or ord(ch) == 127 for ch in url):
        raise AlertDeliveryError("Webhook URL must not contain ASCII control characters.")

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

    parsed = urlsplit(cleaned)
    scheme = parsed.scheme.lower()
    allowed_schemes = {"https", "http"} if allow_insecure_http else {"https"}
    if scheme not in allowed_schemes:
        if scheme == "http" and not allow_insecure_http:
            raise AlertDeliveryError(
                "Webhook URL requires https:// (pass allow_insecure_http=True to permit http://)."
            )
        raise AlertDeliveryError(f"Unsupported webhook URL scheme {parsed.scheme!r}.")

    if parsed.username is not None or parsed.password is not None:
        raise AlertDeliveryError("Webhook URL must not embed credentials.")
    if parsed.fragment:
        raise AlertDeliveryError("Webhook URL must not include a fragment.")

    hostname = (parsed.hostname or "").lower()
    if not hostname:
        raise AlertDeliveryError("Webhook URL must include a valid hostname.")

    if allowed_hosts is not None and hostname not in allowed_hosts:
        raise AlertDeliveryError(
            f"Webhook host {hostname!r} is not in the permitted host allowlist "
            f"{sorted(allowed_hosts)}."
        )

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

    if not allow_private_targets:
        try:
            ipaddress.ip_address(hostname)
        except ValueError:
            pass
        else:
            if not is_public_ip(hostname):
                raise AlertDeliveryError(
                    f"Blocked non-public webhook literal IP host {hostname!r}."
                )

        try:
            resolved_ips = dns_resolver(hostname, port)
        except Exception as exc:
            raise AlertDeliveryError(
                f"DNS resolution failed for webhook host {hostname!r}: {exc}"
            ) from exc

        if not resolved_ips:
            raise AlertDeliveryError(
                f"DNS resolution returned no IPs for webhook host {hostname!r}."
            )
        for ip_str in resolved_ips:
            if not is_public_ip(ip_str):
                raise AlertDeliveryError(
                    f"Blocked SSRF target: webhook host {hostname!r} resolved to non-public "
                    f"IP {ip_str!r}."
                )

    return cleaned