Skip to content

Human Triage Queue & Worker

SQLite triage queue persistence, concurrency-serialized approve/reject action handler, signed Slack HTTP callback receiver, and optional Socket Mode listener.

triage

Human-in-the-loop triage queue, shared action handler, and signed callback server.

SlackInteractionRequest

Bases: StrictModel

Validated interactive Slack Block Kit button callback action.

TriageActionHandler(store, *, backend_factory=None, alert_notifiers=())

Shared deterministic execution engine for CLI, HTTP webhook, and Socket Mode actions.

Initialize the shared triage decision engine.

Parameters:

Name Type Description Default
store TriageQueueStore

SQLite triage queue store.

required
backend_factory Callable[[], InventoryBackend | None] | None

Optional callable creating a fresh :class:InventoryBackend when approving an advisory (close() is invoked automatically).

None
alert_notifiers Sequence[TriageNotifier]

Outbound notifiers notified only when an approved item yields hits.

()
Source code in src/zerobom/triage/actions.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def __init__(
    self,
    store: TriageQueueStore,
    *,
    backend_factory: Callable[[], InventoryBackend | None] | None = None,
    alert_notifiers: Sequence[TriageNotifier] = (),
) -> None:
    """Initialize the shared triage decision engine.

    Args:
        store: SQLite triage queue store.
        backend_factory: Optional callable creating a fresh :class:`InventoryBackend`
            when approving an advisory (``close()`` is invoked automatically).
        alert_notifiers: Outbound notifiers notified only when an approved item yields hits.
    """
    self._store = store
    self._backend_factory = backend_factory
    self._alert_notifiers = tuple(alert_notifiers)
    self._locks_guard = threading.Lock()
    self._item_locks: dict[str, threading.Lock] = {}

approve(triage_id, *, actor, note=None)

Approve a PENDING advisory, scan inventory deterministically, and alert on hits.

Source code in src/zerobom/triage/actions.py
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
def approve(
    self,
    triage_id: str,
    *,
    actor: str,
    note: str | None = None,
) -> TriageActionResult:
    """Approve a ``PENDING`` advisory, scan inventory deterministically, and alert on hits."""
    cleaned_id = validate_triage_id(triage_id)
    with self._lock_for_id(cleaned_id):
        record = self._store.get(cleaned_id)
        if record is None:
            raise TriageNotFoundError(f"Triage item {cleaned_id!r} does not exist.")

        if record.status != TriageStatus.PENDING:
            return TriageActionResult(
                record=record,
                already_decided=True,
            )

        try:
            osv = OsvAdvisory.model_validate_json(record.osv_json)
            credibility = CredibilityReport.model_validate_json(record.credibility_json)
        except Exception as exc:
            raise TriageError(
                f"Corrupted OSV/credibility payload stored for triage item "
                f"{record.triage_id!r}: {exc}"
            ) from exc

        matches: tuple[MatchResult, ...] = ()
        if self._backend_factory is not None:
            with ExitStack() as stack:
                backend = self._backend_factory()
                if backend is not None:
                    close_fn = getattr(backend, "close", None)
                    if callable(close_fn):
                        stack.callback(close_fn)
                    matches = match_advisory_with_backend(osv, backend, only_vulnerable=True)

        matches_json = (
            json.dumps([m.model_dump(mode="json") for m in matches], sort_keys=True)
            if matches
            else "[]"
        )

        updated, transitioned = self._store.transition_status(
            record.triage_id,
            new_status=TriageStatus.APPROVED,
            actor=actor,
            note=note,
            match_count=len(matches),
            matches_json=matches_json,
        )
        if not transitioned:
            return TriageActionResult(record=updated, already_decided=True)

        alert_sent = False
        if matches and self._alert_notifiers:
            approved_outcome = PipelineOutcome(
                credibility=credibility.model_copy(update={"routing": RoutingDecision.AUTO}),
                osv=osv,
                matches=matches,
            )
            for notifier in self._alert_notifiers:
                delivery = notifier.send_outcome(approved_outcome)
                if delivery.delivered:
                    alert_sent = True

        return TriageActionResult(
            record=updated,
            matches=matches,
            already_decided=False,
            alert_sent=alert_sent,
        )

execute_slack_interaction(request)

Dispatch a Slack interactive callback and return a replacement Block Kit body.

Source code in src/zerobom/triage/actions.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def execute_slack_interaction(
    self,
    request: SlackInteractionRequest,
) -> tuple[TriageActionResult, dict[str, Any]]:
    """Dispatch a Slack interactive callback and return a replacement Block Kit body."""
    if request.action_id == "zerobom_triage_approve":
        result = self.approve(request.triage_id, actor=request.actor)
    else:
        result = self.reject(request.triage_id, actor=request.actor)

    payload = build_slack_triage_decision_payload(
        advisory_id=result.record.advisory_id,
        status=result.record.status.value,
        actor=result.record.decided_by or request.actor,
        match_count=result.record.last_match_count or len(result.matches),
        already_decided=result.already_decided,
        note=result.record.decision_note,
    )
    return result, payload

reject(triage_id, *, actor, note=None)

Reject a PENDING advisory without scanning or alerting.

Source code in src/zerobom/triage/actions.py
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
def reject(
    self,
    triage_id: str,
    *,
    actor: str,
    note: str | None = None,
) -> TriageActionResult:
    """Reject a ``PENDING`` advisory without scanning or alerting."""
    cleaned_id = validate_triage_id(triage_id)
    with self._lock_for_id(cleaned_id):
        record = self._store.get(cleaned_id)
        if record is None:
            raise TriageNotFoundError(f"Triage item {cleaned_id!r} does not exist.")
        if record.status != TriageStatus.PENDING:
            return TriageActionResult(record=record, already_decided=True)

        updated, transitioned = self._store.transition_status(
            record.triage_id,
            new_status=TriageStatus.REJECTED,
            actor=actor,
            note=note,
        )
        return TriageActionResult(
            record=updated,
            already_decided=not transitioned,
        )

TriageActionResult

Bases: StrictModel

Result of executing an approve or reject triage decision.

TriageError

Bases: RuntimeError

Base error for triage queue persistence, validation, and action failures.

TriageNotFoundError

Bases: TriageError

Raised when a requested triage item ID does not exist in the queue store.

TriageQueueStore(db_path)

SQLite-backed human triage queue with atomic state transitions and alert dedup.

Initialize the triage SQLite database and ensure WAL/schema setup.

Source code in src/zerobom/triage/store.py
140
141
142
143
144
def __init__(self, db_path: Path | str) -> None:
    """Initialize the triage SQLite database and ensure WAL/schema setup."""
    self._db_path = Path(db_path)
    self._db_path.parent.mkdir(parents=True, exist_ok=True)
    self._init_schema()

db_path property

Filesystem path backing this SQLite triage queue.

enqueue_outcome(outcome)

Enqueue a compiled TRIAGE outcome into the persistent queue, if eligible.

Already-decided records are preserved intact rather than silently reverted to pending.

Source code in src/zerobom/triage/store.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
def enqueue_outcome(self, outcome: PipelineOutcome) -> TriageRecord | None:
    """Enqueue a compiled ``TRIAGE`` outcome into the persistent queue, if eligible.

    Already-decided records are preserved intact rather than silently reverted to pending.
    """
    if (
        outcome.osv is None
        or outcome.credibility is None
        or outcome.credibility.routing != RoutingDecision.TRIAGE
    ):
        return None

    triage_id = validate_triage_id(outcome.osv.id)
    now_iso = datetime.now(UTC).isoformat()
    osv_json = json.dumps(outcome.osv.to_osv_dict(), sort_keys=True)
    credibility_json = outcome.credibility.model_dump_json()

    quotes = extract_verified_quotes(outcome)
    evidence_quote = quotes[0] if quotes else None

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

    conn = self._connect()
    try:
        with conn:
            current_record = _fetch_record(conn, triage_id)
            if current_record is not None:
                if current_record.status != TriageStatus.PENDING:
                    return current_record
                conn.execute(
                    """
                    UPDATE triage_items
                    SET article_url = ?, source_name = ?, title = ?, composite_score = ?,
                        osv_json = ?, credibility_json = ?, evidence_quote = ?, updated_at = ?
                    WHERE triage_id = ? AND status = ?
                    """,
                    (
                        outcome.credibility.article_url,
                        _sanitize_short_text(source_name, max_length=200, fallback="Unknown"),
                        _sanitize_short_text(title, max_length=500, fallback=outcome.osv.id),
                        float(outcome.credibility.composite_score),
                        osv_json,
                        credibility_json,
                        evidence_quote,
                        now_iso,
                        triage_id,
                        TriageStatus.PENDING.value,
                    ),
                )
            else:
                conn.execute(
                    """
                    INSERT INTO triage_items (
                        triage_id, advisory_id, article_url, source_name, title,
                        composite_score, status, osv_json, credibility_json, evidence_quote,
                        created_at, updated_at
                    )
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    """,
                    (
                        triage_id,
                        outcome.osv.id,
                        outcome.credibility.article_url,
                        _sanitize_short_text(source_name, max_length=200, fallback="Unknown"),
                        _sanitize_short_text(title, max_length=500, fallback=outcome.osv.id),
                        float(outcome.credibility.composite_score),
                        TriageStatus.PENDING.value,
                        osv_json,
                        credibility_json,
                        evidence_quote,
                        now_iso,
                        now_iso,
                    ),
                )
            persisted = _fetch_record(conn, triage_id)
            if persisted is None:
                raise TriageError(f"Failed to persist triage item {triage_id!r}.")
            return persisted
    finally:
        conn.close()

get(triage_id)

Retrieve a single :class:TriageRecord by ID, or None if not present.

Source code in src/zerobom/triage/store.py
305
306
307
308
309
310
311
312
def get(self, triage_id: str) -> TriageRecord | None:
    """Retrieve a single :class:`TriageRecord` by ID, or ``None`` if not present."""
    cleaned_id = validate_triage_id(triage_id)
    conn = self._connect()
    try:
        return _fetch_record(conn, cleaned_id)
    finally:
        conn.close()

list_items(*, status=None, limit=100)

List triage records ordered newest-first, optionally filtered by status.

Source code in src/zerobom/triage/store.py
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
def list_items(
    self,
    *,
    status: TriageStatus | None = None,
    limit: int = 100,
) -> tuple[TriageRecord, ...]:
    """List triage records ordered newest-first, optionally filtered by status."""
    if isinstance(limit, bool) or not 1 <= limit <= 1000:
        raise TriageError("list_items 'limit' must be between 1 and 1000.")
    conn = self._connect()
    try:
        if status is not None:
            rows = conn.execute(
                """
                SELECT triage_id, advisory_id, article_url, source_name, title,
                       composite_score, status, osv_json, credibility_json, evidence_quote,
                       notification_digest, notified_at, created_at, updated_at, decided_at,
                       decided_by, decision_note, last_match_count, last_matches_json
                FROM triage_items
                WHERE status = ?
                ORDER BY created_at DESC LIMIT ?
                """,
                (status.value, limit),
            ).fetchall()
        else:
            rows = conn.execute(
                """
                SELECT triage_id, advisory_id, article_url, source_name, title,
                       composite_score, status, osv_json, credibility_json, evidence_quote,
                       notification_digest, notified_at, created_at, updated_at, decided_at,
                       decided_by, decision_note, last_match_count, last_matches_json
                FROM triage_items
                ORDER BY created_at DESC LIMIT ?
                """,
                (limit,),
            ).fetchall()
        return tuple(_row_to_record(r) for r in rows)
    finally:
        conn.close()

mark_notified(triage_id, digest, *, channel='default')

Record that digest was delivered for (triage_id, channel).

Source code in src/zerobom/triage/store.py
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
def mark_notified(self, triage_id: str, digest: str, *, channel: str = "default") -> None:
    """Record that ``digest`` was delivered for ``(triage_id, channel)``."""
    cleaned_id = validate_triage_id(triage_id)
    cleaned_channel = channel.strip().lower()
    if not _SAFE_CHANNEL_RE.fullmatch(cleaned_channel):
        raise TriageError(f"Invalid notification channel name: {channel!r}.")
    now_iso = datetime.now(UTC).isoformat()
    conn = self._connect()
    try:
        with conn:
            conn.execute(
                """
                INSERT INTO triage_notifications (triage_id, channel, digest, notified_at)
                VALUES (?, ?, ?, ?)
                ON CONFLICT(triage_id, channel) DO UPDATE SET
                    digest = excluded.digest,
                    notified_at = excluded.notified_at
                """,
                (cleaned_id, cleaned_channel, digest, now_iso),
            )
            conn.execute(
                """
                UPDATE triage_items
                SET notification_digest = ?, notified_at = ?, updated_at = ?
                WHERE triage_id = ?
                """,
                (digest, now_iso, now_iso, cleaned_id),
            )
    finally:
        conn.close()

schema_version()

Return the current SQLite PRAGMA user_version integer.

Source code in src/zerobom/triage/store.py
205
206
207
208
209
210
211
212
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()

should_notify(triage_id, digest, *, channel='default')

Return True if (triage_id, channel) has not already sent digest.

Source code in src/zerobom/triage/store.py
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
def should_notify(self, triage_id: str, digest: str, *, channel: str = "default") -> bool:
    """Return ``True`` if ``(triage_id, channel)`` has not already sent ``digest``."""
    cleaned_id = validate_triage_id(triage_id)
    cleaned_channel = channel.strip().lower()
    if not _SAFE_CHANNEL_RE.fullmatch(cleaned_channel):
        raise TriageError(f"Invalid notification channel name: {channel!r}.")
    conn = self._connect()
    try:
        row = conn.execute(
            "SELECT digest FROM triage_notifications WHERE triage_id = ? AND channel = ?",
            (cleaned_id, cleaned_channel),
        ).fetchone()
        if row is not None:
            return str(row[0]) != digest
        has_any_channel = conn.execute(
            "SELECT 1 FROM triage_notifications WHERE triage_id = ? LIMIT 1",
            (cleaned_id,),
        ).fetchone()
        if has_any_channel is not None:
            # Avoid cross-suppressing when other channels have entries, but none for this one.
            return True
        item_row = conn.execute(
            "SELECT notification_digest FROM triage_items WHERE triage_id = ?",
            (cleaned_id,),
        ).fetchone()
        if item_row is not None and item_row[0] is not None:
            return str(item_row[0]) != digest
        return True
    finally:
        conn.close()

transition_status(triage_id, *, new_status, actor, note=None, match_count=None, matches_json=None)

Atomically transition a PENDING item to APPROVED or REJECTED.

Returns:

Type Description
TriageRecord

(record, True) if this caller won the transition; (existing, False) if the

bool

item had already transitioned previously (preventing duplicate concurrent alerts).

Source code in src/zerobom/triage/store.py
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
def transition_status(
    self,
    triage_id: str,
    *,
    new_status: TriageStatus,
    actor: str,
    note: str | None = None,
    match_count: int | None = None,
    matches_json: str | None = None,
) -> tuple[TriageRecord, bool]:
    """Atomically transition a ``PENDING`` item to ``APPROVED`` or ``REJECTED``.

    Returns:
        ``(record, True)`` if this caller won the transition; ``(existing, False)`` if the
        item had already transitioned previously (preventing duplicate concurrent alerts).
    """
    if new_status == TriageStatus.PENDING:
        raise TriageError("Cannot transition a triage item back to 'pending'.")

    cleaned_id = validate_triage_id(triage_id)
    safe_actor = _sanitize_short_text(actor, max_length=128, fallback="unknown")
    safe_note = _sanitize_short_text(note, max_length=512, fallback="") or None
    now_iso = datetime.now(UTC).isoformat()

    conn = self._connect()
    try:
        with conn:
            cursor = conn.execute(
                """
                UPDATE triage_items
                SET status = ?, decided_at = ?, decided_by = ?, decision_note = ?,
                    last_match_count = ?, last_matches_json = ?, updated_at = ?
                WHERE triage_id = ? AND status = ?
                """,
                (
                    new_status.value,
                    now_iso,
                    safe_actor,
                    safe_note,
                    match_count,
                    matches_json,
                    now_iso,
                    cleaned_id,
                    TriageStatus.PENDING.value,
                ),
            )
            transitioned = cursor.rowcount == 1
            record = _fetch_record(conn, cleaned_id)
            if record is None:
                raise TriageNotFoundError(f"Triage item {cleaned_id!r} was not found.")
            return record, transitioned
    finally:
        conn.close()

TriageRecord

Bases: StrictModel

Persistent triage queue item capturing compiled OSV JSON and human audit state.

TriageStatus

Bases: StrEnum

Lifecycle states of a queued human-triage advisory.

TriageWebhookServer(handler, *, signing_secret, host='127.0.0.1', port=8787, callback_path='/slack/actions', max_body_bytes=MAX_SLACK_CALLBACK_BYTES, max_skew_seconds=DEFAULT_SIGNATURE_MAX_SKEW_SECONDS, request_timeout_seconds=10.0, max_concurrent_requests=32, response_allowed_hosts=SLACK_WEBHOOK_HOSTS, dns_resolver=default_dns_resolver, response_http_client=None, now_fn=None)

Zero-dependency HTTP server receiving signed Slack interactive callbacks with <3s ack.

Initialize the signed Slack HTTP triage callback worker.

Parameters:

Name Type Description Default
handler TriageActionHandler

Shared :class:TriageActionHandler executing approve/reject actions.

required
signing_secret str

Slack App Signing Secret used to verify X-Slack-Signature.

required
host str

Bind interface (defaults to loopback 127.0.0.1).

'127.0.0.1'
port int

TCP port (0 binds an ephemeral test port).

8787
callback_path str

HTTP POST route handling interactive callbacks.

'/slack/actions'
max_body_bytes int

Maximum incoming HTTP request payload ceiling.

MAX_SLACK_CALLBACK_BYTES
max_skew_seconds int

Timestamp replay tolerance in seconds (default 300).

DEFAULT_SIGNATURE_MAX_SKEW_SECONDS
request_timeout_seconds float

Socket read timeout per connection (Slowloris defense).

10.0
max_concurrent_requests int

Maximum simultaneous in-flight POST handlers.

32
response_allowed_hosts frozenset[str]

Pinned allowlist for Slack response_url updates.

SLACK_WEBHOOK_HOSTS
dns_resolver DnsResolver

DNS resolver injected for URL/SSRF verification.

default_dns_resolver
response_http_client Client | None

Optional :class:httpx.Client for response_url POSTs.

None
now_fn Callable[[], int] | None

Optional clock function returning epoch seconds for deterministic tests.

None
Source code in src/zerobom/triage/server.py
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
def __init__(
    self,
    handler: TriageActionHandler,
    *,
    signing_secret: str,
    host: str = "127.0.0.1",
    port: int = 8787,
    callback_path: str = "/slack/actions",
    max_body_bytes: int = MAX_SLACK_CALLBACK_BYTES,
    max_skew_seconds: int = DEFAULT_SIGNATURE_MAX_SKEW_SECONDS,
    request_timeout_seconds: float = 10.0,
    max_concurrent_requests: int = 32,
    response_allowed_hosts: frozenset[str] = SLACK_WEBHOOK_HOSTS,
    dns_resolver: DnsResolver = default_dns_resolver,
    response_http_client: httpx.Client | None = None,
    now_fn: Callable[[], int] | None = None,
) -> None:
    """Initialize the signed Slack HTTP triage callback worker.

    Args:
        handler: Shared :class:`TriageActionHandler` executing approve/reject actions.
        signing_secret: Slack App Signing Secret used to verify ``X-Slack-Signature``.
        host: Bind interface (defaults to loopback ``127.0.0.1``).
        port: TCP port (``0`` binds an ephemeral test port).
        callback_path: HTTP POST route handling interactive callbacks.
        max_body_bytes: Maximum incoming HTTP request payload ceiling.
        max_skew_seconds: Timestamp replay tolerance in seconds (default ``300``).
        request_timeout_seconds: Socket read timeout per connection (Slowloris defense).
        max_concurrent_requests: Maximum simultaneous in-flight POST handlers.
        response_allowed_hosts: Pinned allowlist for Slack ``response_url`` updates.
        dns_resolver: DNS resolver injected for URL/SSRF verification.
        response_http_client: Optional :class:`httpx.Client` for ``response_url`` POSTs.
        now_fn: Optional clock function returning epoch seconds for deterministic tests.
    """
    if not isinstance(signing_secret, str) or not signing_secret.strip():
        raise TriageError("Slack callback server requires a non-empty signing_secret.")
    if any(ord(ch) < 32 or ord(ch) == 127 for ch in signing_secret):
        raise TriageError("signing_secret must not contain control characters.")

    try:
        self._request_timeout_seconds = validate_timeout_seconds(request_timeout_seconds)
        conc_limit = validate_bounded_int(
            max_concurrent_requests,
            field_name="max_concurrent_requests",
            min_value=1,
            max_value=256,
        )
    except (BackendError, ValueError) as exc:
        raise TriageError(str(exc)) from exc

    cleaned_path = "/" + callback_path.strip().lstrip("/")
    if not cleaned_path or " " in cleaned_path:
        raise TriageError(f"Invalid callback_path: {callback_path!r}.")

    self._handler = handler
    self._signing_secret = signing_secret
    self._callback_path = cleaned_path
    self._max_body_bytes = max_body_bytes
    self._max_skew_seconds = max_skew_seconds
    self._inflight_sem = threading.BoundedSemaphore(conc_limit)
    self._response_allowed_hosts = response_allowed_hosts
    self._dns_resolver = dns_resolver
    self._response_http_client = response_http_client
    self._now_fn = now_fn

    self._executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="zerobom-triage")
    self._pending_lock = threading.Lock()
    self._pending: set[Future[None]] = set()
    self._errors_lock = threading.Lock()
    self._background_errors: list[str] = []

    request_handler_cls = self._build_request_handler()
    self._httpd = _ReusableThreadingHTTPServer((host, port), request_handler_cls)

background_errors property

Return any errors captured while executing async triage background tasks.

server_address property

Return bound (host, port) tuple.

server_port property

Return the bound TCP port.

close()

Shutdown background worker pool and close the listening socket.

Source code in src/zerobom/triage/server.py
241
242
243
244
def close(self) -> None:
    """Shutdown background worker pool and close the listening socket."""
    self._httpd.server_close()
    self._executor.shutdown(wait=True)

serve_forever()

Start serving signed HTTP callbacks until :meth:shutdown is called.

Source code in src/zerobom/triage/server.py
224
225
226
def serve_forever(self) -> None:
    """Start serving signed HTTP callbacks until :meth:`shutdown` is called."""
    self._httpd.serve_forever()

shutdown()

Stop the HTTP server loop cleanly.

Source code in src/zerobom/triage/server.py
228
229
230
def shutdown(self) -> None:
    """Stop the HTTP server loop cleanly."""
    self._httpd.shutdown()

wait_for_pending(timeout=5.0)

Block until all currently queued async triage tasks complete.

Source code in src/zerobom/triage/server.py
232
233
234
235
236
237
238
239
def wait_for_pending(self, timeout: float = 5.0) -> None:
    """Block until all currently queued async triage tasks complete."""
    with self._pending_lock:
        futures = list(self._pending)
    deadline = time.monotonic() + timeout
    for fut in futures:
        remaining = max(0.01, deadline - time.monotonic())
        fut.result(timeout=remaining)

parse_slack_interaction_payload(payload)

Parse and strictly validate a Slack block_actions interaction JSON payload.

Parameters:

Name Type Description Default
payload Mapping[str, Any]

Decoded JSON mapping extracted from Slack's payload=... callback form.

required

Returns:

Name Type Description
Validated SlackInteractionRequest

class:SlackInteractionRequest.

Raises:

Type Description
TriageError

If payload type, action ID, triage value, actor, or URL fail validation.

Source code in src/zerobom/triage/actions.py
 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
def parse_slack_interaction_payload(payload: Mapping[str, Any]) -> SlackInteractionRequest:
    """Parse and strictly validate a Slack ``block_actions`` interaction JSON payload.

    Args:
        payload: Decoded JSON mapping extracted from Slack's ``payload=...`` callback form.

    Returns:
        Validated :class:`SlackInteractionRequest`.

    Raises:
        TriageError: If payload type, action ID, triage value, actor, or URL fail validation.
    """
    if payload.get("type") != "block_actions":
        raise TriageError(f"Unsupported Slack interaction payload type: {payload.get('type')!r}.")

    actions = payload.get("actions")
    if not isinstance(actions, list) or not actions or not isinstance(actions[0], Mapping):
        raise TriageError("Slack interaction payload missing valid 'actions[0]' object.")

    first_action = actions[0]
    raw_action_id = first_action.get("action_id")
    if raw_action_id not in ("zerobom_triage_approve", "zerobom_triage_reject"):
        raise TriageError(f"Unsupported Slack triage action_id: {raw_action_id!r}.")

    triage_id = validate_triage_id(first_action.get("value"))

    raw_user = payload.get("user")
    actor = "slack-user"
    if isinstance(raw_user, Mapping):
        for key in ("username", "name", "id"):
            candidate = raw_user.get(key)
            if isinstance(candidate, str) and candidate.strip():
                cleaned = "".join(
                    ch for ch in candidate if ord(ch) >= 32 and ord(ch) != 127
                ).strip()
                if cleaned:
                    actor = cleaned[:128]
                    break

    raw_resp_url = payload.get("response_url")
    response_url: str | None = None
    if raw_resp_url is not None:
        if not isinstance(raw_resp_url, str) or any(
            ord(ch) < 32 or ord(ch) == 127 for ch in raw_resp_url
        ):
            raise TriageError("Invalid Slack interaction response_url.")
        stripped_url = raw_resp_url.strip()
        if stripped_url:
            response_url = stripped_url

    action_literal: Literal["zerobom_triage_approve", "zerobom_triage_reject"] = (
        "zerobom_triage_approve"
        if raw_action_id == "zerobom_triage_approve"
        else "zerobom_triage_reject"
    )
    return SlackInteractionRequest(
        action_id=action_literal,
        triage_id=triage_id,
        actor=actor,
        response_url=response_url,
    )

post_slack_response_url(response_url, payload, *, allowed_hosts=SLACK_WEBHOOK_HOSTS, dns_resolver=default_dns_resolver, http_client=None, timeout_seconds=10.0)

Post a Slack interactive message update to a strictly host-pinned response_url.

Raises:

Type Description
AlertDeliveryError

If response_url targets a disallowed/private host or fails.

Source code in src/zerobom/triage/server.py
 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
def post_slack_response_url(
    response_url: str,
    payload: Mapping[str, Any],
    *,
    allowed_hosts: frozenset[str] = SLACK_WEBHOOK_HOSTS,
    dns_resolver: DnsResolver = default_dns_resolver,
    http_client: httpx.Client | None = None,
    timeout_seconds: float = 10.0,
) -> int:
    """Post a Slack interactive message update to a strictly host-pinned ``response_url``.

    Raises:
        AlertDeliveryError: If ``response_url`` targets a disallowed/private host or fails.
    """
    validated_url = validate_webhook_url(
        response_url,
        allow_insecure_http=False,
        allow_private_targets=False,
        allowed_hosts=allowed_hosts,
        dns_resolver=dns_resolver,
    )
    if http_client is not None:
        return _post_json_webhook(
            http_client,
            validated_url,
            payload,
            backend_name="slack_response",
        )

    with create_pinned_httpx_client(
        timeout=timeout_seconds,
        dns_resolver=dns_resolver,
        allowed_hosts=allowed_hosts,
        on_blocked=AlertDeliveryError,
    ) as client:
        return _post_json_webhook(
            client,
            validated_url,
            payload,
            backend_name="slack_response",
        )

run_socket_mode_worker(handler, *, app_token, bot_token, allowed_response_hosts=SLACK_WEBHOOK_HOSTS, dns_resolver=default_dns_resolver)

Start an optional Slack Socket Mode listener sharing :class:TriageActionHandler.

Lazily imports slack_sdk so core zerobom retains zero mandatory Slack SDK dependencies.

Source code in src/zerobom/triage/server.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
def run_socket_mode_worker(
    handler: TriageActionHandler,
    *,
    app_token: str,
    bot_token: str,
    allowed_response_hosts: frozenset[str] = SLACK_WEBHOOK_HOSTS,
    dns_resolver: DnsResolver = default_dns_resolver,
) -> _SocketModeHandle:
    """Start an optional Slack Socket Mode listener sharing :class:`TriageActionHandler`.

    Lazily imports ``slack_sdk`` so core ``zerobom`` retains zero mandatory Slack SDK
    dependencies.
    """
    if not app_token.strip() or not bot_token.strip():
        raise TriageError("Slack Socket Mode requires both non-empty app_token and bot_token.")

    try:
        slack_web = importlib.import_module("slack_sdk.web")
        slack_sm = importlib.import_module("slack_sdk.socket_mode")
        slack_sm_resp = importlib.import_module("slack_sdk.socket_mode.response")
    except ImportError as exc:
        raise RuntimeError(
            "Socket Mode triage worker requires optional package 'slack-sdk' "
            "(pip install slack-sdk), or use default HTTP mode ('--transport http')."
        ) from exc

    web_client = slack_web.WebClient(token=bot_token)
    sm_client = slack_sm.SocketModeClient(app_token=app_token, web_client=web_client)
    stop_handle = _SocketModeHandle(sm_client)

    def _process(client: Any, req_envelope: Any) -> None:
        if getattr(req_envelope, "type", None) != "interactive":
            return
        client.send_socket_mode_response(
            slack_sm_resp.SocketModeResponse(envelope_id=req_envelope.envelope_id)
        )
        raw_payload = getattr(req_envelope, "payload", None)
        if not isinstance(raw_payload, Mapping):
            return
        try:
            interaction = parse_slack_interaction_payload(raw_payload)
        except (TriageError, ValueError):
            return

        try:
            _, slack_update = handler.execute_slack_interaction(interaction)
        except (
            TriageError,
            BackendError,
            SbomParseError,
            AlertDeliveryError,
            ValueError,
            RuntimeError,
        ):
            if interaction.response_url is not None:
                with suppress(AlertDeliveryError, ValueError):
                    post_slack_response_url(
                        interaction.response_url,
                        {
                            "response_type": "ephemeral",
                            "replace_original": False,
                            "text": f"zerobom triage action failed for {interaction.triage_id}.",
                        },
                        allowed_hosts=allowed_response_hosts,
                        dns_resolver=dns_resolver,
                    )
            return

        if interaction.response_url is not None:
            with suppress(AlertDeliveryError, ValueError):
                post_slack_response_url(
                    interaction.response_url,
                    slack_update,
                    allowed_hosts=allowed_response_hosts,
                    dns_resolver=dns_resolver,
                )

    sm_client.socket_mode_request_listeners.append(_process)
    sm_client.connect()
    return stop_handle

validate_triage_id(triage_id)

Validate an untrusted triage identifier before SQL lookup or CLI/Slack dispatch.

Source code in src/zerobom/triage/store.py
72
73
74
75
76
77
78
79
80
81
82
83
def validate_triage_id(triage_id: Any) -> str:
    """Validate an untrusted triage identifier before SQL lookup or CLI/Slack dispatch."""
    if not isinstance(triage_id, str):
        raise TriageError("Triage ID must be a string.")
    if any(ord(ch) < 32 or ord(ch) == 127 for ch in triage_id):
        raise TriageError("Triage ID must not contain control characters.")
    cleaned = triage_id.strip()
    if ".." in cleaned or not _TRIAGE_ID_RE.fullmatch(cleaned):
        raise TriageError(
            f"Invalid triage ID {triage_id!r}; expected 1-128 chars in [A-Za-z0-9._-] without '..'."
        )
    return cleaned

verify_slack_signature(body, *, timestamp_header, signature_header, signing_secret, now=None, max_skew_seconds=DEFAULT_SIGNATURE_MAX_SKEW_SECONDS)

Verify Slack X-Slack-Signature HMAC-SHA256 with replay timestamp checks.

Parameters:

Name Type Description Default
body bytes

Exact raw HTTP POST body bytes.

required
timestamp_header str | None

Value of X-Slack-Request-Timestamp.

required
signature_header str | None

Value of X-Slack-Signature (v0=<64-hex>).

required
signing_secret str

Slack App Signing Secret.

required
now int | None

Optional current UNIX timestamp override for deterministic tests.

None
max_skew_seconds int

Maximum allowed timestamp drift in seconds (default 300).

DEFAULT_SIGNATURE_MAX_SKEW_SECONDS

Returns:

Type Description
bool

True only if signature format, timestamp replay window, and HMAC match cleanly.

Source code in src/zerobom/triage/server.py
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
71
72
73
74
75
76
77
def verify_slack_signature(
    body: bytes,
    *,
    timestamp_header: str | None,
    signature_header: str | None,
    signing_secret: str,
    now: int | None = None,
    max_skew_seconds: int = DEFAULT_SIGNATURE_MAX_SKEW_SECONDS,
) -> bool:
    """Verify Slack ``X-Slack-Signature`` HMAC-SHA256 with replay timestamp checks.

    Args:
        body: Exact raw HTTP POST body bytes.
        timestamp_header: Value of ``X-Slack-Request-Timestamp``.
        signature_header: Value of ``X-Slack-Signature`` (``v0=<64-hex>``).
        signing_secret: Slack App Signing Secret.
        now: Optional current UNIX timestamp override for deterministic tests.
        max_skew_seconds: Maximum allowed timestamp drift in seconds (default ``300``).

    Returns:
        ``True`` only if signature format, timestamp replay window, and HMAC match cleanly.
    """
    if not signing_secret or not timestamp_header or not signature_header:
        return False

    ts_str = timestamp_header.strip()
    sig_str = signature_header.strip().lower()
    if not ts_str.isdigit() or not _SLACK_SIG_RE.fullmatch(sig_str):
        return False

    req_ts = int(ts_str)
    current_ts = int(time.time()) if now is None else now
    if abs(current_ts - req_ts) > max_skew_seconds:
        return False

    base_string = f"v0:{ts_str}:".encode("ascii") + body
    expected_digest = hmac.new(
        signing_secret.encode("utf-8"),
        base_string,
        hashlib.sha256,
    ).hexdigest()
    expected_sig = f"v0={expected_digest}"
    return hmac.compare_digest(expected_sig, sig_str)