From ab9fa03040185e2bf4df74d26f184de635f6e9c3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:43:44 -0600 Subject: [PATCH 1/7] Approval gate audits a request its Vault transit Outage leaves unchecked Rebuild under the Lander's rebuild terms for vault BACKLOG #8202, items 145, 146 and 153. - Item 146: ApprovalGate._approval_seal_outage now writes a best-effort approval.seal_check_unavailable row (actor system, throttled per request, its lost-row page keyed approval::seal-check) beside its page. ADR 0217 records gap (3) as narrowed, not closed, and says why. - Item 145: the Outage page, WARNING and 503 text no longer say the request was refused, that nothing was done, or that Vault did not answer. - Item 153: the 503's Retry-After uses the shared TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS; the local duplicate is gone. Docs: ADR 0217 corrections, SECURITY.md, the audit_write_failed key lists in alerts.py and PHI.md, and a changelog.d fragment. Proposed PR title: Approval gate audits a request its Vault transit Outage leaves unchecked (rebuild, vault BACKLOG #8202 items 145, 146, 153) Ledger banner text: #8202 PARTIAL - items 145, 146 and 153 built by this rebuild; every other item stays open. Verified-by: tests --- .../8202-approval-seal-outage-row.security.md | 6 + docs/PHI.md | 2 +- docs/SECURITY.md | 18 +- ...ciler-ends-sessions-rather-than-holding.md | 25 ++- messagefoundry/api/approvals.py | 64 ++++++-- messagefoundry/pipeline/alerts.py | 3 +- tests/test_transit_approval_gate.py | 155 +++++++++++++++++- 7 files changed, 250 insertions(+), 23 deletions(-) create mode 100644 changelog.d/8202-approval-seal-outage-row.security.md diff --git a/changelog.d/8202-approval-seal-outage-row.security.md b/changelog.d/8202-approval-seal-outage-row.security.md new file mode 100644 index 0000000000..46e681e786 --- /dev/null +++ b/changelog.d/8202-approval-seal-outage-row.security.md @@ -0,0 +1,6 @@ +- **An approval request whose seal Vault transit cannot check now writes an audit row.** Under + `[store].cipher_provider = "vault_transit"`, the approval gate's 503 on a Transit Outage at a + request's seal check also writes a best-effort, throttled `approval.seal_check_unavailable` row; + before, it only paged. The row names the request, not who was refused. Its page, log line and + 503 text no longer say the request was refused, that nothing was done, or that Vault did not + answer. (`BACKLOG #8202`) diff --git a/docs/PHI.md b/docs/PHI.md index 347a11dde8..6523036bd3 100644 --- a/docs/PHI.md +++ b/docs/PHI.md @@ -2386,7 +2386,7 @@ with materially different PHI profiles, so they get their own rows; stream 4 is | **5. `audit_log` table** (SQLite, Postgres, SQL Server) | who / what / **where-from** / when of auth + PHI *access* and admin actions — plus, while `[security].audit_all_authorization_decisions` is on (**default `true`** since BACKLOG #1277, 2026-09-02, which reversed the ADR 0118 §5 `false`; the internal field it desugars to is `audit_all_authz`, whose old `[diagnostics]` TOML spelling is **refused at load** — ADR 0118), an `authz` row for **every** authorization decision including successes. That is the shipped volume of this stream, not an opt-in addition to it: one row per authenticated request on each `require()`-gated route, and this row's retention cell records that **nothing prunes the table** — `actor`, `action`, `channel_id`, `client`, `detail`, `row_hash` | JSON `detail`; **tamper-evident hash chain** over `prev_hash` + the row (the `client` address is **inside** the chained payload — ADR 0150) | the store database | HIPAA §164.312(b) audit controls; incident response; `verify_audit_chain` integrity checks | `GET /audit` requires **`audit:read`**; `GET /audit/export` requires the separate **`audit:export`** and streams CSV with formula-injection neutralisation, recording its own `audit.export` row *before* streaming; `GET /me/security-events` is a per-user view of the same table | **`[retention].audit_days` is reserved and NOT enforced — keep-forever by design** (the audit-retention requirement, ~6 years — **not** chain-breakage; [§8](#8-retention--purge) states the position and cites its source of record) | `detail` is stored **in the clear** (it is not a cipher-covered column): its protection is that writers store at least filter shapes, counts, ids, keyed digests, bounded engine-authored text and client addresses, the `audit_log.detail` row above says which — never bodies or credentials — plus the store ACL and the volume layer. *Corrected 2026-10-16 (vault BACKLOG #3145):* this said writers "only ever store filter shapes, counts and ids" | | **6. `message_events` table** | the per-message disposition timeline — the **complete** vocabulary is `received`, `routed`, `unrouted`, `filtered`, `transformed`, `delivered`, `failed`, `dead`, `error`, `replayed`, `resent`, `reingressed`, `passthrough`, `passthrough_dropped`, `cancelled`, `edit_resend`, `edit_resubmit`, `viewed`, `not_deployed`, the ADR 0154 synchronous-reply pair `reply_returned` / `reply_timeout` (names, counts and `waited_ms` only — **never** a fragment of the partner's reply body), and `reply_dropped`, a delivery whose 2xx reply body was over the byte bound and dropped (the status and the bound only, vault BACKLOG #3040) (CI asserts this list against the engine's own `MESSAGE_EVENT_KINDS`). `[diagnostics].message_events` can thin the set, but never below the compliance floor `viewed` / `dead` / `error` / `failed` / `not_deployed` / `reply_timeout` / `reply_dropped` | rows: `message_id`, `ts`, `event`, `destination`, `detail` | the store database | operator timeline on the message-detail view; the `viewed` row is the HIPAA PHI-access record | `GET /messages/{id}` under **`messages:view_raw`** + `require_phi_read`; the read itself writes a `viewed` event **and** a `message_view` audit row | no dedicated window — `purge_message_bodies` sets `message_events.detail` to `NULL` in the same transaction that blanks the body, so it inherits `[retention].messages_days` | `detail` is `safe_text()`-scrubbed **then** cipher-encrypted (AAD `("message_events","detail",message_id,ts,event)`). Verbosity gate `[diagnostics].message_events` = `all` (default) / `errors` / `off`, with a **compliance floor that can never be thinned**: `viewed`, `dead`, `error`, `failed`, `not_deployed`, `reply_timeout`, `reply_dropped` are retained at every level (`reply_timeout` is the one row that explains a "we called you and got a 504" complaint, so an instance that thinned its logs would lose exactly the record it is later asked for; `reply_dropped` is the one row that answers "you ignored our reply", for the same reason) | | **7. `connection_event` table — DEFAULT ON** (`[diagnostics].connection_events = true`) | transport/lifecycle events per connection: `established`, `closed` (reason `eof`, `idle_timeout` or `frame_deadline` — a fixed vocabulary chosen by the listener, never free text), `idle_timeout`, `at_capacity`, `peer_not_allowlisted`, `frame_oversize`, `framing_error`, `peer_reset`, the MLLP, raw-TCP, X12 and HTTP listeners' and the DATABASE poll source's `handler_error` (BACKLOG #1619, #5022, #5680 for the HTTP listener, which answers it `503` or `500` by the exception's type, as [CONNECTIONS.md Table B](CONNECTIONS.md#table-b--per-service-resource-strategy-asvs-1313) states -- the inbound handler faulted on a frame the listener read cleanly, such as a failed ingress commit; on the X12 listener also, BACKLOG #5971, the engine's own reply to an interchange already recorded could not be encoded in the inbound's charset, so it was not sent; on the DATABASE source, BACKLOG #4921, on a polled row, which is left unmarked and, when the source has a mark statement, stops that poll; the reason is scrubbed at the source like every other), the MLLP, raw-TCP and X12 listeners' `reply_replaced` (BACKLOG #5799 -- the engine's own reply held characters the inbound's charset cannot encode, and each was replaced before the reply was written to the connection; throttled per listener: the first such reply sends one at once, then at most one a minute, sent by the first such reply past the minute and carrying the count of such replies since the last one, with no trailing report, so replies counted after the last event are not reported if no later one comes; an event is sent whether or not the write then succeeds, while the WARNING log line is written once per connection per process; a frame byte turned into a space writes no event; the reason is a count and fixed text that names neither the charset setting nor any part of the reply), the MLLP and HTTP listeners' `tls_handshake_failed` (vault BACKLOG #2613, #3302 and #3785 -- an inbound TLS handshake failed, on any event loop. **This is the one statement of the failed-handshake throttle, and other pages link here.** The first failure is reported at once, then at most one report per listener per minute, carrying the count since the last report. The reason is a count, an exception class name and OpenSSL's reason mnemonic, never the peer's bytes or certificate. A report names a peer only for a single failure, and only where the listener runs its own handshakes or awaits each one's outcome itself, which the MLLP and HTTP listeners do on every loop (BACKLOG #1606, #2479) and the DICOM C-STORE SCP always does. Such a listener also counts a handshake that runs past its bound. Where only the loop sees them, which is at least the API listener on every loop, the report names no peer, since the loop's hook does not read it (the module docstring of `messagefoundry/tls_handshake_failures.py` says what was measured), and a handshake that only runs past its bound is not counted. A peer that closes or resets the socket mid-handshake is not counted anywhere. That is what a load balancer's TCP health check does. The past-bound and hang-up limits stand by owner ruling 2026-10-26 (vault BACKLOG #3785 items 7 and 8), and that ruling covers only those two. Whether the API's report should name the peer is still an open owner question (vault BACKLOG #3302). The item 8 decline keeps the hang-up counting that came before #3785 and adds none. So a close_notify after the ClientHello is still counted, and the DICOM C-STORE SCP counts it too. A handshake that the listener's own stop ends is not counted. At least every listener also drops a genuine failure that lands once its stop has begun. The DICOM C-STORE SCP drops them for the whole of its server shutdown. On the MLLP and HTTP listeners, a stop that is cancelled before it finishes loses the failures its trailing report still held. The DICOM C-STORE SCP still reports them when its server shutdown raises or is cancelled. The API listener and the DICOM C-STORE SCP write the same report, throttled the same way, as a WARNING log line rather than an event: the API has no connection to carry one, and the SCP emits none (vault BACKLOG #3784)), the DATABASE poll source's `row_undecodable` (BACKLOG #1662 — a polled row the source cannot turn into a body; the reason is scrubbed at the source and names the exception type or the operator's own configured column, never a row value), the FILE poll source's quarantine kinds `file_oversize` / `file_decompress_failed` / `file_content_mismatch` / `file_scan_rejected` (BACKLOG #1621 — a drop moved to `.error`; the reason is a size, a content type or a codec or scanner message, and **that message can still name the file**. The name scrub on both the FILE and REMOTEFILE sources is `safe_exc(exc, file_name=...)`. safe_exc replaces the file name and, at least, its repr, ascii, bytes-repr and JSON-escaped forms, each also with uppercase hex digits. A scanner's `ScanRejected` message that quotes the name in at least another case, without its extension, percent-encoded, in another Unicode normalization, or escaped in a spelling those forms do not produce, such as a JSON escape of a decomposed spelling, keeps that text in the reason (`tests/test_file_source_quarantine_events.py` and `tests/test_remotefile_source_quarantine_events.py` pin this on each source's scan-reject arm), so a scan hook should leave the name out of its message. The directory part of a path stays, so a subdirectory a partner made under a recursive FILE source can appear in the reason; the REMOTEFILE poll source records the same kinds except `file_decompress_failed`, since it does not decompress), the inbound-HTTP intake-auth refusals `intake_auth_failed` / `auth_subject_denied` / `auth_rate_limited` (ADR 0154 D6 — peer address and mode only, plus, behind a proxy the connection lists in its trusted_proxies setting, the forwarded client address as a forwarded_for suffix on the reason and the audit detail (BACKLOG #5525); **never** the credential, a prefix of it, or its length. Each of these also writes a tamper-evident audit-log row — the copy that survives an operator turning this diagnostics stream off. The MLLP listener writes `auth_subject_denied` and `auth_rate_limited` too, with the same audit rows, when its expected-sender allowlist refuses a sender, naming the peer address and never a certificate field; BACKLOG #4907), plus the runner's `connection_lost` / `connection_restored` / `config_fault`. That is the whole vocabulary, asserted in CI against the literal emit call sites in `transports/` and the pipeline runner **and** against `CONNECTION_EVENT_KINDS` (`messagefoundry/connection_events.py`), the one set the store enforces on write and the console's filter reads (BACKLOG #1624). The MLLP, raw-TCP, X12 and HTTP listeners emit these; the **DATABASE poll source** emits `row_undecodable` and `handler_error` and nothing else (it dials out, so there is no lifecycle to report and its rows carry a **NULL peer column**); the **FILE poll source** emits only its four quarantine kinds, and the **REMOTEFILE poll source** only three of them, both with a NULL peer column; the **DICOM inbound C-STORE SCP** emits none — the runner injects the sink onto **every** source (`wiring_runner.py`, over the base-class `on_connection_event` field), so that connector *has* the wiring and simply never calls it — so this stream covers those four listeners plus those poll-source events and the runner's outbound-lane transitions — not literally every connection. A DICOM association's connects and refusals are therefore **absent** from this stream. The **`ISA`/`IEA`-framed X12 inbound** was equally absent until BACKLOG #1665 and is not any more: it emits the same kinds as the raw-TCP listener | rows: `ts`, `connection`, `transport`, `direction`, `kind`, `peer_host`, `message_id` (correlation hint), `reason` | the store database, **all three backends** | Corepoint-style transport diagnostics — "did the sender connect, and why did it drop" | `GET /events` and `GET /connections/{name}/events` under **`monitoring:read`** (**not** a PHI permission) with per-channel RBAC — an out-of-scope `connection=` is 403'd *and* audited — server-clamped to ≤1000 rows. `reason` alone is gated on `messages:view_summary` and masked as `****` until the audited per-event `reveal=` act (BACKLOG #2443; the `connection_event.reason` row of §3's PL-2 block says how) | `[retention].connection_event_retention_hours` (its own **hours** window); 0 inherits `[retention].messages_days`; both 0 = keep forever. Plain age `DELETE` | **`reason` is free text that can carry sensitive fragments.** Defended twice — `safe_exc()` at the source, `safe_text(reason, limit=200)` at the store (the bound §3's PL-2 block states) — then cipher-encrypted (AAD `("connection_event","reason",connection,ts,kind)`). Every other column is engine or config metadata except `peer_host`, and `reason` is not metadata-only: the [data-at-rest inventory](#2-where-phi-lives--data-at-rest-inventory) grades `reason` and `peer_host` in rows of their own (BACKLOG #5021). Writes are a pure side observer: a bounded in-memory queue drained by a background task outside any handoff transaction, so a flood can never block a listener or pin a message disposition | -| **8. `alert_instance` table — default on wherever an `[alerts]` notifier exists** | resolvable operator alerts: `connection_stopped`, `queue_buildup`, `lane_stuck`, `message_stall`, `saturation`, `connection_error`, `connection_error.config_fault`, `storage_threshold`, `cert_expiry`, `secret_rotation`, `initial_credential_expiring` (an UNCLAIMED admin-issued temporary password nearing the instant the login gate stops accepting it -- ASVS 6.4.5, BACKLOG #1141; keyed on `user:`, and the payload is the ISO deadline plus whole hours remaining, repeated in the reason column, never the password), `integrity_drift`, `update_available`, `backup_failed`, `store_privilege_warning` (the store privilege preflight found the store principal over-granted or could not read it -- BACKLOG #305; the payload is the finding, a count and the preflight's summary line, which names the login, the database and role names, never a password or message content), `vault_privilege_warning` (the Vault privilege preflight found a Vault token over-granted or could not read it -- BACKLOG #2903, ADR 0216; keyed on `vault:store` or `vault:secrets`, and the payload is the finding, a count of refusing-class grants and the hop's judgment, which names policy names, paths and capabilities, never a token, an accessor, a digest of either or message content), `leadership_acquired`, `dr_activated`, `dr_restarted_passive` (a DR box last recorded as activated came back up passive after a restart -- BACKLOG #5965; also raised when the start could not read whether the box was activated; keyed on the box's host label, with the engine shard appended on an engine shard, and the payload is that label, never message content), `log_write_failed` (an application-log sink was rolled after a write failure, or is UNWRITABLE and this process's connections were stopped -- BACKLOG #122, ADR 0162; the payload is the sink LABEL, the stage, a `safe_exc` reason and a count of connections stopped, never the record whose write failed), `log_forward_failed` (the off-box log forwarder is absent, losing records or not sending -- BACKLOG #2612; keyed on `forwarder:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, fixed reason words and a count, never a record, the collector's address or an error text; an unpinned cluster node's `node_id` holds this engine's own host name and process id, so the key carries them), `gcm_invocations` (the per-key AES-GCM invocation bound crossing its 2^31 soft warn — ASVS 11.3.4; its payload carries a one-way `key_id` fingerprint plus counters, never key bytes), `approval_stale_requester` (a dual-control release refused because the requester no longer holds the authority the operation needs -- ASVS 8.3.2, BACKLOG #289; keyed on the approval id, and the payload is that id, the operation key and a closed-set reason slug, never the requester's name or the captured params), `approval_too_early` (a dual-control release refused because it arrived before `[approvals].min_dwell_seconds` -- ASVS 2.4.2, BACKLOG #287; keyed on `approval:`, and the payload is that key, the operation key and a fixed reason string, never the approver's or requester's name or the captured params), `audit_write_failed` (the approval gate could not write one of its audit rows -- vault BACKLOG #2255; keyed on `approval:`, on `approval::resolve` for a resolution's lost provenance row -- vault BACKLOG #3438, on the fixed `approval:listing` for a queue listing's lost `approval.standing_shown` row -- vault BACKLOG #3747, on `config_reload:inline` when an ungated config reload could not write its `config_reload_attempted` row -- vault BACKLOG #2254, or on `step_up_return:audit_budget:` when the IdP step-up return audit budget's backstop stopped a row -- BACKLOG #3965, its rules stated once as control 11 of [SECURITY.md](SECURITY.md#the-documented-protection-set-asvs-611)'s 6.1.1 protection set, or on `directory-reconciler:` when a directory reconcile pass that completed could not write a row -- BACKLOG #3018 step 2, or on `directory-sign-in:` when a directory sign-in's role-sync row was refused twice -- BACKLOG #2221; the payload is that key and the lost row's audit action name, never the row's detail, a username or the captured params; the ERROR log line beside it holds the detail on some paths and only the exception on others), `audit_offbox_copy_missing` (an approval audit row whose write the gate read back as committed, whose off-box copy was never sent -- vault BACKLOG #3193; keyed on `approval:`, and the payload is that key and the row's audit action name, never the row's detail, a username or the captured params), `ad_reconcile_aborted` (a directory reconciler pass left signed-in accounts unrevoked and needs an operator: the mass-revoke breaker tripped and nothing was revoked, or one or more probes were answered with an LDAP referral and those accounts were left unjudged while the rest of the pass was applied, BACKLOG #2538, or one or more probes raised a fault the engine could not read and those accounts were left unjudged the same way, BACKLOG #3100, or the directory refused one or more probes with a result code that points at the configuration, such as a deleted search base, and those accounts were left unjudged the same way, vault BACKLOG #3010, or an account's group search was refused for the engine's own deadline or cap, so a role or scope change in the directory does not revoke that account's sessions, though a disable or deletion still does, vault BACKLOG #3696, or every lookup failed to reach the directory for `[auth].ad_reconcile_outage_passes` passes running, BACKLOG #3709; for the breaker, a referral, a probe fault, a configuration refusal and a lasting outage the payload is a fixed source label, `directory-reconciler` for the breaker, `directory-reconciler-referral` for a referral, `directory-reconciler-probe-fault` for a probe fault, `directory-reconciler-misconfigured` for a configuration refusal and `directory-reconciler-outage` for a lasting outage so each is its own instance, the closed-set reason slug `mass_revoke_breaker`, `directory_referral`, `probe_fault`, `directory_misconfigured` or `directory_unavailable`, a count (the accounts the breaker judged, or for each of the other four the lookups the pass sent, which leaves out an id-less row -- vault BACKLOG #3170) and the latched operator explanation, or for a lasting outage a fixed sentence with the run's length, never a username; a paging refusal is instead keyed on that operator account's username, as `directory-reconciler-paging:`, so each account is its own instance, raised as the account enters that state and again after a restart while it stands, and the payload is that key, the closed-set reason slug `group_search_deadline` or `group_search_cap`, the same count as the breaker's and a fixed sentence naming the cause, never anything else about the account; an account the directory keeps failing to answer for is keyed the same way, as `directory-reconciler-unreached:`, raised as it enters that state, and its payload is that key, the closed-set reason slug `account_unreachable`, the count of lookups the pass sent and a fixed sentence with two numbers, how many probes failed and the most recent probes its window can hold (faults aside), never anything else about the account -- vault BACKLOG #3100, #3709; on a rolled-up pass, those entering page as one instance under the source `directory-reconciler-unreached-rollup:`, with no username. The key is an unkeyed SHA-256 prefix of the entering accounts' sorted internal user ids, not a pseudonym: anyone who can list user ids can recompute it for a set of accounts and so learn which accounts a rollup covers (vault BACKLOG #3100 item 14), and the `ad_reconcile_outage_passes` row of [CONFIGURATION.md](CONFIGURATION.md) states when), `ad_reconcile_held` (the reconciler is holding accounts whose `userAccountControl` it cannot read, ADR 0195; the payload is the same fixed source label, a closed-set reason slug, the count of undetermined accounts and the latched operator explanation, never a username), `ad_session_revoked` (the reconciler revoked a directory principal's sessions; keyed on that operator account's username, with at least a `directory_absent`, `directory_disabled`, `directory_undetermined`, `directory_object_id_missing`, `roles_changed` or `scope_changed` reason), `approval_approver_provenance` (a dual-control release, or the resolution of an interrupted one, went ahead with an approver or resolver account created, re-passworded or TOTP-enrolled after the request -- BACKLOG #315, #2125; keyed on `approval:`, or `approval::resolve` for a resolution, and the payload is the operation key and the closed-set change slugs, never a username or the captured params), `administrator_granted` (the built-in Administrator role was granted by account creation, a role change, a directory group newly mapped to it -- BACKLOG #315 --, a directory sign-in whose role sync newly gave the account the role -- vault BACKLOG #2610 -- or a directory reconcile pass whose role re-diff did -- vault BACKLOG #3141; keyed on `user:` or `ad-group:`, with the grant route and the granting administrator's username, or `` for a directory sign-in or reconcile pass), `no_enabled_administrator` (a directory sign-in's role sync or the session reconciler took Administrator from its last enabled holder -- vault BACKLOG #3229; keyed on `user:`, and the payload is `via`, `ad-sync` or `ad-reconcile`, and a fixed reason sentence, never message content), `intake_paused` (the engine paused intake because the staged backlog went over `[inbound].max_staged_depth` or the SQLite volume fell below `[retention].min_free_disk_mb` -- BACKLOG #290; keyed on `intake:staged_depth` or `intake:disk_floor`, with `@node:` or `@shard:` appended when several engine processes share the store (BACKLOG #2272), and the payload is the reason, a count or a MiB figure, its limit and the store backend's name, never message content), `config_changed` (a start's config differs from the store's baseline: the bytes it loaded, or the directory just after the load -- vault BACKLOG #2597, #3765; keyed on `config:`, and the payload is the two digests, the node and engine shard labels, the action, actor username, time and node of the row the older digest came from, and the `comparison` outcome, never the config directory, a git commit or message content), `crl_reload_refused` (the CRL reload refused a replaced CRL file, so running TLS contexts keep the copy they hold -- vault BACKLOG #2904; keyed on `crl_reload:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the file's path, a short class token for the remedy, a count of contexts, the engine's own fixed remedy sentence and, when a start would refuse the file too, a `start_refuses` flag, never the refusal's reason, which quotes CRL issuer names and dates; that reason is in the application log, and in the `detail` of the CRL expiry alert once the held copy nears its `nextUpdate`), `remote_debug_refused` (the engine's remote-debugging guard refused scripts that another process injected into the engine process -- vault BACKLOG #2742; keyed on `remote_debug:refused`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the count of scripts refused since the alert was last raised, the count since the process started and a fixed sentence built from the two, never a script's file name, which the injecting process chooses; that name is in the application log, in the guard's WARNING line), `sandbox_worker_refused` (a `[sandbox].mode = "subprocess"` worker was refused because the graph it loaded differs from the engine's, most often a config file edited on disk with no reload -- vault BACKLOG #2724; keyed on the inbound's name, raised once per refusal, and the payload is that name and a fixed sentence naming the cause and the remedy, never a message body or the refusal text, which names config names and digests and is in the application log), `cert_monitor_stalled` (a cert-expiry scan pass ran past its stall threshold, most likely on a blocked certificate or CRL read, so no expiry alert is raised until it returns -- vault BACKLOG #5885; keyed on `cert_monitor:scan`, raised once the pass runs past the threshold and again each threshold while it runs, and the payload holds at least that key, the seconds the pass has run and a fixed sentence built from them, never a file's path), `store_restored` (the first `serve` on a store `messagefoundry restore` placed ended every session -- BACKLOG #2614; keyed on `store:restored`, raised once per restore, and the payload is that key; a fixed sentence carrying the archive's age in days, the count of sessions ended, a pointer to `messagefoundry restore --help` and the time of the archive's newest audit row, of which the alert instance's reason column keeps the age, the count and the pointer whole and the time redacted or cut; that time again as `last_audit_at`; and the fixed notice of what a restore rolls back as `rollback_notice` (`messagefoundry/restore_notice.py`, BACKLOG #5094), fixed text the reason column never holds; never an account name or a row's content), and the seven security signals of the audit-stream rule layer -- vault BACKLOG #2613: `signin_failure_burst` (keyed on `signin:`, never the typed username), `access_denied_burst`, `body_view_burst` and `bulk_export` (each keyed on `account:`), `peer_refused_burst` (keyed on `inbound:`, never the refused peer's address), `log_level_debug` (keyed on `logging:debug`) and `posture_loosened` (keyed on `posture:start`, with `@node:` or `@shard:` appended when several engine processes share the store); the payload is a count and a fixed sentence holding a level name, switch names or a username, never a message body, a message id or an audit row's detail. The reachable **inverse** signals — `connection_restored`, `leadership_lost`, `dr_released`, `dr_restart_cleared` (raised by each `dr_activated` and `dr_released`, so an activation, or a release that leaves a restarted box passive, resolves the open `dr_restarted_passive` for the same box label -- BACKLOG #5965), `store_privilege_clean`, `vault_privilege_clean`, `intake_resumed`, `posture_restored` (it resolves `posture_loosened` under the same key, so for the same engine process, when a start records no security loosening in a row marked neither `superseded` nor `baseline_unchecked` and a live posture read then names none -- vault BACKLOG #2613; an unpinned cluster node's key changes on every start, so that node raises the inverse for its own instance as it shuts down; when that instance can still stay open is in [SECURITY.md](SECURITY.md)), `crl_reload_applied` (it resolves `crl_reload_refused` under the same key, so for the same file and the same engine identity, at least once the reload's record no longer holds the refusal, once no hop holds any CRL, and when the reload stops -- vault BACKLOG #2904; it is also raised once per held file outside a CA bundle, at the first pass that judges it with no refusal standing, whether or not an alert is open, so it can resolve nothing, and it then clears one an earlier run under that identity left open -- vault BACKLOG #3543. An alert for a file no hop holds now stays open, and so does one an unpinned cluster node raised, because that node's identity changes on every start; [CONFIGURATION.md](CONFIGURATION.md), *The alert resolves itself*, is the source of record), `ad_reconcile_breaker_cleared`, `ad_reconcile_hold_released` (the last two resolve `ad_reconcile_held` and `ad_reconcile_aborted`, the latter only under the breaker's, the referral's or the lasting outage's source: the probe fault's, the configuration refusal's, a paging refusal's and an unreached account's instances have no inverse; when they do, and where they never do, is stated once in [CONFIGURATION.md](CONFIGURATION.md#when-the-reconcilers-alerts-resolve-themselves) -- BACKLOG #2136) — are never rows here: `_record_state` routes an inverse through `_AUTO_RESOLVE` to `resolve_alert_instances_fenced` (BACKLOG #4916), or `resolve_alert_instances_for` on a store without the fence methods, never to `upsert_alert_instance`. So is `connection_started`, which resolves `connection_stopped` under the bare connection name: the runner raises it only when an operator's start or restart finds an inbound up and no cause it can see still holds the name down in either direction (BACKLOG #1741). Every other start raises nothing, at least an engine start, a committed reload, the scheduler and every alert rule's restart, so an open stop keeps its instance, ack and suspend across them. `AlertSink.connection_started` states the full contract, including the operator starts that still raise nothing. An instance raised under a prefixed stand-in such as `reference:` is never resolved by it. | rows: `event_type`, `connection`, `severity`, `status`, `first_seen`, `last_seen`, `count`, `reason`, `acked_by`, `acked_at`, `resolved_at`, `suspended_until`, `escalation_tier`, `raised_by` (a random per-process id naming the newest raise's writer, BACKLOG #4916; never a host, user or message value) | the store database, **all three backends** | the operator alert list — acknowledge / resolve / suspend. Durable state is recorded **before** any suppression or throttle return, so a muted alert still leaves a record | `GET /alerts/active` under **`monitoring:diagnose`** (**not** a PHI permission) with the same per-channel scope, and `reason` alone gated on `messages:view_summary` and masked as `****` until the audited per-alert `reveal=` act (BACKLOG #2443; the `alert_instance.reason` row of §3's PL-2 block says how); ack/resolve/suspend/**resume** are POSTs on the same tier, and the separate read-only `GET /alerts/rules` view sits on its own gate | shares the connection-event window; **only RESOLVED instances are DELETEd**, by `resolved_at` — retention never ages out an open or acknowledged condition from under an operator; a row can still close with no inverse and no operator, at least through the `intake_paused` staleness sweep (BACKLOG #3269), which resolves another engine process's open or acknowledged pause under the expiry rule in [CONFIGURATION.md](CONFIGURATION.md#alerts), after which retention treats it as any resolved row | **`reason` is free text** taken from the event's internal `_detail` (the `connection_error` reason kept off the wire, BACKLOG #5021), `detail` or `reason`: `safe_text(reason, limit=200)` (the bound §3's PL-2 block states) then cipher-encrypted (AAD `("alert_instance","reason",event_type,connection)` — the de-dup grain, so one AAD covers both the INSERT and the re-fire UPDATE). | +| **8. `alert_instance` table — default on wherever an `[alerts]` notifier exists** | resolvable operator alerts: `connection_stopped`, `queue_buildup`, `lane_stuck`, `message_stall`, `saturation`, `connection_error`, `connection_error.config_fault`, `storage_threshold`, `cert_expiry`, `secret_rotation`, `initial_credential_expiring` (an UNCLAIMED admin-issued temporary password nearing the instant the login gate stops accepting it -- ASVS 6.4.5, BACKLOG #1141; keyed on `user:`, and the payload is the ISO deadline plus whole hours remaining, repeated in the reason column, never the password), `integrity_drift`, `update_available`, `backup_failed`, `store_privilege_warning` (the store privilege preflight found the store principal over-granted or could not read it -- BACKLOG #305; the payload is the finding, a count and the preflight's summary line, which names the login, the database and role names, never a password or message content), `vault_privilege_warning` (the Vault privilege preflight found a Vault token over-granted or could not read it -- BACKLOG #2903, ADR 0216; keyed on `vault:store` or `vault:secrets`, and the payload is the finding, a count of refusing-class grants and the hop's judgment, which names policy names, paths and capabilities, never a token, an accessor, a digest of either or message content), `leadership_acquired`, `dr_activated`, `dr_restarted_passive` (a DR box last recorded as activated came back up passive after a restart -- BACKLOG #5965; also raised when the start could not read whether the box was activated; keyed on the box's host label, with the engine shard appended on an engine shard, and the payload is that label, never message content), `log_write_failed` (an application-log sink was rolled after a write failure, or is UNWRITABLE and this process's connections were stopped -- BACKLOG #122, ADR 0162; the payload is the sink LABEL, the stage, a `safe_exc` reason and a count of connections stopped, never the record whose write failed), `log_forward_failed` (the off-box log forwarder is absent, losing records or not sending -- BACKLOG #2612; keyed on `forwarder:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, fixed reason words and a count, never a record, the collector's address or an error text; an unpinned cluster node's `node_id` holds this engine's own host name and process id, so the key carries them), `gcm_invocations` (the per-key AES-GCM invocation bound crossing its 2^31 soft warn — ASVS 11.3.4; its payload carries a one-way `key_id` fingerprint plus counters, never key bytes), `approval_stale_requester` (a dual-control release refused because the requester no longer holds the authority the operation needs -- ASVS 8.3.2, BACKLOG #289; keyed on the approval id, and the payload is that id, the operation key and a closed-set reason slug, never the requester's name or the captured params), `approval_too_early` (a dual-control release refused because it arrived before `[approvals].min_dwell_seconds` -- ASVS 2.4.2, BACKLOG #287; keyed on `approval:`, and the payload is that key, the operation key and a fixed reason string, never the approver's or requester's name or the captured params), `audit_write_failed` (the approval gate could not write one of its audit rows -- vault BACKLOG #2255; keyed on `approval:`, on `approval::resolve` for a resolution's lost provenance row -- vault BACKLOG #3438, on the fixed `approval:listing` for a queue listing's lost `approval.standing_shown` row -- vault BACKLOG #3747, on `approval::seal-check` for a lost `approval.seal_check_unavailable` row -- vault BACKLOG #8202, on `config_reload:inline` when an ungated config reload could not write its `config_reload_attempted` row -- vault BACKLOG #2254, or on `step_up_return:audit_budget:` when the IdP step-up return audit budget's backstop stopped a row -- BACKLOG #3965, its rules stated once as control 11 of [SECURITY.md](SECURITY.md#the-documented-protection-set-asvs-611)'s 6.1.1 protection set, or on `directory-reconciler:` when a directory reconcile pass that completed could not write a row -- BACKLOG #3018 step 2, or on `directory-sign-in:` when a directory sign-in's role-sync row was refused twice -- BACKLOG #2221; the payload is that key and the lost row's audit action name, never the row's detail, a username or the captured params; the ERROR log line beside it holds the detail on some paths and only the exception on others), `audit_offbox_copy_missing` (an approval audit row whose write the gate read back as committed, whose off-box copy was never sent -- vault BACKLOG #3193; keyed on `approval:`, and the payload is that key and the row's audit action name, never the row's detail, a username or the captured params), `ad_reconcile_aborted` (a directory reconciler pass left signed-in accounts unrevoked and needs an operator: the mass-revoke breaker tripped and nothing was revoked, or one or more probes were answered with an LDAP referral and those accounts were left unjudged while the rest of the pass was applied, BACKLOG #2538, or one or more probes raised a fault the engine could not read and those accounts were left unjudged the same way, BACKLOG #3100, or the directory refused one or more probes with a result code that points at the configuration, such as a deleted search base, and those accounts were left unjudged the same way, vault BACKLOG #3010, or an account's group search was refused for the engine's own deadline or cap, so a role or scope change in the directory does not revoke that account's sessions, though a disable or deletion still does, vault BACKLOG #3696, or every lookup failed to reach the directory for `[auth].ad_reconcile_outage_passes` passes running, BACKLOG #3709; for the breaker, a referral, a probe fault, a configuration refusal and a lasting outage the payload is a fixed source label, `directory-reconciler` for the breaker, `directory-reconciler-referral` for a referral, `directory-reconciler-probe-fault` for a probe fault, `directory-reconciler-misconfigured` for a configuration refusal and `directory-reconciler-outage` for a lasting outage so each is its own instance, the closed-set reason slug `mass_revoke_breaker`, `directory_referral`, `probe_fault`, `directory_misconfigured` or `directory_unavailable`, a count (the accounts the breaker judged, or for each of the other four the lookups the pass sent, which leaves out an id-less row -- vault BACKLOG #3170) and the latched operator explanation, or for a lasting outage a fixed sentence with the run's length, never a username; a paging refusal is instead keyed on that operator account's username, as `directory-reconciler-paging:`, so each account is its own instance, raised as the account enters that state and again after a restart while it stands, and the payload is that key, the closed-set reason slug `group_search_deadline` or `group_search_cap`, the same count as the breaker's and a fixed sentence naming the cause, never anything else about the account; an account the directory keeps failing to answer for is keyed the same way, as `directory-reconciler-unreached:`, raised as it enters that state, and its payload is that key, the closed-set reason slug `account_unreachable`, the count of lookups the pass sent and a fixed sentence with two numbers, how many probes failed and the most recent probes its window can hold (faults aside), never anything else about the account -- vault BACKLOG #3100, #3709; on a rolled-up pass, those entering page as one instance under the source `directory-reconciler-unreached-rollup:`, with no username. The key is an unkeyed SHA-256 prefix of the entering accounts' sorted internal user ids, not a pseudonym: anyone who can list user ids can recompute it for a set of accounts and so learn which accounts a rollup covers (vault BACKLOG #3100 item 14), and the `ad_reconcile_outage_passes` row of [CONFIGURATION.md](CONFIGURATION.md) states when), `ad_reconcile_held` (the reconciler is holding accounts whose `userAccountControl` it cannot read, ADR 0195; the payload is the same fixed source label, a closed-set reason slug, the count of undetermined accounts and the latched operator explanation, never a username), `ad_session_revoked` (the reconciler revoked a directory principal's sessions; keyed on that operator account's username, with at least a `directory_absent`, `directory_disabled`, `directory_undetermined`, `directory_object_id_missing`, `roles_changed` or `scope_changed` reason), `approval_approver_provenance` (a dual-control release, or the resolution of an interrupted one, went ahead with an approver or resolver account created, re-passworded or TOTP-enrolled after the request -- BACKLOG #315, #2125; keyed on `approval:`, or `approval::resolve` for a resolution, and the payload is the operation key and the closed-set change slugs, never a username or the captured params), `administrator_granted` (the built-in Administrator role was granted by account creation, a role change, a directory group newly mapped to it -- BACKLOG #315 --, a directory sign-in whose role sync newly gave the account the role -- vault BACKLOG #2610 -- or a directory reconcile pass whose role re-diff did -- vault BACKLOG #3141; keyed on `user:` or `ad-group:`, with the grant route and the granting administrator's username, or `` for a directory sign-in or reconcile pass), `no_enabled_administrator` (a directory sign-in's role sync or the session reconciler took Administrator from its last enabled holder -- vault BACKLOG #3229; keyed on `user:`, and the payload is `via`, `ad-sync` or `ad-reconcile`, and a fixed reason sentence, never message content), `intake_paused` (the engine paused intake because the staged backlog went over `[inbound].max_staged_depth` or the SQLite volume fell below `[retention].min_free_disk_mb` -- BACKLOG #290; keyed on `intake:staged_depth` or `intake:disk_floor`, with `@node:` or `@shard:` appended when several engine processes share the store (BACKLOG #2272), and the payload is the reason, a count or a MiB figure, its limit and the store backend's name, never message content), `config_changed` (a start's config differs from the store's baseline: the bytes it loaded, or the directory just after the load -- vault BACKLOG #2597, #3765; keyed on `config:`, and the payload is the two digests, the node and engine shard labels, the action, actor username, time and node of the row the older digest came from, and the `comparison` outcome, never the config directory, a git commit or message content), `crl_reload_refused` (the CRL reload refused a replaced CRL file, so running TLS contexts keep the copy they hold -- vault BACKLOG #2904; keyed on `crl_reload:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the file's path, a short class token for the remedy, a count of contexts, the engine's own fixed remedy sentence and, when a start would refuse the file too, a `start_refuses` flag, never the refusal's reason, which quotes CRL issuer names and dates; that reason is in the application log, and in the `detail` of the CRL expiry alert once the held copy nears its `nextUpdate`), `remote_debug_refused` (the engine's remote-debugging guard refused scripts that another process injected into the engine process -- vault BACKLOG #2742; keyed on `remote_debug:refused`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the count of scripts refused since the alert was last raised, the count since the process started and a fixed sentence built from the two, never a script's file name, which the injecting process chooses; that name is in the application log, in the guard's WARNING line), `sandbox_worker_refused` (a `[sandbox].mode = "subprocess"` worker was refused because the graph it loaded differs from the engine's, most often a config file edited on disk with no reload -- vault BACKLOG #2724; keyed on the inbound's name, raised once per refusal, and the payload is that name and a fixed sentence naming the cause and the remedy, never a message body or the refusal text, which names config names and digests and is in the application log), `cert_monitor_stalled` (a cert-expiry scan pass ran past its stall threshold, most likely on a blocked certificate or CRL read, so no expiry alert is raised until it returns -- vault BACKLOG #5885; keyed on `cert_monitor:scan`, raised once the pass runs past the threshold and again each threshold while it runs, and the payload holds at least that key, the seconds the pass has run and a fixed sentence built from them, never a file's path), `store_restored` (the first `serve` on a store `messagefoundry restore` placed ended every session -- BACKLOG #2614; keyed on `store:restored`, raised once per restore, and the payload is that key; a fixed sentence carrying the archive's age in days, the count of sessions ended, a pointer to `messagefoundry restore --help` and the time of the archive's newest audit row, of which the alert instance's reason column keeps the age, the count and the pointer whole and the time redacted or cut; that time again as `last_audit_at`; and the fixed notice of what a restore rolls back as `rollback_notice` (`messagefoundry/restore_notice.py`, BACKLOG #5094), fixed text the reason column never holds; never an account name or a row's content), and the seven security signals of the audit-stream rule layer -- vault BACKLOG #2613: `signin_failure_burst` (keyed on `signin:`, never the typed username), `access_denied_burst`, `body_view_burst` and `bulk_export` (each keyed on `account:`), `peer_refused_burst` (keyed on `inbound:`, never the refused peer's address), `log_level_debug` (keyed on `logging:debug`) and `posture_loosened` (keyed on `posture:start`, with `@node:` or `@shard:` appended when several engine processes share the store); the payload is a count and a fixed sentence holding a level name, switch names or a username, never a message body, a message id or an audit row's detail. The reachable **inverse** signals — `connection_restored`, `leadership_lost`, `dr_released`, `dr_restart_cleared` (raised by each `dr_activated` and `dr_released`, so an activation, or a release that leaves a restarted box passive, resolves the open `dr_restarted_passive` for the same box label -- BACKLOG #5965), `store_privilege_clean`, `vault_privilege_clean`, `intake_resumed`, `posture_restored` (it resolves `posture_loosened` under the same key, so for the same engine process, when a start records no security loosening in a row marked neither `superseded` nor `baseline_unchecked` and a live posture read then names none -- vault BACKLOG #2613; an unpinned cluster node's key changes on every start, so that node raises the inverse for its own instance as it shuts down; when that instance can still stay open is in [SECURITY.md](SECURITY.md)), `crl_reload_applied` (it resolves `crl_reload_refused` under the same key, so for the same file and the same engine identity, at least once the reload's record no longer holds the refusal, once no hop holds any CRL, and when the reload stops -- vault BACKLOG #2904; it is also raised once per held file outside a CA bundle, at the first pass that judges it with no refusal standing, whether or not an alert is open, so it can resolve nothing, and it then clears one an earlier run under that identity left open -- vault BACKLOG #3543. An alert for a file no hop holds now stays open, and so does one an unpinned cluster node raised, because that node's identity changes on every start; [CONFIGURATION.md](CONFIGURATION.md), *The alert resolves itself*, is the source of record), `ad_reconcile_breaker_cleared`, `ad_reconcile_hold_released` (the last two resolve `ad_reconcile_held` and `ad_reconcile_aborted`, the latter only under the breaker's, the referral's or the lasting outage's source: the probe fault's, the configuration refusal's, a paging refusal's and an unreached account's instances have no inverse; when they do, and where they never do, is stated once in [CONFIGURATION.md](CONFIGURATION.md#when-the-reconcilers-alerts-resolve-themselves) -- BACKLOG #2136) — are never rows here: `_record_state` routes an inverse through `_AUTO_RESOLVE` to `resolve_alert_instances_fenced` (BACKLOG #4916), or `resolve_alert_instances_for` on a store without the fence methods, never to `upsert_alert_instance`. So is `connection_started`, which resolves `connection_stopped` under the bare connection name: the runner raises it only when an operator's start or restart finds an inbound up and no cause it can see still holds the name down in either direction (BACKLOG #1741). Every other start raises nothing, at least an engine start, a committed reload, the scheduler and every alert rule's restart, so an open stop keeps its instance, ack and suspend across them. `AlertSink.connection_started` states the full contract, including the operator starts that still raise nothing. An instance raised under a prefixed stand-in such as `reference:` is never resolved by it. | rows: `event_type`, `connection`, `severity`, `status`, `first_seen`, `last_seen`, `count`, `reason`, `acked_by`, `acked_at`, `resolved_at`, `suspended_until`, `escalation_tier`, `raised_by` (a random per-process id naming the newest raise's writer, BACKLOG #4916; never a host, user or message value) | the store database, **all three backends** | the operator alert list — acknowledge / resolve / suspend. Durable state is recorded **before** any suppression or throttle return, so a muted alert still leaves a record | `GET /alerts/active` under **`monitoring:diagnose`** (**not** a PHI permission) with the same per-channel scope, and `reason` alone gated on `messages:view_summary` and masked as `****` until the audited per-alert `reveal=` act (BACKLOG #2443; the `alert_instance.reason` row of §3's PL-2 block says how); ack/resolve/suspend/**resume** are POSTs on the same tier, and the separate read-only `GET /alerts/rules` view sits on its own gate | shares the connection-event window; **only RESOLVED instances are DELETEd**, by `resolved_at` — retention never ages out an open or acknowledged condition from under an operator; a row can still close with no inverse and no operator, at least through the `intake_paused` staleness sweep (BACKLOG #3269), which resolves another engine process's open or acknowledged pause under the expiry rule in [CONFIGURATION.md](CONFIGURATION.md#alerts), after which retention treats it as any resolved row | **`reason` is free text** taken from the event's internal `_detail` (the `connection_error` reason kept off the wire, BACKLOG #5021), `detail` or `reason`: `safe_text(reason, limit=200)` (the bound §3's PL-2 block states) then cipher-encrypted (AAD `("alert_instance","reason",event_type,connection)` — the de-dup grain, so one AAD covers both the INSERT and the re-fire UPDATE). | | **9. `response` rows with `kind='ack_sent'` — DEFAULT ON** (`[diagnostics].response_sent = true`) | the ACK/NAK the engine returned to an inbound sender, under a sentinel destination `\x1fack:` | rows: `ack_code` (`AA`/`AE`/`AR`/`CA`/`CE`/`CR`), `ack_phase` (`decode`/`parse`/`strict`/`ingest`), `outcome`, `body`, `detail` | the store database | "what did we actually reply, and why" — the operator's answer to a sender disputing an ACK | `GET /messages/{id}/responses` under `messages:read` + `require_phi_read`; the `body` only for a caller who also holds `messages:view_raw` and `messages:view_summary`; every read writes a `response.read` audit row | `body`, `detail` and `resp_headers` are set to `NULL` in place by `purge_message_bodies` on the message-body window, on all three backends | **PHI fail-safe:** the ACK **body** is stored **only when the store cipher is active** — on a keyless store it is `NULL` rather than plaintext — and every NAK passes no body at all, so the offending field value is never persisted. The disposition metadata (`ack_code`/`ack_phase`/`outcome`) is non-PHI and always captured; `detail` is `safe_text`-scrubbed, held to the 200-character bound §3's PL-2 block states, and encrypted | | **10. `[alerts]` webhook transport** (off by default — `webhook_url` unset) | one HTTPS POST per alert, carrying every non-underscore event key as JSON | JSON | the operator's webhook endpoint (Slack/Teams/PagerDuty/custom) | operator notification | **`https` only** — a plaintext `http://` webhook URL is refused at construction. Redirects are refused; an optional `webhook_allowed_hosts` egress allowlist gates the host. A verifying `https` hop off this box also takes the revocation guard at build, on a host the `webhook_allowed_hosts` allowlist admits. An unset or empty allowlist admits every host, an explicit `[]` included, and so does an environment value that splits to no host, such as `""` or `","`. A host off a non-empty allowlist is refused at build, before this guard (BACKLOG #5088). A TOML list keeps its entries as written, so `[""]` or `[","]` is not empty and names no real host, and the build refuses every real host. Under an enforcing or unknown posture the guarded hop is refused unless the `[alerts].webhook_tls_revocation_attested` pair is set ([ADR 0173](adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md) states the guard and its levers) | the endpoint's | **carries the alert's `detail`/`reason` free text** for at least `connection_stopped`, `log_write_failed` and `backup_failed` (`safe_exc()`-scrubbed at the emit sites, but **not** re-run through `safe_text` on this path, and a scrubbed reason can still echo a partner's reply text). `connection_error` no longer carries its detail: in its place it sends the exception class (or the fixed token `unnamed error` for a class that is not a plain identifier), beside at least the connection and the kind, and keeps the detail under the internal `_detail` key, which the notifier pops before any transport is handed the event and which the alert instance's stored `reason` (row 8) still keeps (`NotifierAlertSink.connection_error`, BACKLOG #5021). Internal `_`-prefixed keys, at least `_detail`, `_transports`, the per-rule recipients, the rule id and the cooldown, are stripped before send, so recipient addresses never cross the wire | | **11. `[alerts]` SMTP transport — operator alert list** (off unless `email_smtp_host` + `email_from` + ≥1 `email_to`) | one email per alert; default subject `[MessageFoundry] — `, default body every non-underscore event key as `k: v` | plain text (always kept — never HTML-only); optional HTML alternative | the operators' mailboxes | operator notification | `smtp_allowed_hosts` egress allowlist; the SMTP password comes from `MEFOR_ALERTS_EMAIL_PASSWORD` or a `[secrets]` provider, never the config file; per-send timeout `email_timeout` | the mail system's | carries the same `detail`/`reason` free text as the webhook, and like it leaves out `connection_error`'s detail (row 10, BACKLOG #5021). #138 operator templates are constrained to a **closed non-PHI variable allowlist** validated fail-closed at config load. **Transport posture:** `send_plain_email` builds an explicit **verifying** context (chain + hostname + strict RFC 5280, TLS 1.2 floor) via `tls_policy.build_smtp_tls_context()` and passes it to `starttls()`, anchored to the OS roots, `[alerts].email_tls_ca_file`, or `[tls].internal_ca_file` — the same factory the EMAIL and DIRECT *message destinations* use, so all three SMTP cells now share one policy ([#323](BACKLOG.md), closed 2026-08-02). Before that this call passed **no** context and Python's stdlib default applied (`ssl._create_stdlib_context` **is** `ssl._create_unverified_context` — `CERT_NONE`, `check_hostname = False`), leaving the hop encrypted but unauthenticated. There is still **no hop gradient or attestation for this path's TLS deviations** — unlike the connectors, this cell is constructed outside the `active_hop_posture` scope, so those deviations (`email_use_tls = false`, or `email_tls_verify = false`) are gated by a `[security].allow_unverified_alert_smtp_tls` **acknowledgment switch at the serve gate** rather than by the clamped escape: on an enforcing PHI instance `serve` refuses to start without it, and permits + `AUDIT`-logs the start with it. That switch covers a hop with no login: beside `email_username` either deviation is refused at settings load, with no escape (vault BACKLOG #3533). Both deviations are named by `security_loosenings()` and reported by `messagefoundry check`'s `alert-smtp-tls` advisory. Revocation is a separate gate: a hop off this box that carries a login takes the revocation guard at build, on a host the `smtp_allowed_hosts` allowlist admits; that allowlist reads as row 10 says the webhook's does, a TOML `[""]` included. A host off a non-empty allowlist is refused at build, before this guard (BACKLOG #5088). Under an enforcing or unknown posture the guarded hop is refused unless one of its levers holds ([ADR 0173](adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md) states the guard, its levers, and why a hop with no login takes none) | diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 5080ef82cf..fe093955ef 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -3376,7 +3376,9 @@ least these paths. The alert is keyed `approval:` and carries the row's acti resolution's lost `approval.approver_provenance` row is keyed `approval::resolve` instead, so it cannot fold into a lost release flag on the same request (vault BACKLOG #3438). A lost `approval.standing_shown` row is keyed `approval:listing`, because it belongs to a listing rather -than to one request. +than to one request. A lost `approval.seal_check_unavailable` row is keyed +`approval::seal-check`, so it cannot fold into a lost request or outcome row on the same +request. - a refusal's row, or an outcome row written alone after its status. The log line carries the row's detail; @@ -3391,7 +3393,19 @@ than to one request. - an outcome whose status write found the row moved, where the read-back does not find this write's row at its status and decision time, as below. The log line carries the row's detail; on an interrupted or failed outcome its `recorded` or `compensated` field reads `false` where - another caller moved the row, and `unknown` where the read-back cannot tell. + another caller moved the row, and `unknown` where the read-back cannot tell; +- the best-effort `approval.seal_check_unavailable` row, below. The log line carries the row's + detail. + +**Under `vault_transit`, a request whose seal Vault transit cannot check writes a best-effort +`approval.seal_check_unavailable` row (vault BACKLOG #8202 item 146).** The gate pages +`authority-seal-transit` and writes the row with actor `system`, naming the request whose seal +went unchecked, not who was refused, from where, or for which act. A route that meets it answers +**503** with `Retry-After`; the gate's own read-back after a failed write, and the restart +reconcile, meet the same check, write the row and answer nobody. The row is throttled, may fail +to write during the Outage it records, and holds the store's writer lock while it waits; +[ADR 0217](adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md), +*Open audit gaps*, states how, and what stays open. For some failed writes the gate logs at ERROR and pages nothing. At least this one: a restart cannot move a leftover `executing` row to `interrupted`. diff --git a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md index 901c3a67da..0050f404e4 100644 --- a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md +++ b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md @@ -313,7 +313,9 @@ give, or freeze a revocation a failed seal would not**. That is the test each an A correction, added 2026-11-11: the Outage row's "the refused request itself is audited where the audit append still works" does not hold for a request the approval gate refuses on an Outage, which writes no row; that path and two others are named in *Open audit gaps, a correction added -2026-11-11*, in (c). +2026-11-11*, in (c). A later correction, added 2026-12-01: the approval gate's path is gap (3) +there, which that list now records as narrowed, not closed. At least gaps (1), (3), (4), (6) and +(7) there, with its extension, are paths where the Outage row's audit promise does not fully hold. A correction, added 2026-11-11: the Unverifiable row's audit action and page do not hold on at least gaps (1), (2), (5) and (6) of *Open audit gaps, a correction added 2026-11-11*, and its @@ -1130,6 +1132,27 @@ session, approval, on SQLite, PostgreSQL and SQL Server): writes no row. The owner ruled on 2026-11-11, in the Lander's session, that this ADR names them as open and the build merges with them filed: "do it" (https://github.com/MEFORORG/MessageFoundry/pull/2860#issuecomment-6785384065). + **A correction, added 2026-12-01:** gap (3) is narrowed, not closed (vault BACKLOG #8202 item + 146). `_approval_seal_outage` now writes a best-effort `approval.seal_check_unavailable` row + beside its page, an `approval.*` action rather than `integrity.*`, since an Outage records no + seal failure. What it records is the approval row whose seal went unchecked, under the actor + `system`: it does not name who was refused, from where, or for which act. It is throttled per + request on the gate's seal-report interval (`SEAL_FAILURE_REPORT_INTERVAL_SECONDS`), in each + gate and so in each engine process, not across a cluster, and an attempt spends that interval + whether or not it lands, so at least these refusals write no row of their own: a second refusal + on the same request inside the interval, by any operator; one whose attempt fell in an interval + a failed write, or a write cancelled while it waited, already spent, though the append may work + again by then (a cancelled write is not logged or paged either); and one whose slot the gate's + own read-back after a failed write spent, which writes the row though no caller was refused. A + failed write is + logged and paged as the gate's other soft rows are, under the key + `approval::seal-check`. Under `vault_transit` the audit append's MAC goes through Transit + too, so during an Outage the write may fail, and while it waits it holds the store's writer + lock, as the AD map's Outage row (decision d20261110T181645742-b9eccb) already does. Its page, + WARNING and 503 text no longer say the request was refused, that nothing was done, or that Vault + did not answer, as (c) item 4 requires (item 145), since the same check runs on the gate's + read-back after a write or a release. Gaps (1) and (2) are still open, and so is at least the + extension's list below. - **Open audit gaps, extended 2026-11-11.** The three paths above are not the whole list. At least these are open too, named here for filing on vault BACKLOG #8202, and each fails closed. (4) A disable reads every account: `update_user` asks `is_last_enabled_admin`, which reads every diff --git a/messagefoundry/api/approvals.py b/messagefoundry/api/approvals.py index fcbf460ad8..df07760a0e 100644 --- a/messagefoundry/api/approvals.py +++ b/messagefoundry/api/approvals.py @@ -98,6 +98,7 @@ UserRecord, approval_seal_ok_async, ) +from messagefoundry.transports.http_listener import TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS log = logging.getLogger(__name__) @@ -254,9 +255,10 @@ def _releasing_in_process(approval_id: str) -> bool: #: files a second request. REJOIN_SCAN_LIMIT = 1000 -#: The ``Retry-After`` seconds on the 503 :meth:`ApprovalGate._verified` raises when a Vault transit -#: Outage leaves a request's seal unchecked (ADR 0217: an Outage answers 503 with ``Retry-After``). -_TRANSIT_OUTAGE_RETRY_AFTER_SECONDS = 5 +#: The best-effort audit action a request writes when a Vault transit Outage leaves its seal +#: unchecked (ADR 0217, the Outage row: the refused request is audited where the audit append still +#: works). Not ``integrity.*``: an Outage records no seal failure. +APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION = "approval.seal_check_unavailable" #: Faults :meth:`ApprovalGate._read` raises as they are, because they name a defect in the read #: path, not a store that is down: a 503 inviting a retry would never clear (BACKLOG #3157). @@ -707,6 +709,8 @@ def __init__( self._seal_failures_reported = SealFailureThrottle() # When each request whose seal Vault transit cannot verify is reported again (ADR 0217). self._seal_unverifiable_reported = SealFailureThrottle() + # When each request a Vault transit Outage left unchecked is audited again (ADR 0217). + self._seal_outage_reported = SealFailureThrottle() # When the queue warns again about a request whose params are unreadable (BACKLOG #3252). self._unreadable_params_reported = SealFailureThrottle() # When a failed store read of each kind is logged again (BACKLOG #3157): the queue page @@ -3245,7 +3249,8 @@ async def _verified(self, found: Any, *, report: bool = True) -> ApprovalRow | N """``found`` as a checked :class:`ApprovalRow`, or ``None`` when its seal fails, which is reported unless ``report`` is False. Its params and requester id are what a release acts on and what the self-approval refusal compares, so a row changed outside the store acts on - nothing.""" + nothing. A Vault transit Outage raises a 503 :class:`ApprovalError` instead, reported by + :meth:`_approval_seal_outage` whatever ``report`` says, its audit row included.""" try: row = ApprovalRow.from_mapping(found) except RowSealError: @@ -3260,13 +3265,15 @@ async def _verified(self, found: Any, *, report: bool = True) -> ApprovalRow | N await self._approval_seal_unverifiable(row.id, exc) return None except TransitSealUnavailableError as exc: - # ADR 0217, the Outage row: refuse the request, record no seal failure, page. - self._approval_seal_outage() + # ADR 0217, the Outage row: record no seal failure, page, audit the request where the + # append still works, and answer 503. A read-back after a write or a release meets + # this too, so the text says only what was not checked, never what was not done. + await self._approval_seal_outage(row.id) raise ApprovalError( 503, - "Vault transit could not check this approval request's integrity seal, so " - "nothing was done; try again once it answers", - headers={"Retry-After": str(_TRANSIT_OUTAGE_RETRY_AFTER_SECONDS)}, + "an approval request's integrity seal could not be checked through Vault " + "transit; try again later", + headers={"Retry-After": str(TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS)}, ) from exc if held: return row @@ -3312,20 +3319,45 @@ async def _approval_seal_unverifiable( context="a request's integrity seal could not be verified", ) - def _approval_seal_outage(self) -> None: - """Page a Vault transit Outage met checking a request's seal under the shared - ``authority-seal-transit`` subject (ADR 0217, *The four answers*), with no audit row: an - Outage records no seal failure. The WARNING is throttled, as :meth:`_read` throttles a - store fault's, since the queue reads on every page load.""" + async def _approval_seal_outage(self, approval_id: str) -> None: + """Report a Vault transit Outage met checking request ``approval_id``'s seal (ADR 0217, + *The four answers*): a page under the shared ``authority-seal-transit`` subject, every + time; a WARNING, throttled as :meth:`_read` throttles a store fault's, since the queue reads + on every page load; and a best-effort :data:`APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION` row, + which records no seal failure. The row names the request whose seal went unchecked, not + who was refused or for what act, and is throttled per request: an attempt spends the slot + whether or not it lands, so a Vault that stays down is not asked for an audit MAC on every + page load. A failed audit write is logged and paged under its own key, not raised: during + an Outage the append may fail too, and the 503 still stands. + + The text names what was not checked and no outcome, and never says Vault did not answer: + this check also runs on the gate's read-back after a write or a release + (:meth:`_read_back_request`), where an operation may have run, and Vault may have answered + with a refusal the probe could not clear (ADR 0217 (c) item 4).""" reason = ( - f"an {APPROVAL_KIND} request's integrity seal could not be checked because Vault" - " transit was unavailable; the request was refused and nothing was done" + f"an {APPROVAL_KIND} request's integrity seal could not be checked through Vault" + " transit, so nothing this check read from it is acted on" ) if self._read_faults_reported.due("transit-outage"): log.warning("%s", reason) pager = getattr(self._store, "seal_pager", None) if callable(pager): pager().outage(reason) + if not self._seal_outage_reported.due(approval_id): + return + ref = scrub_log_argument(approval_id) + await self._record_audit_soft( + ref, + APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION, + actor="system", + detail=json.dumps({"kind": APPROVAL_KIND, "approval_id": approval_id}), + client=None, + context="a request's integrity seal could not be checked through Vault transit", + # Its own key, so a lost row of this best-effort kind cannot fold into, and throttle, + # the page for a lost approval.requested or outcome row on the same request, which a + # read-back after a failed write raises next (as approval::resolve is kept apart). + alert_key=f"approval:{ref}:seal-check", + ) async def _approval_seal_failed(self, approval_id: str) -> None: """Report a request whose row failed its integrity seal (BACKLOG #2592): a WARNING, an diff --git a/messagefoundry/pipeline/alerts.py b/messagefoundry/pipeline/alerts.py index 284e525ddd..21cf1830dd 100644 --- a/messagefoundry/pipeline/alerts.py +++ b/messagefoundry/pipeline/alerts.py @@ -723,7 +723,8 @@ def audit_write_failed(self, name: str, *, action: str) -> None: id>``, the key :meth:`approval_too_early` uses, ``approval::resolve`` for a resolution's lost provenance row (vault BACKLOG #3438), and ``approval:listing`` for a lost ``approval.standing_shown`` row, which belongs to a listing rather than to one request - (vault BACKLOG #3747). ``POST /config/reload`` uses + (vault BACKLOG #3747), and ``approval::seal-check`` for a lost + ``approval.seal_check_unavailable`` row (vault BACKLOG #8202). ``POST /config/reload`` uses ``config_reload:inline`` when it loses the ``config_reload_attempted`` row it writes before an ungated reload, and then refuses the reload with 503 (vault BACKLOG #2254). The IdP step-up return's audit budget uses ``step_up_return:audit_budget:`` when its diff --git a/tests/test_transit_approval_gate.py b/tests/test_transit_approval_gate.py index 8d5b94dd81..9314c4ca54 100644 --- a/tests/test_transit_approval_gate.py +++ b/tests/test_transit_approval_gate.py @@ -2,10 +2,12 @@ # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """The approval gate under the Transit row sealer (ADR 0217): an Unverifiable request is denied as a Forged one is, under its own audit action and page, and an Outage refuses the request with a 503, -pages under the Outage subject and records no seal failure. Synthetic data only.""" +pages under the Outage subject, records no seal failure and writes a best-effort row of its own. +Synthetic data only.""" from __future__ import annotations +import logging import sqlite3 from collections.abc import AsyncIterator from pathlib import Path @@ -20,6 +22,7 @@ AUTHORITY_SEAL_UNVERIFIABLE_ACTION, ) from messagefoundry.config.settings import ApprovalsSettings +from messagefoundry.pipeline.alerts import LoggingAlertSink from messagefoundry.store.crypto import generate_key, make_cipher from messagefoundry.store.row_seal import ( TRANSIT_OUTAGE_SUBJECT, @@ -27,6 +30,7 @@ TransitRowSealer, ) from messagefoundry.store.store import MessageStore +from messagefoundry.transports.http_listener import TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS from tests._pending_approval_store_contract import _resolve, _StandingStore from tests._transit_seal_fake import FakeBackend, with_version @@ -136,7 +140,7 @@ async def test_an_unverifiable_executing_release_is_hidden_audited_and_paged( @pytest.mark.parametrize("route", ["list_executing", "interrupt_stranded"]) -async def test_an_outage_refuses_the_route_with_a_503_and_pages_without_an_audit_row( +async def test_an_outage_refuses_the_route_with_a_503_and_pages_without_a_seal_failure_row( transit: tuple[MessageStore, FakeBackend, Path], route: str ) -> None: store, backend, path = transit @@ -162,3 +166,150 @@ async def test_an_outage_refuses_the_route_with_a_503_and_pages_without_an_audit assert _sql(path, "SELECT status FROM pending_approvals WHERE id=?", ("a-1",)) == [ ("executing",) ] + + +#: The best-effort row a request met by a Vault transit Outage writes (ADR 0217, the Outage row: +#: "the refused request itself is audited where the audit append still works"). Written out, not +#: imported, so this file pins the action name the audit trail carries. +_OUTAGE_ACTION = "approval.seal_check_unavailable" + + +@pytest.mark.parametrize("route", ["list_executing", "interrupt_stranded"]) +async def test_an_outage_writes_one_best_effort_row_per_request_and_pages_each_time( + transit: tuple[MessageStore, FakeBackend, Path], route: str +) -> None: + """Vault BACKLOG #8202 item 146: an Outage at the gate's seal check wrote no row, so a request + it refused went unaudited though this store's audit append still works. The row is throttled + per request, as the gate's other seal reports are; the page is not.""" + store, backend, path = transit + await _executing(store, path, "a-1") + store._row_sealer = TransitRowSealer(backend) # nothing cached + pages = _arm(store) + gate = _gate(store) + + backend.down = True + try: + for _ in range(2): + with pytest.raises(ApprovalError) as refused: + if route == "list_executing": + await gate.list_executing() + else: + await gate.interrupt_stranded("a-1", actor="op", actor_user_id="op-id") + assert refused.value.status == 503 + # The engine's one temporary-refusal interval (vault BACKLOG #8202 item 153). + assert refused.value.headers == { + "Retry-After": str(TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS) + } + finally: + backend.down = False + audited = await _rows(store, _OUTAGE_ACTION, "a-1") + assert len(audited) == 1 + assert audited[0]["actor"] == "system" + assert '"kind": "approval"' in str(audited[0]["detail"]) + assert pages == [TRANSIT_OUTAGE_SUBJECT, TRANSIT_OUTAGE_SUBJECT] + # An Outage records no seal failure, under either cause. + assert await _rows(store, AUTHORITY_SEAL_UNVERIFIABLE_ACTION, "a-1") == [] + assert await _rows(store, AUTHORITY_SEAL_FAILED_ACTION, "a-1") == [] + + +async def test_an_outage_row_is_throttled_per_request_not_once_for_all( + transit: tuple[MessageStore, FakeBackend, Path], +) -> None: + """A second request refused inside the interval still writes its own row: the throttle is + keyed by request, so one request's row cannot hold back another's.""" + store, backend, path = transit + await _executing(store, path, "a-1") + await _executing(store, path, "a-2") + store._row_sealer = TransitRowSealer(backend) # nothing cached + gate = _gate(store) + + backend.down = True + try: + for approval_id in ("a-1", "a-2"): + with pytest.raises(ApprovalError): + await gate.interrupt_stranded(approval_id, actor="op", actor_user_id="op-id") + finally: + backend.down = False + assert len(await _rows(store, _OUTAGE_ACTION, "a-1")) == 1 + assert len(await _rows(store, _OUTAGE_ACTION, "a-2")) == 1 + + +async def test_an_outage_names_no_refusal_and_no_outcome( + transit: tuple[MessageStore, FakeBackend, Path], caplog: pytest.LogCaptureFixture +) -> None: + """Vault BACKLOG #8202 item 145: ADR 0217 (c) item 4 says an Outage's text never says "the + request was refused", since there may be no request, nor that Vault did not answer, since it + may have; and the gate's own read-back after a write, or after a release ran, meets the same + check, where "nothing was done" would be false. The page, the WARNING and the 503 say only that + the seal could not be checked.""" + store, backend, path = transit + await _executing(store, path, "a-1") + store._row_sealer = TransitRowSealer(backend) # nothing cached + reasons: list[str] = [] + store.seal_pager().arm(lambda _subject, reason: reasons.append(reason)) + gate = _gate(store) + + backend.down = True + try: + with ( + caplog.at_level(logging.WARNING, logger="messagefoundry.api.approvals"), + pytest.raises(ApprovalError) as refused, + ): + await gate.list_executing() + finally: + backend.down = False + assert len(reasons) == 1 + warnings = [ + r.getMessage() + for r in caplog.records + if r.name == "messagefoundry.api.approvals" and r.levelno == logging.WARNING + ] + assert warnings == [reasons[0]] + for text in (reasons[0], str(refused.value.detail)): + assert "Vault transit" in text + assert "refused" not in text + assert "nothing was done" not in text + assert "answer" not in text + + +class _LostAuditSink(LoggingAlertSink): + def __init__(self) -> None: + super().__init__() + self.lost: list[tuple[str, str]] = [] + + def audit_write_failed(self, name: str, *, action: str) -> None: + self.lost.append((name, action)) + + +async def test_an_outage_row_that_cannot_be_written_is_paged_under_its_own_key( + transit: tuple[MessageStore, FakeBackend, Path], monkeypatch: pytest.MonkeyPatch +) -> None: + """The row is best effort: during an Outage the append may fail too. The 503 still stands, the + loss is paged as ``audit_write_failed``, and under ``approval::seal-check``, so it cannot + fold into the page for a lost ``approval.requested`` or outcome row on the same request, which + is keyed ``approval:``. The slot is spent either way, so a Vault that stays down is not + asked again on the next load.""" + store, backend, path = transit + await _executing(store, path, "a-1") + store._row_sealer = TransitRowSealer(backend) # nothing cached + sink = _LostAuditSink() + gate = ApprovalGate( + _StandingStore(store), + ApprovalsSettings(enabled=True, operations=["dead_letter_replay"], min_dwell_seconds=0.0), + resolve_identity=_resolve, + alert_sink=sink, + ) + + async def refuse(_action: str, **_kw: Any) -> None: + raise sqlite3.OperationalError("synthetic: the audit append is down too") + + monkeypatch.setattr(gate._store, "record_audit", refuse) + backend.down = True + try: + for _ in range(2): + with pytest.raises(ApprovalError) as refused: + await gate.list_executing() + assert refused.value.status == 503 + finally: + backend.down = False + assert sink.lost == [("approval:a-1:seal-check", _OUTAGE_ACTION)] From dbb202161c7759e8b812b2c13aef1548f9f30eee Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:50:29 -0600 Subject: [PATCH 2/7] Outage row is not tried against a silent Vault, and a cancel cannot drop it One repair round for the Lander's hold 7329911665 on this rebuild (vault BACKLOG #8202). - Fix (1): TransitSealUnavailableError gains an unreachable flag, set by the Transit sealer when the failed call's error chains an OSError (a connection error or a timeout). The approval gate then does not try its approval.seal_check_unavailable row, whose audit MAC would wait on the same Vault under the writer lock; it logs the row at ERROR and pages it as lost. - Fix (2): where the row is tried, it runs through the gate's _shielded write, so a cancelled caller cannot drop it with no record. - Fix (3): the _verified docstring, the action constant's comment and the changelog headline say best effort, throttled, actor system. Proof tests: a hung Vault never starts the append (503 and a concurrent store write inside the bound, row paged as lost); a cancel during the write still lands the row. Both failed on ab9fa03 before this change. Verified-by: tests --- .../8202-approval-seal-outage-row.security.md | 13 +- docs/SECURITY.md | 11 +- ...ciler-ends-sessions-rather-than-holding.md | 35 ++--- messagefoundry/api/approvals.py | 90 +++++++++---- messagefoundry/store/row_seal.py | 29 +++- tests/test_transit_approval_gate.py | 125 +++++++++++++++++- 6 files changed, 247 insertions(+), 56 deletions(-) diff --git a/changelog.d/8202-approval-seal-outage-row.security.md b/changelog.d/8202-approval-seal-outage-row.security.md index 46e681e786..dcb8ea696d 100644 --- a/changelog.d/8202-approval-seal-outage-row.security.md +++ b/changelog.d/8202-approval-seal-outage-row.security.md @@ -1,6 +1,9 @@ -- **An approval request whose seal Vault transit cannot check now writes an audit row.** Under - `[store].cipher_provider = "vault_transit"`, the approval gate's 503 on a Transit Outage at a - request's seal check also writes a best-effort, throttled `approval.seal_check_unavailable` row; - before, it only paged. The row names the request, not who was refused. Its page, log line and - 503 text no longer say the request was refused, that nothing was done, or that Vault did not +- **An approval request whose seal Vault transit cannot check may now get a best-effort, + throttled audit row under the actor `system`.** Under `[store].cipher_provider = + "vault_transit"`, the approval gate's Outage at a request's seal check pages, logs and refuses + as before, and also tries an `approval.seal_check_unavailable` row where Vault replied with a + failure. The row names the request, not who was refused, and may not be written: it is not tried + when Vault gave no reply, at most one is tried per request per interval, and the write can fail. + A row not written is logged at ERROR and paged as a lost audit row. The page, log line and 503 + text no longer say the request was refused, that nothing was done, or that Vault did not answer. (`BACKLOG #8202`) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index fe093955ef..e9df1dea5f 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -3397,13 +3397,14 @@ request. - the best-effort `approval.seal_check_unavailable` row, below. The log line carries the row's detail. -**Under `vault_transit`, a request whose seal Vault transit cannot check writes a best-effort -`approval.seal_check_unavailable` row (vault BACKLOG #8202 item 146).** The gate pages -`authority-seal-transit` and writes the row with actor `system`, naming the request whose seal +**Under `vault_transit`, a request whose seal Vault transit cannot check may get a best-effort, +throttled `approval.seal_check_unavailable` row under the actor `system` (vault BACKLOG #8202 item +146).** The gate pages `authority-seal-transit` and tries the row, naming the request whose seal went unchecked, not who was refused, from where, or for which act. A route that meets it answers **503** with `Retry-After`; the gate's own read-back after a failed write, and the restart -reconcile, meet the same check, write the row and answer nobody. The row is throttled, may fail -to write during the Outage it records, and holds the store's writer lock while it waits; +reconcile, meet the same check, try the row and answer nobody. The row is not tried when Vault gave +no reply, since its audit MAC would wait on the same Vault; that row is logged and paged as lost. +Where it is tried it may still fail to write; [ADR 0217](adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md), *Open audit gaps*, states how, and what stays open. diff --git a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md index 0050f404e4..066d225532 100644 --- a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md +++ b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md @@ -1133,22 +1133,25 @@ session, approval, on SQLite, PostgreSQL and SQL Server): as open and the build merges with them filed: "do it" (https://github.com/MEFORORG/MessageFoundry/pull/2860#issuecomment-6785384065). **A correction, added 2026-12-01:** gap (3) is narrowed, not closed (vault BACKLOG #8202 item - 146). `_approval_seal_outage` now writes a best-effort `approval.seal_check_unavailable` row - beside its page, an `approval.*` action rather than `integrity.*`, since an Outage records no - seal failure. What it records is the approval row whose seal went unchecked, under the actor - `system`: it does not name who was refused, from where, or for which act. It is throttled per - request on the gate's seal-report interval (`SEAL_FAILURE_REPORT_INTERVAL_SECONDS`), in each - gate and so in each engine process, not across a cluster, and an attempt spends that interval - whether or not it lands, so at least these refusals write no row of their own: a second refusal - on the same request inside the interval, by any operator; one whose attempt fell in an interval - a failed write, or a write cancelled while it waited, already spent, though the append may work - again by then (a cancelled write is not logged or paged either); and one whose slot the gate's - own read-back after a failed write spent, which writes the row though no caller was refused. A - failed write is - logged and paged as the gate's other soft rows are, under the key - `approval::seal-check`. Under `vault_transit` the audit append's MAC goes through Transit - too, so during an Outage the write may fail, and while it waits it holds the store's writer - lock, as the AD map's Outage row (decision d20261110T181645742-b9eccb) already does. Its page, + 146). `_approval_seal_outage` now tries a best-effort, throttled + `approval.seal_check_unavailable` row under the actor `system` beside its page, an `approval.*` + action rather than `integrity.*`, since an Outage records no seal failure. What it records is + the approval row whose seal went unchecked: it does not name who was refused, from where, or for + which act. It is throttled per request on the gate's seal-report interval + (`SEAL_FAILURE_REPORT_INTERVAL_SECONDS`), in each gate and so in each engine process, not across + a cluster, and an attempt spends that interval whether or not it lands, so at least these + refusals write no row of their own: a second refusal on the same request inside the interval, + by any operator; one whose attempt fell in an interval a failed or untried write already spent, + though the append may work again by then; one whose slot the gate's own read-back after a failed + write spent, which tries the row though no caller was refused; and every one where Vault gave no + reply. Under `vault_transit` the audit append's MAC goes through Transit too, under the store's + writer lock, so where the Outage's error chains an `OSError` (a connection error or a timeout, + `TransitSealUnavailableError.unreachable`) the row is not tried, so the refusal holds no store + lock and no Transit thread; it is logged at ERROR and paged as lost. Where Vault replied with a + failure the row is tried, through the gate's shielded write, so a cancelled caller does not + drop it; it may still fail, and a Vault that stops replying between the check and the append + can still hold the lock until Transit's timeout. A failed or untried write is logged and paged + as the gate's other soft rows are, under the key `approval::seal-check`. Its page, WARNING and 503 text no longer say the request was refused, that nothing was done, or that Vault did not answer, as (c) item 4 requires (item 145), since the same check runs on the gate's read-back after a write or a release. Gaps (1) and (2) are still open, and so is at least the diff --git a/messagefoundry/api/approvals.py b/messagefoundry/api/approvals.py index df07760a0e..f355041cd9 100644 --- a/messagefoundry/api/approvals.py +++ b/messagefoundry/api/approvals.py @@ -51,6 +51,7 @@ from __future__ import annotations import asyncio +import contextlib import json import logging import math @@ -255,9 +256,10 @@ def _releasing_in_process(approval_id: str) -> bool: #: files a second request. REJOIN_SCAN_LIMIT = 1000 -#: The best-effort audit action a request writes when a Vault transit Outage leaves its seal -#: unchecked (ADR 0217, the Outage row: the refused request is audited where the audit append still -#: works). Not ``integrity.*``: an Outage records no seal failure. +#: The audit action of the best-effort, throttled row, under the actor ``system``, that the gate +#: writes when a Vault transit Outage leaves a request's seal unchecked (ADR 0217, the Outage row). +#: It names the request, not who was refused; it is not tried when Vault gave no reply, and may +#: fail to write when it is tried. Not ``integrity.*``: an Outage records no seal failure. APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION = "approval.seal_check_unavailable" #: Faults :meth:`ApprovalGate._read` raises as they are, because they name a defect in the read @@ -3250,7 +3252,8 @@ async def _verified(self, found: Any, *, report: bool = True) -> ApprovalRow | N reported unless ``report`` is False. Its params and requester id are what a release acts on and what the self-approval refusal compares, so a row changed outside the store acts on nothing. A Vault transit Outage raises a 503 :class:`ApprovalError` instead, reported by - :meth:`_approval_seal_outage` whatever ``report`` says, its audit row included.""" + :meth:`_approval_seal_outage` whatever ``report`` says: a page, and a best-effort, + throttled audit row under the actor ``system``, which may not be written.""" try: row = ApprovalRow.from_mapping(found) except RowSealError: @@ -3265,10 +3268,11 @@ async def _verified(self, found: Any, *, report: bool = True) -> ApprovalRow | N await self._approval_seal_unverifiable(row.id, exc) return None except TransitSealUnavailableError as exc: - # ADR 0217, the Outage row: record no seal failure, page, audit the request where the - # append still works, and answer 503. A read-back after a write or a release meets - # this too, so the text says only what was not checked, never what was not done. - await self._approval_seal_outage(row.id) + # ADR 0217, the Outage row: record no seal failure, page, write a best-effort, + # throttled system row where Vault replied, and answer 503. A read-back after a write + # or a release meets this too, so the text says only what was not checked, never what + # was not done. + await self._approval_seal_outage(row.id, unreachable=exc.unreachable) raise ApprovalError( 503, "an approval request's integrity seal could not be checked through Vault " @@ -3319,16 +3323,22 @@ async def _approval_seal_unverifiable( context="a request's integrity seal could not be verified", ) - async def _approval_seal_outage(self, approval_id: str) -> None: + async def _approval_seal_outage(self, approval_id: str, *, unreachable: bool) -> None: """Report a Vault transit Outage met checking request ``approval_id``'s seal (ADR 0217, *The four answers*): a page under the shared ``authority-seal-transit`` subject, every time; a WARNING, throttled as :meth:`_read` throttles a store fault's, since the queue reads - on every page load; and a best-effort :data:`APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION` row, - which records no seal failure. The row names the request whose seal went unchecked, not - who was refused or for what act, and is throttled per request: an attempt spends the slot - whether or not it lands, so a Vault that stays down is not asked for an audit MAC on every - page load. A failed audit write is logged and paged under its own key, not raised: during - an Outage the append may fail too, and the 503 still stands. + on every page load; and a best-effort, throttled + :data:`APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION` row under the actor ``system``, which records + no seal failure. The row names the request whose seal went unchecked, not who was refused + or for what act, and is throttled per request: an attempt spends the slot whether or not it + lands, so a Vault that stays down is not asked for an audit MAC on every page load. A + failed audit write is logged and paged under its own key, not raised: during an Outage the + append may fail too, and the 503 still stands. + + When ``unreachable`` (Vault gave no reply, :attr:`TransitSealUnavailableError.unreachable`) + the row is not tried, and is logged and paged as lost, so this refusal holds no store lock + and no Transit thread. Otherwise the write runs through :meth:`_shielded`, so a cancelled + caller cannot drop it with no record. The text names what was not checked and no outcome, and never says Vault did not answer: this check also runs on the gate's read-back after a write or a release @@ -3346,18 +3356,44 @@ async def _approval_seal_outage(self, approval_id: str) -> None: if not self._seal_outage_reported.due(approval_id): return ref = scrub_log_argument(approval_id) - await self._record_audit_soft( - ref, - APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION, - actor="system", - detail=json.dumps({"kind": APPROVAL_KIND, "approval_id": approval_id}), - client=None, - context="a request's integrity seal could not be checked through Vault transit", - # Its own key, so a lost row of this best-effort kind cannot fold into, and throttle, - # the page for a lost approval.requested or outcome row on the same request, which a - # read-back after a failed write raises next (as approval::resolve is kept apart). - alert_key=f"approval:{ref}:seal-check", - ) + detail = json.dumps({"kind": APPROVAL_KIND, "approval_id": approval_id}) + context = "a request's integrity seal could not be checked through Vault transit" + # Its own key, so a lost row of this best-effort kind cannot fold into, and throttle, the + # page for a lost approval.requested or outcome row on the same request, which a read-back + # after a failed write raises next (as approval::resolve is kept apart). + alert_key = f"approval:{ref}:seal-check" + if unreachable: + # Under vault_transit the append's audit MAC is a Transit call made under the store's + # writer lock, so against a Vault that gave no reply it would hold that lock and a + # Transit thread until the same timeout again. The row is not tried: it is lost, and + # reported as the gate reports any lost row. + log.error( + "approval %s: %s, but its %s audit row was not tried, since Vault transit gave no " + "reply and the audit append's MAC goes through it. Lost detail: %s", + ref, + context, + APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION, + scrub_log_argument(detail), + ) + self._alert_lost_audit(ref, APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION, key=alert_key) + return + # Shielded, so a cancelled caller does not cancel the write with it: the write lands, or its + # failure is logged and paged by _record_audit_soft, or its own cancel is logged by the + # shield's orphan log. OperationInterrupted means the write itself was cancelled under a + # caller that was not, which the shield has logged; the caller's 503 still stands. + with contextlib.suppress(OperationInterrupted): + await self._shielded( + self._record_audit_soft( + ref, + APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION, + actor="system", + detail=detail, + client=None, + context=context, + alert_key=alert_key, + ), + approval_id, + ) async def _approval_seal_failed(self, approval_id: str) -> None: """Report a request whose row failed its integrity seal (BACKLOG #2592): a WARNING, an diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index 4855278773..9acad18e84 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -485,12 +485,35 @@ class TransitSealUnavailableError(Exception): :class:`RowSealError` (ADR 0217 (c) step 2), so no ``except CipherError`` and no forged-row fallback catches it. Raised outside any handler, so it chains nothing, and its text is fixed: never row data, a token hash or Vault's text. Its ``args`` are empty, so copy and pickle - rebuild it.""" + rebuild it. + + :attr:`unreachable` is True when the failed call never got a reply from Vault: the backend's + error chains an ``OSError``, as the Transit client's connection errors and timeouts are. A + caller that would make another Transit call only to record the refusal reads it to skip that + call rather than wait out the same timeout again (vault BACKLOG #8202).""" + + #: Whether Vault gave no reply at all (a connection error or a timeout); set per instance by the + #: sealer, False by default, so an instance built anywhere else claims nothing. + unreachable: bool = False def __str__(self) -> str: return "a row seal could not be made or checked through Vault transit" +def _vault_gave_no_reply(error: BaseException) -> bool: + """Whether ``error``'s cause chain holds an ``OSError``: a call that never got Vault's reply + (``requests``' connection errors and timeouts are ``OSError``), not one Vault answered with a + failure. Walks ``__cause__`` then ``__context__``, each link once.""" + seen: set[int] = set() + link: BaseException | None = error + while link is not None and id(link) not in seen: + if isinstance(link, OSError): + return True + seen.add(id(link)) + link = link.__cause__ if link.__cause__ is not None else link.__context__ + return False + + class TransitSealUnverifiableError(Exception): """A well-formed row seal that Transit refused to check while its active key still answers: the **Unverifiable** answer. A planted version, a node that lags a rotation and a retired @@ -1050,7 +1073,9 @@ def _outage(self, exc: CipherError) -> TransitSealUnavailableError: " not a seal failure", cause, ) - return TransitSealUnavailableError() + outage = TransitSealUnavailableError() + outage.unreachable = _vault_gave_no_reply(exc) + return outage @staticmethod def _parse(stored: object) -> tuple[str, str, int] | None: diff --git a/tests/test_transit_approval_gate.py b/tests/test_transit_approval_gate.py index 9314c4ca54..2c5306efc1 100644 --- a/tests/test_transit_approval_gate.py +++ b/tests/test_transit_approval_gate.py @@ -7,6 +7,7 @@ from __future__ import annotations +import asyncio import logging import sqlite3 from collections.abc import AsyncIterator @@ -23,7 +24,7 @@ ) from messagefoundry.config.settings import ApprovalsSettings from messagefoundry.pipeline.alerts import LoggingAlertSink -from messagefoundry.store.crypto import generate_key, make_cipher +from messagefoundry.store.crypto import CipherError, generate_key, make_cipher from messagefoundry.store.row_seal import ( TRANSIT_OUTAGE_SUBJECT, UNVERIFIABLE_SUBJECT_PREFIX, @@ -313,3 +314,125 @@ async def refuse(_action: str, **_kw: Any) -> None: finally: backend.down = False assert sink.lost == [("approval:a-1:seal-check", _OUTAGE_ACTION)] + + +class _HungBackend(FakeBackend): + """A Vault that accepts the call and never replies: the backend's verify ends only at its own + read timeout, as a ``CipherError`` chained from an ``OSError``, the form the Transit client + gives an unreachable Vault (``requests``' timeouts and connection errors are ``OSError``).""" + + def __init__(self) -> None: + super().__init__() + self.hung = False + + def verify_seal_hmac(self, key_name: str, digest: bytes, mac: str) -> bool: + if self.hung: + try: + raise TimeoutError("synthetic: Vault did not reply before the read timeout") + except TimeoutError as exc: + raise CipherError("synthetic: Transit row seal verify failed") from exc + return super().verify_seal_hmac(key_name, digest, mac) + + +#: The proof bound: the 503 and a concurrent store write each finish well inside it. +_BOUND_SECONDS = 2.0 + + +async def test_a_hung_vault_never_starts_the_append_and_pages_the_row_as_lost( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The Lander's hold on vault BACKLOG #8202's rebuild, fix (1): under ``vault_transit`` the + audit append's MAC is itself a Transit call made under the store's writer lock, so an append + attempted while Vault does not reply would hold that lock and a Transit thread until Transit's + own timeout. Here the append stands in as a call that never returns, as it would against a + hung Vault. The gate must not start it: the 503 comes back inside the bound, a concurrent store + write completes inside it, and the row is reported lost through the existing ERROR and page.""" + store = await MessageStore.open( + tmp_path / "hung.db", cipher=make_cipher(generate_key(), write_v2=True) + ) + try: + backend = _HungBackend() + store._row_sealer = TransitRowSealer(backend) + await _executing(store, tmp_path / "hung.db", "a-1") + store._row_sealer = TransitRowSealer(backend) # nothing cached + sink = _LostAuditSink() + gate = ApprovalGate( + _StandingStore(store), + ApprovalsSettings( + enabled=True, operations=["dead_letter_replay"], min_dwell_seconds=0.0 + ), + resolve_identity=_resolve, + alert_sink=sink, + ) + started = asyncio.Event() + + async def hung_append(_action: str, **_kw: Any) -> None: + started.set() + await asyncio.Event().wait() # never set: the append a hung Vault would never finish + + monkeypatch.setattr(gate._store, "record_audit", hung_append) + backend.hung = True + with caplog.at_level(logging.ERROR, logger="messagefoundry.api.approvals"): + try: + with pytest.raises(ApprovalError) as refused: + await asyncio.wait_for(gate.list_executing(), _BOUND_SECONDS) + finally: + backend.hung = False + assert refused.value.status == 503 + assert not started.is_set() + # A store write the hung append would have queued behind completes inside the bound. + await asyncio.wait_for( + store.create_pending_approval( + approval_id="a-2", + operation="dead_letter_replay", + params='{"n": "synthetic"}', + requester="r", + requester_user_id="r-id", + requested_at=3.0, + expires_at=None, + ), + _BOUND_SECONDS, + ) + assert sink.lost == [("approval:a-1:seal-check", _OUTAGE_ACTION)] + assert any( + r.levelno == logging.ERROR and _OUTAGE_ACTION in r.getMessage() + for r in caplog.records + if r.name == "messagefoundry.api.approvals" + ) + finally: + await store.close() + + +async def test_a_cancel_during_the_outage_row_write_does_not_lose_it_silently( + transit: tuple[MessageStore, FakeBackend, Path], monkeypatch: pytest.MonkeyPatch +) -> None: + """The Lander's hold, fix (2): the caller of a refused request can be cancelled, by a request + timeout or a client that goes away, while the gate waits on the best-effort row. The write + must then finish on its own, as the gate's other shielded writes do, or be logged and paged; + it must not vanish with no record.""" + store, backend, path = transit + await _executing(store, path, "a-1") + store._row_sealer = TransitRowSealer(backend) # nothing cached + gate = _gate(store) + entered = asyncio.Event() + release = asyncio.Event() + real_append = gate._store.record_audit + + async def slow_append(action: str, **kw: Any) -> None: + entered.set() + await release.wait() + await real_append(action, **kw) + + monkeypatch.setattr(gate._store, "record_audit", slow_append) + backend.down = True + try: + caller = asyncio.create_task(gate.list_executing()) + await asyncio.wait_for(entered.wait(), _BOUND_SECONDS) + caller.cancel() + with pytest.raises(asyncio.CancelledError): + await caller + finally: + backend.down = False + release.set() + assert await gate.drain(_BOUND_SECONDS) == [] + assert len(await _rows(store, _OUTAGE_ACTION, "a-1")) == 1 From dc1339e7befa75af4a4275041f4171d153f2e43d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 10:59:34 -0600 Subject: [PATCH 3/7] Outage row: a 504 or 408 gateway reply skips the append, and the 503 does not wait on it Repair round on the Lander's hold 7349008635, its four fixes only (vault BACKLOG #8202). 1. row_seal._vault_gave_no_reply counts a link as no reply when it is an OSError or keyprovider_vault.is_vault_timeout_reply reads it as an HTTP 408 or 504 reply, as crypto_transit does, so a gateway in front of a hung Vault no longer starts the audit append under the store's writer lock. The crypto inventory documents the new import. 2. ApprovalGate._approval_seal_outage starts the row as a task tracked in _inflight with the _forget and _log_orphaned_write done-callbacks, which drain() waits for, and returns at once, so the 503 no longer waits on the audit write (under _owner_lock on the catch-up reconcile path). 3. The docstring, ADR 0217, SECURITY.md and the changelog fragment no longer say the skip holds no store lock and no Transit thread; they say it does not hold the writer lock for an audit MAC, and name a connection error, a timeout, or a gateway or server timeout reply (HTTP 408 or 504) as what counts. 4. The ERROR line says the Transit call failed at the connection level or timed out, not that Vault gave no reply. Tests: the hung-Vault test is parametrized over a timeout, a 504 and a 408, takes the store's real writer lock in the append, and runs a concurrent write; the cancel test is replaced by one proving the 503 returns while the row is held and drain lands it. Both failed on 7df47c90 before the product edit. Verified-by: tests --- .../8202-approval-seal-outage-row.security.md | 7 +- docs/SECURITY.md | 6 +- ...ciler-ends-sessions-rather-than-holding.md | 16 +-- messagefoundry/api/approvals.py | 71 ++++++++------ messagefoundry/store/row_seal.py | 25 +++-- scripts/security/crypto_inventory_check.py | 7 +- tests/test_transit_approval_gate.py | 98 ++++++++++++------- 7 files changed, 139 insertions(+), 91 deletions(-) diff --git a/changelog.d/8202-approval-seal-outage-row.security.md b/changelog.d/8202-approval-seal-outage-row.security.md index dcb8ea696d..73b2e1dab8 100644 --- a/changelog.d/8202-approval-seal-outage-row.security.md +++ b/changelog.d/8202-approval-seal-outage-row.security.md @@ -1,9 +1,10 @@ - **An approval request whose seal Vault transit cannot check may now get a best-effort, throttled audit row under the actor `system`.** Under `[store].cipher_provider = "vault_transit"`, the approval gate's Outage at a request's seal check pages, logs and refuses - as before, and also tries an `approval.seal_check_unavailable` row where Vault replied with a - failure. The row names the request, not who was refused, and may not be written: it is not tried - when Vault gave no reply, at most one is tried per request per interval, and the write can fail. + as before, and also tries an `approval.seal_check_unavailable` row, without the 503 waiting on + it. The row names the request, not who was refused, and may not be written: it is not tried after + a connection error, a timeout, or a gateway or server timeout reply (HTTP 408 or 504), at most one + is tried per request per interval, and the write can fail. A row not written is logged at ERROR and paged as a lost audit row. The page, log line and 503 text no longer say the request was refused, that nothing was done, or that Vault did not answer. (`BACKLOG #8202`) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 28453bcdda..731e285734 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -3402,8 +3402,10 @@ throttled `approval.seal_check_unavailable` row under the actor `system` (vault 146).** The gate pages `authority-seal-transit` and tries the row, naming the request whose seal went unchecked, not who was refused, from where, or for which act. A route that meets it answers **503** with `Retry-After`; the gate's own read-back after a failed write, and the restart -reconcile, meet the same check, try the row and answer nobody. The row is not tried when Vault gave -no reply, since its audit MAC would wait on the same Vault; that row is logged and paged as lost. +reconcile, meet the same check, try the row and answer nobody. The row is not tried when the check +met a connection error, a timeout, or a gateway or server timeout reply (HTTP 408 or 504), so the +refusal does not hold the store's writer lock for an audit MAC; that row is logged and paged as +lost. Where it is tried, the 503 does not wait on it. Where it is tried it may still fail to write; [ADR 0217](adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md), *Open audit gaps*, states how, and what stays open. diff --git a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md index 066d225532..0b796aa1b2 100644 --- a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md +++ b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md @@ -1143,13 +1143,15 @@ session, approval, on SQLite, PostgreSQL and SQL Server): refusals write no row of their own: a second refusal on the same request inside the interval, by any operator; one whose attempt fell in an interval a failed or untried write already spent, though the append may work again by then; one whose slot the gate's own read-back after a failed - write spent, which tries the row though no caller was refused; and every one where Vault gave no - reply. Under `vault_transit` the audit append's MAC goes through Transit too, under the store's - writer lock, so where the Outage's error chains an `OSError` (a connection error or a timeout, - `TransitSealUnavailableError.unreachable`) the row is not tried, so the refusal holds no store - lock and no Transit thread; it is logged at ERROR and paged as lost. Where Vault replied with a - failure the row is tried, through the gate's shielded write, so a cancelled caller does not - drop it; it may still fail, and a Vault that stops replying between the check and the append + write spent, which tries the row though no caller was refused; and every one whose check met a + connection error, a timeout, or a gateway or server timeout reply (HTTP 408 or 504). Under + `vault_transit` the audit append's MAC goes through Transit too, under the store's writer lock, + so where the Outage's error is a connection error, a timeout, or a gateway or server timeout + reply (HTTP 408 or 504) (`TransitSealUnavailableError.unreachable`) the row is not tried, so the + refusal does not hold the store's writer lock for an audit MAC; it is logged at ERROR and paged + as lost. Where Vault replied with any other failure the row is tried, as a task the gate tracks + and its shutdown drain waits for, which the 503 does not wait on, so no caller drops it; it may + still fail, and a Vault that stops replying between the check and the append can still hold the lock until Transit's timeout. A failed or untried write is logged and paged as the gate's other soft rows are, under the key `approval::seal-check`. Its page, WARNING and 503 text no longer say the request was refused, that nothing was done, or that Vault diff --git a/messagefoundry/api/approvals.py b/messagefoundry/api/approvals.py index f355041cd9..88979309d7 100644 --- a/messagefoundry/api/approvals.py +++ b/messagefoundry/api/approvals.py @@ -51,7 +51,6 @@ from __future__ import annotations import asyncio -import contextlib import json import logging import math @@ -258,8 +257,9 @@ def _releasing_in_process(approval_id: str) -> bool: #: The audit action of the best-effort, throttled row, under the actor ``system``, that the gate #: writes when a Vault transit Outage leaves a request's seal unchecked (ADR 0217, the Outage row). -#: It names the request, not who was refused; it is not tried when Vault gave no reply, and may -#: fail to write when it is tried. Not ``integrity.*``: an Outage records no seal failure. +#: It names the request, not who was refused; it is not tried after a connection error, a timeout, +#: or a gateway or server timeout reply (HTTP 408 or 504), and may fail to write when it is tried. +#: Not ``integrity.*``: an Outage records no seal failure. APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION = "approval.seal_check_unavailable" #: Faults :meth:`ApprovalGate._read` raises as they are, because they name a defect in the read @@ -3268,11 +3268,12 @@ async def _verified(self, found: Any, *, report: bool = True) -> ApprovalRow | N await self._approval_seal_unverifiable(row.id, exc) return None except TransitSealUnavailableError as exc: - # ADR 0217, the Outage row: record no seal failure, page, write a best-effort, - # throttled system row where Vault replied, and answer 503. A read-back after a write + # ADR 0217, the Outage row: record no seal failure, page, start a best-effort, + # throttled system row unless the check was unreachable, and answer 503 without + # waiting on that row. A read-back after a write # or a release meets this too, so the text says only what was not checked, never what # was not done. - await self._approval_seal_outage(row.id, unreachable=exc.unreachable) + self._approval_seal_outage(row.id, unreachable=exc.unreachable) raise ApprovalError( 503, "an approval request's integrity seal could not be checked through Vault " @@ -3323,7 +3324,7 @@ async def _approval_seal_unverifiable( context="a request's integrity seal could not be verified", ) - async def _approval_seal_outage(self, approval_id: str, *, unreachable: bool) -> None: + def _approval_seal_outage(self, approval_id: str, *, unreachable: bool) -> None: """Report a Vault transit Outage met checking request ``approval_id``'s seal (ADR 0217, *The four answers*): a page under the shared ``authority-seal-transit`` subject, every time; a WARNING, throttled as :meth:`_read` throttles a store fault's, since the queue reads @@ -3335,10 +3336,13 @@ async def _approval_seal_outage(self, approval_id: str, *, unreachable: bool) -> failed audit write is logged and paged under its own key, not raised: during an Outage the append may fail too, and the 503 still stands. - When ``unreachable`` (Vault gave no reply, :attr:`TransitSealUnavailableError.unreachable`) - the row is not tried, and is logged and paged as lost, so this refusal holds no store lock - and no Transit thread. Otherwise the write runs through :meth:`_shielded`, so a cancelled - caller cannot drop it with no record. + When ``unreachable`` (a connection error, a timeout, or a gateway or server timeout reply + (HTTP 408 or 504), :attr:`TransitSealUnavailableError.unreachable`) the row is not tried, + and is logged and paged as lost, so this refusal does not wait on an audit append or hold + the store's writer lock for its MAC; its pages may still make Transit calls of their own + (see :meth:`_alert_lost_audit`). Otherwise the write is started as a task the gate tracks + in ``_inflight``, which :meth:`drain` waits for, and is not awaited: the 503 does not wait + on it, and no caller, cancelled or not, can drop it with no record. The text names what was not checked and no outcome, and never says Vault did not answer: this check also runs on the gate's read-back after a write or a release @@ -3364,12 +3368,13 @@ async def _approval_seal_outage(self, approval_id: str, *, unreachable: bool) -> alert_key = f"approval:{ref}:seal-check" if unreachable: # Under vault_transit the append's audit MAC is a Transit call made under the store's - # writer lock, so against a Vault that gave no reply it would hold that lock and a - # Transit thread until the same timeout again. The row is not tried: it is lost, and - # reported as the gate reports any lost row. + # writer lock, so against a Vault that the check could not reach it would hold that + # lock until the same timeout again. The row is not tried: it is lost, and reported as + # the gate reports any lost row. log.error( - "approval %s: %s, but its %s audit row was not tried, since Vault transit gave no " - "reply and the audit append's MAC goes through it. Lost detail: %s", + "approval %s: %s, but its %s audit row was not tried, since the Transit call " + "failed at the connection level or timed out and the audit append's MAC goes " + "through Transit. Lost detail: %s", ref, context, APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION, @@ -3377,23 +3382,25 @@ async def _approval_seal_outage(self, approval_id: str, *, unreachable: bool) -> ) self._alert_lost_audit(ref, APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION, key=alert_key) return - # Shielded, so a cancelled caller does not cancel the write with it: the write lands, or its - # failure is logged and paged by _record_audit_soft, or its own cancel is logged by the - # shield's orphan log. OperationInterrupted means the write itself was cancelled under a - # caller that was not, which the shield has logged; the caller's 503 still stands. - with contextlib.suppress(OperationInterrupted): - await self._shielded( - self._record_audit_soft( - ref, - APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION, - actor="system", - detail=detail, - client=None, - context=context, - alert_key=alert_key, - ), - approval_id, + # Started, not awaited, so the 503 does not wait on the append (on the restart reconcile's + # path that wait would sit under _owner_lock). Tracked in _inflight, as _shielded tracks + # its writes, so drain() waits for it and the loop's weak reference cannot drop it: the + # write lands, or its failure is logged and paged by _record_audit_soft, or a cancel or + # an escaped error is logged by _log_orphaned_write. + task = asyncio.ensure_future( + self._record_audit_soft( + ref, + APPROVAL_SEAL_CHECK_UNAVAILABLE_ACTION, + actor="system", + detail=detail, + client=None, + context=context, + alert_key=alert_key, ) + ) + self._inflight[task] = approval_id + task.add_done_callback(self._forget) + task.add_done_callback(lambda t: _log_orphaned_write(t, approval_id)) async def _approval_seal_failed(self, approval_id: str) -> None: """Report a request whose row failed its integrity seal (BACKLOG #2592): a WARNING, an diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index 9acad18e84..017f8c3a70 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -80,6 +80,7 @@ from messagefoundry.store.crypto import ( TransitSealRefused as TransitSealRefused, ) +from messagefoundry.store.keyprovider_vault import is_vault_timeout_reply from messagefoundry.subject_checksum import shorten_with_checksum log = logging.getLogger(__name__) @@ -487,13 +488,16 @@ class TransitSealUnavailableError(Exception): never row data, a token hash or Vault's text. Its ``args`` are empty, so copy and pickle rebuild it. - :attr:`unreachable` is True when the failed call never got a reply from Vault: the backend's - error chains an ``OSError``, as the Transit client's connection errors and timeouts are. A - caller that would make another Transit call only to record the refusal reads it to skip that - call rather than wait out the same timeout again (vault BACKLOG #8202).""" + :attr:`unreachable` is True when the failed call met a connection error, a timeout, or a + gateway or server timeout reply (HTTP 408 or 504): the backend's error chains an ``OSError``, + as the Transit client's connection errors and timeouts are, or an error + :func:`~messagefoundry.store.keyprovider_vault.is_vault_timeout_reply` reads as one of those + replies. A caller that would make another Transit call only to record the refusal reads it to + skip that call rather than wait out the same timeout again (vault BACKLOG #8202).""" - #: Whether Vault gave no reply at all (a connection error or a timeout); set per instance by the - #: sealer, False by default, so an instance built anywhere else claims nothing. + #: Whether the call met a connection error, a timeout, or a gateway or server timeout reply + #: (HTTP 408 or 504); set per instance by the sealer, False by default, so an instance built + #: anywhere else claims nothing. unreachable: bool = False def __str__(self) -> str: @@ -501,13 +505,16 @@ def __str__(self) -> str: def _vault_gave_no_reply(error: BaseException) -> bool: - """Whether ``error``'s cause chain holds an ``OSError``: a call that never got Vault's reply - (``requests``' connection errors and timeouts are ``OSError``), not one Vault answered with a + """Whether ``error``'s cause chain holds a connection error, a timeout, or a gateway or server + timeout reply (HTTP 408 or 504): an ``OSError`` (``requests``' connection errors and timeouts + are ``OSError``), or an error + :func:`~messagefoundry.store.keyprovider_vault.is_vault_timeout_reply` reads as one of those + replies (a gateway in front of a hung Vault answers so). Not one Vault answered with any other failure. Walks ``__cause__`` then ``__context__``, each link once.""" seen: set[int] = set() link: BaseException | None = error while link is not None and id(link) not in seen: - if isinstance(link, OSError): + if isinstance(link, OSError) or is_vault_timeout_reply(link): return True seen.add(id(link)) link = link.__cause__ if link.__cause__ is not None else link.__context__ diff --git a/scripts/security/crypto_inventory_check.py b/scripts/security/crypto_inventory_check.py index 7f0cbbf5d6..097c39f816 100644 --- a/scripts/security/crypto_inventory_check.py +++ b/scripts/security/crypto_inventory_check.py @@ -582,9 +582,12 @@ "messagefoundry/store/sealed_cache.py": frozenset({"messagefoundry.store.crypto"}), # BACKLOG #2592: row integrity seals. hmac = HMAC-SHA256 over a typed row encoding under a key # derived (HKDF, through the store.crypto seam) from the store key's authorization root; hashlib = - # the SHA-256 the HMAC runs over; compare_digest for the constant-time verify. + # the SHA-256 the HMAC runs over; compare_digest for the constant-time verify. Vault BACKLOG + # #8202: to tell a Transit seal Outage that met a gateway or server timeout reply (HTTP 408 or + # 504) from one Vault answered, it reads the error with keyprovider_vault's timeout-reply test; + # it makes no Vault call through that module. "messagefoundry/store/row_seal.py": frozenset( - {"hashlib", "hmac", "messagefoundry.store.crypto"} + {"hashlib", "hmac", "messagefoundry.store.crypto", "messagefoundry.store.keyprovider_vault"} ), # BACKLOG #2593: builds the AES-GCM associated data a queue payload cell is sealed under (the # row's routing fields) and opens the cell through the store cipher seam. No key of its own. diff --git a/tests/test_transit_approval_gate.py b/tests/test_transit_approval_gate.py index 2c5306efc1..100677386d 100644 --- a/tests/test_transit_approval_gate.py +++ b/tests/test_transit_approval_gate.py @@ -203,6 +203,8 @@ async def test_an_outage_writes_one_best_effort_row_per_request_and_pages_each_t } finally: backend.down = False + # The 503 does not wait on the row; the gate's drain does. + assert await gate.drain(_BOUND_SECONDS) == [] audited = await _rows(store, _OUTAGE_ACTION, "a-1") assert len(audited) == 1 assert audited[0]["actor"] == "system" @@ -231,6 +233,7 @@ async def test_an_outage_row_is_throttled_per_request_not_once_for_all( await gate.interrupt_stranded(approval_id, actor="op", actor_user_id="op-id") finally: backend.down = False + assert await gate.drain(_BOUND_SECONDS) == [] assert len(await _rows(store, _OUTAGE_ACTION, "a-1")) == 1 assert len(await _rows(store, _OUTAGE_ACTION, "a-2")) == 1 @@ -313,43 +316,57 @@ async def refuse(_action: str, **_kw: Any) -> None: assert refused.value.status == 503 finally: backend.down = False + assert await gate.drain(_BOUND_SECONDS) == [] assert sink.lost == [("approval:a-1:seal-check", _OUTAGE_ACTION)] class _HungBackend(FakeBackend): - """A Vault that accepts the call and never replies: the backend's verify ends only at its own - read timeout, as a ``CipherError`` chained from an ``OSError``, the form the Transit client - gives an unreachable Vault (``requests``' timeouts and connection errors are ``OSError``).""" + """A Vault whose verify ends with no reply that settles it: at the backend's own read timeout, + or with a gateway or load balancer in front answering 504 or 408 for it. The backend wraps + the Transit client's error in a ``CipherError``, as the real one does.""" def __init__(self) -> None: super().__init__() - self.hung = False + self.cause: BaseException | None = None def verify_seal_hmac(self, key_name: str, digest: bytes, mac: str) -> bool: - if self.hung: - try: - raise TimeoutError("synthetic: Vault did not reply before the read timeout") - except TimeoutError as exc: - raise CipherError("synthetic: Transit row seal verify failed") from exc + if self.cause is not None: + raise CipherError("synthetic: Transit row seal verify failed") from self.cause return super().verify_seal_hmac(key_name, digest, mac) +def _hung_cause(kind: str) -> BaseException: + """The Transit client's error for ``kind``. ``requests``' timeouts and connection errors are + ``OSError``; hvac raises a 504 or 408 reply as ``UnexpectedError``, carrying the status the + store's client records on it (``keyprovider_vault.is_vault_timeout_reply``).""" + if kind == "timeout": + return TimeoutError("synthetic: Vault did not reply before the read timeout") + exceptions = pytest.importorskip("hvac.exceptions", reason="needs the [vault] extra") + error: BaseException = exceptions.UnexpectedError("synthetic: the gateway timed out on Vault") + error.mefor_reply_status = int(kind.removeprefix("gateway-")) # type: ignore[attr-defined] + return error + + #: The proof bound: the 503 and a concurrent store write each finish well inside it. _BOUND_SECONDS = 2.0 +@pytest.mark.parametrize("kind", ["timeout", "gateway-504", "gateway-408"]) async def test_a_hung_vault_never_starts_the_append_and_pages_the_row_as_lost( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, kind: str ) -> None: - """The Lander's hold on vault BACKLOG #8202's rebuild, fix (1): under ``vault_transit`` the - audit append's MAC is itself a Transit call made under the store's writer lock, so an append - attempted while Vault does not reply would hold that lock and a Transit thread until Transit's - own timeout. Here the append stands in as a call that never returns, as it would against a - hung Vault. The gate must not start it: the 503 comes back inside the bound, a concurrent store - write completes inside it, and the row is reported lost through the existing ERROR and page.""" + """The Lander's holds on vault BACKLOG #8202's rebuild: under ``vault_transit`` the audit + append's MAC is itself a Transit call made under the store's writer lock, so an append attempted + while Vault does not reply would hold that lock until Transit's own timeout. A gateway in front + of a hung Vault answers 504 or 408, which is no settling reply either. Here the append, inside + the store's real writer lock, stands in as a MAC that does not return. The gate must not start + it: the 503 comes back inside the bound, a concurrent store write that needs the writer lock + completes inside it, and the row is reported lost through the existing ERROR and page.""" + cause = _hung_cause(kind) store = await MessageStore.open( tmp_path / "hung.db", cipher=make_cipher(generate_key(), write_v2=True) ) + release = asyncio.Event() try: backend = _HungBackend() store._row_sealer = TransitRowSealer(backend) @@ -365,22 +382,24 @@ async def test_a_hung_vault_never_starts_the_append_and_pages_the_row_as_lost( alert_sink=sink, ) started = asyncio.Event() + real_append = store._append_audit_row - async def hung_append(_action: str, **_kw: Any) -> None: + async def hung_append(action: str, **kw: Any) -> Any: + # Called by the real record_audit under the store's writer lock. started.set() - await asyncio.Event().wait() # never set: the append a hung Vault would never finish + await release.wait() + return await real_append(action, **kw) - monkeypatch.setattr(gate._store, "record_audit", hung_append) - backend.hung = True + monkeypatch.setattr(store, "_append_audit_row", hung_append) + backend.cause = cause with caplog.at_level(logging.ERROR, logger="messagefoundry.api.approvals"): try: with pytest.raises(ApprovalError) as refused: await asyncio.wait_for(gate.list_executing(), _BOUND_SECONDS) finally: - backend.hung = False + backend.cause = None assert refused.value.status == 503 - assert not started.is_set() - # A store write the hung append would have queued behind completes inside the bound. + # A store write that needs the writer lock the append would hold completes inside the bound. await asyncio.wait_for( store.create_pending_approval( approval_id="a-2", @@ -393,23 +412,30 @@ async def hung_append(_action: str, **_kw: Any) -> None: ), _BOUND_SECONDS, ) + assert not started.is_set() assert sink.lost == [("approval:a-1:seal-check", _OUTAGE_ACTION)] - assert any( - r.levelno == logging.ERROR and _OUTAGE_ACTION in r.getMessage() + errors = [ + r.getMessage() for r in caplog.records if r.name == "messagefoundry.api.approvals" - ) + and r.levelno == logging.ERROR + and _OUTAGE_ACTION in r.getMessage() + ] + assert len(errors) == 1 + assert "failed at the connection level or timed out" in errors[0] + assert "gave no reply" not in errors[0] finally: + release.set() await store.close() -async def test_a_cancel_during_the_outage_row_write_does_not_lose_it_silently( +async def test_the_503_does_not_wait_on_the_outage_row_and_drain_lands_it( transit: tuple[MessageStore, FakeBackend, Path], monkeypatch: pytest.MonkeyPatch ) -> None: - """The Lander's hold, fix (2): the caller of a refused request can be cancelled, by a request - timeout or a client that goes away, while the gate waits on the best-effort row. The write - must then finish on its own, as the gate's other shielded writes do, or be logged and paged; - it must not vanish with no record.""" + """The Lander's holds on vault BACKLOG #8202's rebuild: where Vault replied with a failure the + row is tried, but the 503 does not wait on it, since on the restart reconcile's path that wait + would sit under the gate's owner lock. The write runs as a task the gate tracks, so no caller, + cancelled or not, can drop it with no record, and :meth:`ApprovalGate.drain` waits for it.""" store, backend, path = transit await _executing(store, path, "a-1") store._row_sealer = TransitRowSealer(backend) # nothing cached @@ -426,13 +452,13 @@ async def slow_append(action: str, **kw: Any) -> None: monkeypatch.setattr(gate._store, "record_audit", slow_append) backend.down = True try: - caller = asyncio.create_task(gate.list_executing()) + with pytest.raises(ApprovalError) as refused: + await asyncio.wait_for(gate.list_executing(), _BOUND_SECONDS) + assert refused.value.status == 503 await asyncio.wait_for(entered.wait(), _BOUND_SECONDS) - caller.cancel() - with pytest.raises(asyncio.CancelledError): - await caller + assert list(gate._inflight.values()) == ["a-1"] finally: backend.down = False - release.set() + release.set() assert await gate.drain(_BOUND_SECONDS) == [] assert len(await _rows(store, _OUTAGE_ACTION, "a-1")) == 1 From b3896dc1200babaa01360fba19d166ede504e73a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 11:17:11 -0600 Subject: [PATCH 4/7] Outage row task: track it under the scrubbed id, and drain it in the tests that cause it Review round 1 on the repair of hold 7349008635 (vault BACKLOG #8202), two findings in this round's own code: - The seal-check row task is tracked in _inflight and handed to _log_orphaned_write under the scrubbed id, as every other log line in _approval_seal_outage uses: drain() and the orphan log print it, and it comes from a row whose seal went unchecked. - The two remaining tests in test_transit_approval_gate.py that drive an Outage through the gate drain it before reading the audit log or ending, since the row now lands after the 503. Verified-by: tests --- messagefoundry/api/approvals.py | 6 ++++-- tests/test_transit_approval_gate.py | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/messagefoundry/api/approvals.py b/messagefoundry/api/approvals.py index 88979309d7..2874ef8366 100644 --- a/messagefoundry/api/approvals.py +++ b/messagefoundry/api/approvals.py @@ -3398,9 +3398,11 @@ def _approval_seal_outage(self, approval_id: str, *, unreachable: bool) -> None: alert_key=alert_key, ) ) - self._inflight[task] = approval_id + # The scrubbed id, as every log line here uses: drain() and the orphan log print it, and + # it comes from a row whose seal went unchecked. + self._inflight[task] = ref task.add_done_callback(self._forget) - task.add_done_callback(lambda t: _log_orphaned_write(t, approval_id)) + task.add_done_callback(lambda t: _log_orphaned_write(t, ref)) async def _approval_seal_failed(self, approval_id: str) -> None: """Report a request whose row failed its integrity seal (BACKLOG #2592): a WARNING, an diff --git a/tests/test_transit_approval_gate.py b/tests/test_transit_approval_gate.py index 100677386d..639c76638a 100644 --- a/tests/test_transit_approval_gate.py +++ b/tests/test_transit_approval_gate.py @@ -162,6 +162,8 @@ async def test_an_outage_refuses_the_route_with_a_503_and_pages_without_a_seal_f assert refused.value.status == 503 assert refused.value.headers is not None and "Retry-After" in refused.value.headers assert pages == [TRANSIT_OUTAGE_SUBJECT] + # The best-effort row is written after the 503; let it land before reading the audit log. + assert await gate.drain(_BOUND_SECONDS) == [] assert await _rows(store, AUTHORITY_SEAL_UNVERIFIABLE_ACTION, "a-1") == [] assert await _rows(store, AUTHORITY_SEAL_FAILED_ACTION, "a-1") == [] assert _sql(path, "SELECT status FROM pending_approvals WHERE id=?", ("a-1",)) == [ @@ -262,6 +264,7 @@ async def test_an_outage_names_no_refusal_and_no_outcome( await gate.list_executing() finally: backend.down = False + assert await gate.drain(_BOUND_SECONDS) == [] assert len(reasons) == 1 warnings = [ r.getMessage() From 31f8d1af4f34c0ec0c720f7e5fed08ca2aa0f874 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 12:48:17 -0600 Subject: [PATCH 5/7] Approval gate docs: say which errors skip the outage row, and name the slow-reply lock hold These are the four text edits of Lander hold 7354966381 on PR 3526. SECURITY.md and the changelog fragment now say the row is skipped after any error that chains an OSError or an HTTP 408 or 504 reply, and ADR 0217 names the slow-reply writer-lock hold and the unpaged cancelled write. No code or tests change. Verified-by: tests --- changelog.d/8202-approval-seal-outage-row.security.md | 5 +++-- docs/SECURITY.md | 5 +++-- ...-ad-reconciler-ends-sessions-rather-than-holding.md | 10 ++++++---- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/changelog.d/8202-approval-seal-outage-row.security.md b/changelog.d/8202-approval-seal-outage-row.security.md index 73b2e1dab8..2e09db434a 100644 --- a/changelog.d/8202-approval-seal-outage-row.security.md +++ b/changelog.d/8202-approval-seal-outage-row.security.md @@ -3,8 +3,9 @@ "vault_transit"`, the approval gate's Outage at a request's seal check pages, logs and refuses as before, and also tries an `approval.seal_check_unavailable` row, without the 503 waiting on it. The row names the request, not who was refused, and may not be written: it is not tried after - a connection error, a timeout, or a gateway or server timeout reply (HTTP 408 or 504), at most one - is tried per request per interval, and the write can fail. + an error that chains an `OSError` (at least a connection error, a timeout, a TLS or certificate + refusal, a missing CA file, or a reply the HTTP client could not parse) or a gateway or server + timeout reply (HTTP 408 or 504), at most one is tried per request per interval, and the write can fail. A row not written is logged at ERROR and paged as a lost audit row. The page, log line and 503 text no longer say the request was refused, that nothing was done, or that Vault did not answer. (`BACKLOG #8202`) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 731e285734..6ac3bedc04 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -3403,8 +3403,9 @@ throttled `approval.seal_check_unavailable` row under the actor `system` (vault went unchecked, not who was refused, from where, or for which act. A route that meets it answers **503** with `Retry-After`; the gate's own read-back after a failed write, and the restart reconcile, meet the same check, try the row and answer nobody. The row is not tried when the check -met a connection error, a timeout, or a gateway or server timeout reply (HTTP 408 or 504), so the -refusal does not hold the store's writer lock for an audit MAC; that row is logged and paged as +met an error that chains an `OSError` (at least a connection error, a timeout, a TLS or certificate +refusal, a missing CA file, or a reply the HTTP client could not parse) or a gateway or server +timeout reply (HTTP 408 or 504), so the refusal does not hold the store's writer lock for an audit MAC; that row is logged and paged as lost. Where it is tried, the 503 does not wait on it. Where it is tried it may still fail to write; [ADR 0217](adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md), diff --git a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md index 0b796aa1b2..46d3db42f6 100644 --- a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md +++ b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md @@ -1149,11 +1149,13 @@ session, approval, on SQLite, PostgreSQL and SQL Server): so where the Outage's error is a connection error, a timeout, or a gateway or server timeout reply (HTTP 408 or 504) (`TransitSealUnavailableError.unreachable`) the row is not tried, so the refusal does not hold the store's writer lock for an audit MAC; it is logged at ERROR and paged - as lost. Where Vault replied with any other failure the row is tried, as a task the gate tracks + as lost. Otherwise the row is tried, as a task the gate tracks and its shutdown drain waits for, which the 503 does not wait on, so no caller drops it; it may - still fail, and a Vault that stops replying between the check and the append - can still hold the lock until Transit's timeout. A failed or untried write is logged and paged - as the gate's other soft rows are, under the key `approval::seal-check`. Its page, + still fail, and a Vault that replies slowly with a failure, or stops replying between the check + and the append, can hold the store's writer lock until Transit's timeout, at most once per request + per throttle interval; before this change no append ran on this path. A failed or untried write + is logged and paged as the gate's other soft rows are, under the key `approval::seal-check`. + A write cancelled when the loop stops is logged at ERROR, not paged. Its page, WARNING and 503 text no longer say the request was refused, that nothing was done, or that Vault did not answer, as (c) item 4 requires (item 145), since the same check runs on the gate's read-back after a write or a release. Gaps (1) and (2) are still open, and so is at least the From dc770491b85049f83dab672a3a4226ccda03c833 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 13:12:06 -0600 Subject: [PATCH 6/7] Approval gate docs: the ADR names the same skip cases, and the lock hold is not bounded by the Transit timeout These are the text edits from the Lander's second repair note on PR 3526. They change ADR 0217, docs/SECURITY.md and the 8202 changelog fragment only. Verified-by: tests --- .../8202-approval-seal-outage-row.security.md | 5 +++-- docs/SECURITY.md | 5 +++-- ...econciler-ends-sessions-rather-than-holding.md | 15 +++++++++------ 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/changelog.d/8202-approval-seal-outage-row.security.md b/changelog.d/8202-approval-seal-outage-row.security.md index 2e09db434a..bf75c99f27 100644 --- a/changelog.d/8202-approval-seal-outage-row.security.md +++ b/changelog.d/8202-approval-seal-outage-row.security.md @@ -3,8 +3,9 @@ "vault_transit"`, the approval gate's Outage at a request's seal check pages, logs and refuses as before, and also tries an `approval.seal_check_unavailable` row, without the 503 waiting on it. The row names the request, not who was refused, and may not be written: it is not tried after - an error that chains an `OSError` (at least a connection error, a timeout, a TLS or certificate - refusal, a missing CA file, or a reply the HTTP client could not parse) or a gateway or server + an error that chains an `OSError` (at least a connection error, a timeout, a TLS handshake or + certificate-verification failure, a missing CA file, or a reply head the HTTP client could not + parse) or a gateway or server timeout reply (HTTP 408 or 504), at most one is tried per request per interval, and the write can fail. A row not written is logged at ERROR and paged as a lost audit row. The page, log line and 503 text no longer say the request was refused, that nothing was done, or that Vault did not diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 6ac3bedc04..9c0778a408 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -3403,8 +3403,9 @@ throttled `approval.seal_check_unavailable` row under the actor `system` (vault went unchecked, not who was refused, from where, or for which act. A route that meets it answers **503** with `Retry-After`; the gate's own read-back after a failed write, and the restart reconcile, meet the same check, try the row and answer nobody. The row is not tried when the check -met an error that chains an `OSError` (at least a connection error, a timeout, a TLS or certificate -refusal, a missing CA file, or a reply the HTTP client could not parse) or a gateway or server +met an error that chains an `OSError` (at least a connection error, a timeout, a TLS handshake or +certificate-verification failure, a missing CA file, or a reply head the HTTP client could not +parse) or a gateway or server timeout reply (HTTP 408 or 504), so the refusal does not hold the store's writer lock for an audit MAC; that row is logged and paged as lost. Where it is tried, the 503 does not wait on it. Where it is tried it may still fail to write; diff --git a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md index 46d3db42f6..9659c8fbd8 100644 --- a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md +++ b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md @@ -1143,17 +1143,20 @@ session, approval, on SQLite, PostgreSQL and SQL Server): refusals write no row of their own: a second refusal on the same request inside the interval, by any operator; one whose attempt fell in an interval a failed or untried write already spent, though the append may work again by then; one whose slot the gate's own read-back after a failed - write spent, which tries the row though no caller was refused; and every one whose check met a - connection error, a timeout, or a gateway or server timeout reply (HTTP 408 or 504). Under + write spent, which tries the row though no caller was refused; and every one whose check met an + error that chains an `OSError` (at least a connection error, a timeout, a TLS handshake or + certificate-verification failure, a missing CA file, or a reply head the HTTP client could not + parse) or a gateway or server timeout reply (HTTP 408 or 504). Under `vault_transit` the audit append's MAC goes through Transit too, under the store's writer lock, - so where the Outage's error is a connection error, a timeout, or a gateway or server timeout - reply (HTTP 408 or 504) (`TransitSealUnavailableError.unreachable`) the row is not tried, so the + so where the Outage's error is one of those (`TransitSealUnavailableError.unreachable`) the row + is not tried, so the refusal does not hold the store's writer lock for an audit MAC; it is logged at ERROR and paged as lost. Otherwise the row is tried, as a task the gate tracks and its shutdown drain waits for, which the 503 does not wait on, so no caller drops it; it may still fail, and a Vault that replies slowly with a failure, or stops replying between the check - and the append, can hold the store's writer lock until Transit's timeout, at most once per request - per throttle interval; before this change no append ran on this path. A failed or untried write + and the append, can hold the store's writer lock for as long as the Transit call takes, which Transit's + timeout does not bound (`TRANSIT_REQUEST_TIMEOUT_S`), once per request per throttle interval in + each gate; before this change no append ran on this path. A failed or untried write is logged and paged as the gate's other soft rows are, under the key `approval::seal-check`. A write cancelled when the loop stops is logged at ERROR, not paged. Its page, WARNING and 503 text no longer say the request was refused, that nothing was done, or that Vault From 08239c12f90f538df83a3ec818d6eb1c6c8559e0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 13:38:37 -0600 Subject: [PATCH 7/7] Approval gate docs: name the unpaged losses and the throttle's forgotten keys The changelog's lost-row sentence now names the two cases that are not paged: a write cancelled when the loop stops, and a refusal the throttle skips. ADR 0217 no longer reads the per-request throttle as a cap on how often the writer lock is held: the throttle is per approval id and forgets the oldest past SEAL_FAILURE_TRACK_MAX, so several refused requests can each hold the lock in turn. Docs only; the text is the Lander's hold on PR 3526. BACKLOG #8202 Verified-by: tests --- changelog.d/8202-approval-seal-outage-row.security.md | 4 +++- ...d-the-ad-reconciler-ends-sessions-rather-than-holding.md | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/changelog.d/8202-approval-seal-outage-row.security.md b/changelog.d/8202-approval-seal-outage-row.security.md index bf75c99f27..e7d83922e8 100644 --- a/changelog.d/8202-approval-seal-outage-row.security.md +++ b/changelog.d/8202-approval-seal-outage-row.security.md @@ -7,6 +7,8 @@ certificate-verification failure, a missing CA file, or a reply head the HTTP client could not parse) or a gateway or server timeout reply (HTTP 408 or 504), at most one is tried per request per interval, and the write can fail. - A row not written is logged at ERROR and paged as a lost audit row. The page, log line and 503 + A row that is not tried after such an error, or that is tried and fails, is logged at ERROR and + paged as a lost audit row. A write cancelled when the engine's loop stops is logged at ERROR and + not paged, and a refusal the throttle skips logs and pages no row of its own. The page, log line and 503 text no longer say the request was refused, that nothing was done, or that Vault did not answer. (`BACKLOG #8202`) diff --git a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md index 9659c8fbd8..a2948899f4 100644 --- a/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md +++ b/docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md @@ -1155,8 +1155,10 @@ session, approval, on SQLite, PostgreSQL and SQL Server): and its shutdown drain waits for, which the 503 does not wait on, so no caller drops it; it may still fail, and a Vault that replies slowly with a failure, or stops replying between the check and the append, can hold the store's writer lock for as long as the Transit call takes, which Transit's - timeout does not bound (`TRANSIT_REQUEST_TIMEOUT_S`), once per request per throttle interval in - each gate; before this change no append ran on this path. A failed or untried write + timeout does not bound (`TRANSIT_REQUEST_TIMEOUT_S`), at most once per request per throttle + interval in each gate while that gate's throttle still remembers the request (it forgets the + oldest past `SEAL_FAILURE_TRACK_MAX` requests), so several refused requests can each hold it in + turn; before this change no append ran on this path. A failed or untried write is logged and paged as the gate's other soft rows are, under the key `approval::seal-check`. A write cancelled when the loop stops is logged at ERROR, not paged. Its page, WARNING and 503 text no longer say the request was refused, that nothing was done, or that Vault