From fdd1dcaf3e8c987c2d2bbb8c5f12622b17276cd6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 29 Nov 2026 20:36:53 -0600 Subject: [PATCH 1/7] Audit an approval request a Vault transit Outage refuses ApprovalGate._approval_seal_outage now pages and then writes a soft authority.seal_unavailable audit row for each refused call, not an integrity.* action, so an Outage still records no seal failure (vault BACKLOG #8202 item 146). Its reason says only that the seal could not be made or checked through Vault transit, and the 503 no longer says that nothing was done, since the check also runs after a write (item 145). The 503's Retry-After is the shared TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS; the gate's duplicate constant is gone (item 153). Verified-by: tests --- messagefoundry/api/approvals.py | 51 ++++++++++++++++++-------- messagefoundry/store/row_seal.py | 4 ++ tests/test_transit_approval_gate.py | 57 +++++++++++++++++++++++++++-- 3 files changed, 92 insertions(+), 20 deletions(-) diff --git a/messagefoundry/api/approvals.py b/messagefoundry/api/approvals.py index fcbf460ad8..780de7517f 100644 --- a/messagefoundry/api/approvals.py +++ b/messagefoundry/api/approvals.py @@ -85,10 +85,12 @@ from messagefoundry.store.base import Store from messagefoundry.store.row_seal import ( APPROVAL_KIND, + TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, RowSealError, SealFailureThrottle, TransitSealUnavailableError, TransitSealUnverifiableError, + seal_row_ref, ) from messagefoundry.store.store import ( ANY_CLAIM_OWNER, @@ -98,6 +100,7 @@ UserRecord, approval_seal_ok_async, ) +from messagefoundry.transports.http_listener import TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS log = logging.getLogger(__name__) @@ -254,10 +257,6 @@ 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 - #: 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). _READ_DEFECTS: tuple[type[Exception], ...] = ( @@ -3260,13 +3259,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: refuse the request, record no seal failure, page, and audit + # the refused call itself (vault BACKLOG #8202 item 146). The Retry-After is the shared + # temporary-refusal value (item 153). + 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)}, + "Vault transit could not check this approval request's integrity seal; try again" + " once it answers", + headers={"Retry-After": str(TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS)}, ) from exc if held: return row @@ -3312,20 +3313,38 @@ 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, then a + soft :data:`~messagefoundry.store.row_seal.TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION` row for the + refused call (vault BACKLOG #8202 item 146). Neither records a seal failure, so no + ``integrity.*`` action is written. The row is not throttled; the WARNING is, as + :meth:`_read` throttles a store fault's, since the queue reads on every page load. + + The reason says only that the seal could not be made or checked (ADR 0217 (c) step 4, + item 145): this check also runs where an operation or a write may already have run, at + least in :meth:`_read_back_request`, so it never says that nothing was done.""" + ref = seal_row_ref(APPROVAL_KIND, approval_id) 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 made or checked through" + f" Vault transit (approval {ref})" ) if self._read_faults_reported.due("transit-outage"): log.warning("%s", reason) + # The page first, so an audit write that raises a defect cannot skip it. pager = getattr(self._store, "seal_pager", None) if callable(pager): pager().outage(reason) + await self._record_audit_soft( + ref, + TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, + actor="system", + detail=json.dumps( + {"kind": APPROVAL_KIND, "approval_id": approval_id, "during": "approval"} + ), + client=None, + context="a request's integrity seal could not be made or checked through Vault transit", + ) 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..b8d9267888 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -1468,6 +1468,10 @@ async def probe_row_sealer_at_start(sealer: AnyRowSealer | None) -> None: #: The page an Outage on an authority row raises (ADR 0217, *The four answers*). TRANSIT_OUTAGE_SUBJECT: Final = "authority-seal-transit" +#: The audit action a request refused on an Outage writes where the audit append still works (ADR +#: 0217, the Outage row; vault BACKLOG #8202 items 146 and 161). Not ``integrity.*``: an Outage +#: records no seal failure. +TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION: Final = "authority.seal_unavailable" #: The page a Forged authority row raises: ``AUTHORITY_SEAL_SUBJECT`` in ``pipeline/alerts.py``, #: which the store may not import, so a test pins the two equal (ADR 0217, *The four answers*). AUTHORITY_SEAL_FAILED_SUBJECT: Final = "authority-seal" diff --git a/tests/test_transit_approval_gate.py b/tests/test_transit_approval_gate.py index 8d5b94dd81..d52affddc7 100644 --- a/tests/test_transit_approval_gate.py +++ b/tests/test_transit_approval_gate.py @@ -6,6 +6,7 @@ from __future__ import annotations +import json import sqlite3 from collections.abc import AsyncIterator from pathlib import Path @@ -13,6 +14,7 @@ import pytest +from messagefoundry.api import approvals as approvals_module from messagefoundry.api.approvals import ApprovalError, ApprovalGate from messagefoundry.auth.permissions import Permission from messagefoundry.auth.service import ( @@ -22,11 +24,13 @@ from messagefoundry.config.settings import ApprovalsSettings from messagefoundry.store.crypto import generate_key, make_cipher from messagefoundry.store.row_seal import ( + TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, TRANSIT_OUTAGE_SUBJECT, UNVERIFIABLE_SUBJECT_PREFIX, 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,13 +140,18 @@ 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_audits_the_refusal_and_records_no_seal_failure( transit: tuple[MessageStore, FakeBackend, Path], route: str ) -> None: + """Vault BACKLOG #8202 items 146, 145 and 153: the Outage refusal writes its own audit row, + once per refused call, under an action that is not a seal failure; its reason and its 503 never + say the request was refused or that nothing was done; and its ``Retry-After`` is the shared + temporary-refusal value.""" store, backend, path = transit await _executing(store, path, "a-1") store._row_sealer = TransitRowSealer(backend) # nothing cached - pages = _arm(store) + pages: list[tuple[str, str]] = [] + store.seal_pager().arm(lambda subject, reason: pages.append((subject, reason))) gate = _gate(store) backend.down = True @@ -155,10 +164,50 @@ async def test_an_outage_refuses_the_route_with_a_503_and_pages_without_an_audit finally: backend.down = False assert refused.value.status == 503 - assert refused.value.headers is not None and "Retry-After" in refused.value.headers - assert pages == [TRANSIT_OUTAGE_SUBJECT] + assert refused.value.headers == {"Retry-After": str(TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS)} + assert "nothing was done" not in str(refused.value.detail) + assert [subject for subject, _ in pages] == [TRANSIT_OUTAGE_SUBJECT] + reason = pages[0][1] + assert "could not be made or checked through Vault transit" in reason + assert "refused" not in reason and "nothing was done" not in reason + refusals = await _rows(store, TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, "a-1") + assert len(refusals) == 1 + assert json.loads(str(refusals[0]["detail"])) == { + "kind": "approval", + "approval_id": "a-1", + "during": "approval", + } + assert not TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION.startswith("integrity.") 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",)) == [ ("executing",) ] + + +async def test_each_outage_refused_call_writes_its_own_audit_row( + transit: tuple[MessageStore, FakeBackend, Path], +) -> None: + """Vault BACKLOG #8202 item 146: the refused request itself is audited, so a second refused + call writes a second row rather than riding on a throttle.""" + store, backend, path = transit + await _executing(store, path, "a-1") + store._row_sealer = TransitRowSealer(backend) + gate = _gate(store) + + backend.down = True + try: + for _ in range(2): + with pytest.raises(ApprovalError): + await gate.interrupt_stranded("a-1", actor="op", actor_user_id="op-id") + finally: + backend.down = False + assert len(await _rows(store, TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, "a-1")) == 2 + + +def test_the_outage_retry_after_has_one_source() -> None: + """Vault BACKLOG #8202 item 153: the gate keeps no Retry-After constant of its own beside the + shared ``TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS``.""" + assert not hasattr(approvals_module, "_TRANSIT_OUTAGE_RETRY_AFTER_SECONDS") + shared = vars(approvals_module).get("TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS") + assert shared is TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS From c90a8bb3cd0b0aa3222707dc47bdd546347d7ce1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 29 Nov 2026 20:43:17 -0600 Subject: [PATCH 2/7] Answer and report every seal refusal type at the API backstop The API's seal backstop in api/auth_routes.py was registered for RowSealError alone and only logged. It is now registered for RowSealError, RowSealUnverifiableError, TransitSealUnverifiableError and TransitSealUnavailableError (ADR 0217 (c) item 3; vault BACKLOG #8202 item 161). Before it answers it pages through the store's SealPager and writes a soft audit row under the cause's own action: a Forged or Unverifiable row once per report interval per row, an Outage on every refused request under authority.seal_unavailable, with no seal failure. Forged keeps its 409 and text; Unverifiable answers 409 with ADR 0217 (a)'s recovery text; an Outage answers 503 with Retry-After. ADR 0217 notes gap (3) closed and the backstop built for those types, and a changelog fragment says so. The crypto inventory lists the new seal_row_digest use, an unkeyed SHA-256 throttle key held in memory. Verified-by: tests --- .../8202-seal-refusal-audit.security.md | 8 + ...ciler-ends-sessions-rather-than-holding.md | 18 +- messagefoundry/api/auth_routes.py | 200 ++++++++++++++++-- scripts/security/crypto_inventory_check.py | 10 +- tests/test_api_auth.py | 96 +++++++++ 5 files changed, 313 insertions(+), 19 deletions(-) create mode 100644 changelog.d/8202-seal-refusal-audit.security.md diff --git a/changelog.d/8202-seal-refusal-audit.security.md b/changelog.d/8202-seal-refusal-audit.security.md new file mode 100644 index 0000000000..a5015f1599 --- /dev/null +++ b/changelog.d/8202-seal-refusal-audit.security.md @@ -0,0 +1,8 @@ +- **A request a Vault transit Outage refuses is audited, and the API answers every seal refusal + type.** The approval gate writes an `authority.seal_unavailable` audit row, not a seal failure, + for each request it refuses on an Outage, and its page no longer says that nothing was done. + The API's seal backstop now answers the Unverifiable and Outage refusal types as well as a + Forged row, with a 409 or a 503 and `Retry-After` in place of the generic 500, and pages and + audits the refusal before it answers. See + [ADR 0217](../docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md). + (`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 901c3a67da..723a1d0496 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). *(Note 2026-11-29, vault BACKLOG #8202 item 146: the gate now writes an +`authority.seal_unavailable` row for each request it refuses on an Outage at +`ApprovalGate._verified`, so this correction no longer holds for that path; gap (3) says so.)* 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 @@ -1127,7 +1129,10 @@ session, approval, on SQLite, PostgreSQL and SQL Server): claim: an Unverifiable answer there goes to `ApprovalGate._store_fault`, which answers 503 and pages `audit_write_failed`; no `integrity.authority_seal_unverifiable` row is written. (3) A request refused by an Outage at `ApprovalGate._verified`: `_approval_seal_outage` pages and - writes no row. The owner ruled on 2026-11-11, in the Lander's session, that this ADR names them + writes no row. *(Note 2026-11-29, vault BACKLOG #8202 item 146: gap (3) is closed. + `_approval_seal_outage` now also writes a soft `authority.seal_unavailable` row, not an + `integrity.*` action, for each refused call, and its reason no longer says the request was + refused or that nothing was done (item 145).)* 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). - **Open audit gaps, extended 2026-11-11.** The three paths above are not the whole list. At least @@ -1173,7 +1178,14 @@ session, approval, on SQLite, PostgreSQL and SQL Server): page reaches no sink either. Beneath all of these, (c) item 2's catch census test, (c) item 3's API backstop for both refusal types, and *The four answers*' "The API answers an Outage with HTTP 503 and `Retry-After`" are not yet built on every path: a refusal no caller maps - reaches the engine's generic handler as a 500. The sign-in audit actions this ADR names, + reaches the engine's generic handler as a 500. *(Note 2026-11-29, vault BACKLOG #8202 item 161: + the API backstop in `api/auth_routes.py` is now registered for `RowSealError`, + `RowSealUnverifiableError`, `TransitSealUnverifiableError` and `TransitSealUnavailableError`. It + pages and soft-audits before it answers, a Forged or Unverifiable row at most once per report + interval and an Outage on every refused request, so a refusal of those types that an HTTP route lets + escape no longer reaches the generic 500. A refusal another type carries, such as the + `ApprovalError` of item 155, still can, and the catch census test and the CLI's handler are still + not built.)* The sign-in audit actions this ADR names, `auth.login_refused_unavailable` in the Outage row and in (e), `auth.login_refused_unverifiable` in (e), and the audit rows (e)'s *Control kept* and *The refusal cache* promise a sign-in refusal writes, are slice 2's sign-in refusals, which the 2026-11-08 build status line lists as not diff --git a/messagefoundry/api/auth_routes.py b/messagefoundry/api/auth_routes.py index c1ab3a71f5..0ec2efbfe8 100644 --- a/messagefoundry/api/auth_routes.py +++ b/messagefoundry/api/auth_routes.py @@ -147,6 +147,7 @@ from messagefoundry.auth.permissions import CustomRoleError from messagefoundry.auth.policy import BreachCorpusUnavailable from messagefoundry.auth.service import ( + AUTHORITY_SEAL_FAILED_ACTION, ENROL_AUTHENTICATOR_FIRST, STEP_UP_ACTION_ADMIN_ENROLMENT_CODE_ISSUE, STEP_UP_ACTION_ADMIN_ENROLMENT_CODE_REVOKE, @@ -184,10 +185,22 @@ read_user_or_unreadable, ) from messagefoundry.auth.tokens import hash_token +from messagefoundry.controlchars import scrub_log_argument from messagefoundry.credential import constant_time_equal from messagefoundry.spreadsheet import SPREADSHEET_FORMULA_TRIGGERS, spreadsheet_safe -from messagefoundry.store.row_seal import RowSealError, TransitSealUnavailableError +from messagefoundry.store.row_seal import ( + TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, + UNVERIFIABLE_SUBJECT_PREFIX, + RowSealError, + RowSealUnverifiableError, + SealFailureThrottle, + TransitSealUnavailableError, + TransitSealUnverifiableError, + seal_row_digest, + seal_row_ref, +) from messagefoundry.store.store import ( + AUTHORITY_SEAL_UNVERIFIABLE_AUDIT_ACTION, SessionRecord, UnknownRoleError, UserRecord, @@ -393,6 +406,112 @@ def _seal_outage_503() -> HTTPException: ) +#: The seal refusal types the API's backstop answers (ADR 0217 (c) item 3; vault BACKLOG #8202 item +#: 161): Forged (``RowSealError``), both Unverifiable types and the Outage. Every distinct class is +#: named, since the Unverifiable and Outage types are siblings of ``RowSealError``, never subclasses. +_SEAL_BACKSTOP_TYPES: tuple[type[Exception], ...] = ( + RowSealError, + RowSealUnverifiableError, + TransitSealUnverifiableError, + TransitSealUnavailableError, +) + + +class _SealBackstop: + """What the API's seal backstop reports and answers for one refusal no route answered.""" + + __slots__ = ("action", "answer", "cause", "detail", "kind", "reason", "subject") + + def __init__( + self, + cause: str, + *, + kind: str, + subject: str, + action: str, + detail: dict[str, object], + reason: str, + answer: HTTPException, + ) -> None: + self.cause = cause + self.kind = kind + self.subject = subject + self.action = action + self.detail = detail + self.reason = reason + self.answer = answer + + +def _seal_backstop(exc: Exception, route: str) -> _SealBackstop: + """The report and the answer for seal refusal ``exc`` that reached the API's backstop while + answering ``route`` (ADR 0217, *The four answers* and (c) items 3 and 4). A Forged row answers + 409 with ``main``'s fixed text; an Unverifiable one 409 with (a)'s recovery text, never + "forged"; an Outage 503 with ``Retry-After``, worded as the seal that "could not be made or + checked". A row is named only by its bounded ref (:func:`seal_row_ref`), never a row value.""" + if isinstance(exc, TransitSealUnavailableError): + return _SealBackstop( + "outage", + kind="", + subject="", + action=TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, + detail={"during": "api", "route": route}, + reason=( + f"a row seal could not be made or checked through Vault transit while the API" + f" answered {route}" + ), + answer=_seal_outage_503(), + ) + if isinstance(exc, RowSealUnverifiableError | TransitSealUnverifiableError): + subject = exc.subject if isinstance(exc, RowSealUnverifiableError) else "" + kind = scrub_log_argument(str(exc.kind)) + ref = seal_row_ref(kind, subject) if subject else "" + return _SealBackstop( + "unverifiable", + kind=kind, + subject=subject, + action=AUTHORITY_SEAL_UNVERIFIABLE_AUDIT_ACTION, + detail={ + "kind": kind, + "ref": ref, + "during": "api", + "route": route, + "stored_version": exc.stored_version, + "probe_version": exc.probe_version, + }, + reason=( + f"a stored {kind} record's integrity seal could not be verified by Vault transit" + f" while the API answered {route}" + (f" ({kind} {ref})" if ref else "") + ), + answer=HTTPException( + status.HTTP_409_CONFLICT, + f"a stored {kind} record's integrity seal could not be verified by Vault transit," + " so the request was refused. The seal may be planted: check that Vault is healthy" + " and that every node holds the audit key's latest version, then retry; a record" + " that still does not verify is untrusted and is re-created from an authoritative" + " source, never from its stored values", + ), + ) + assert isinstance(exc, RowSealError) + kind = scrub_log_argument(str(exc.kind)) + subject = exc.subject + ref = seal_row_ref(kind, subject) if subject else "" + return _SealBackstop( + "forged", + kind=kind, + subject=subject, + action=AUTHORITY_SEAL_FAILED_ACTION, + detail={"kind": kind, "ref": ref, "during": "api", "route": route}, + reason=( + f"a stored {kind} record failed its integrity check while the API answered {route}" + + (f" ({kind} {ref})" if ref else "") + ), + answer=HTTPException( + status.HTTP_409_CONFLICT, + f"a stored {exc.kind} record fails its integrity check, so the request was refused", + ), + ) + + async def _checked_user(service: AuthService, user_id: str) -> VerifiedUser: """The account an admin route reads, its record checked against its seal (BACKLOG #5520), or the route's refusal: 404 when no row is there, 423 when the row's record fails its check, with @@ -688,27 +807,80 @@ async def _repeated_credential(request: Request, exc: Exception) -> Response: app.add_exception_handler(RepeatedCredentialError, _repeated_credential) + # One per app: a Forged or Unverifiable row the backstop meets is reported at most once per + # SEAL_FAILURE_REPORT_INTERVAL_SECONDS, keyed by cause and the SHA-256 of the kind and the + # whole ref, so one cause never holds back the other's report (ADR 0217). + seal_reports = SealFailureThrottle() + async def _row_seal_refused(request: Request, exc: Exception) -> Response: # BACKLOG #2592: the store refused a row that fails its integrity check. A write helper # meets it when the row's seal does not verify, and wrote nothing. Since BACKLOG #5505 a # raw read meets it when a cell the read parses does not parse. So the texts name # neither a write nor a change. (A supersession's read-back refusal, RevokedRowSealError, is - # answered in the service and does not reach here.) A 409 with a fixed text, never the row and never a 500. Logged with the - # row's kind, since this path does not pass the service loader that audits and alerts. - assert isinstance(exc, RowSealError) - _log.warning( - "a stored %s row failed its integrity check and was refused (BACKLOG #2592, #5505)", - exc.kind, - ) - return await http_exception_handler( - request, - HTTPException( - status.HTTP_409_CONFLICT, - f"a stored {exc.kind} record fails its integrity check, so the request was refused", + # answered in the service and does not reach here.) A fixed text, never the row and never + # a 500. + # + # Vault BACKLOG #8202 item 161, ADR 0217 (c) item 3: this is the API's backstop for every + # seal refusal type no route answered, the Unverifiable and Outage types as well as Forged, + # and it reports before it answers. A Forged or Unverifiable refusal is logged, paged and + # audited under its own action, throttled per row; an Outage pages and writes a + # TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION row for each refused request, and records no seal + # failure. The code that raised may have reported the same refusal already, so a refusal + # can be reported twice; the backstop never reports less than the raising site did. + assert isinstance(exc, _SEAL_BACKSTOP_TYPES) + route = str(getattr(request.scope.get("route"), "path", "") or "an API route") + refusal = _seal_backstop(exc, route) + if refusal.cause == "outage": + report = True + logged = seal_reports.due(("outage", route)) + else: + report = seal_reports.due( + (refusal.cause, seal_row_digest(refusal.kind, refusal.subject)) + ) + logged = report + if logged: + _log.warning("%s (BACKLOG #2592, #5505)", refusal.reason) + if report: + await _report_seal_refusal(request, refusal) + return await http_exception_handler(request, refusal.answer) + + async def _report_seal_refusal(request: Request, refusal: _SealBackstop) -> None: + """Page, then audit softly, one refusal the backstop answers. Never raises, so the + refusal's own answer always goes out. With no auth service attached there is no store to + audit to or pager to page through, and the log line is the only record.""" + auth: AuthService | None = getattr(request.app.state, "auth", None) + if auth is None: + return + store = auth.store + pager = getattr(store, "seal_pager", None) + if callable(pager): + try: + seal_pager = pager() + if refusal.cause == "outage": + seal_pager.outage(refusal.reason) + elif refusal.cause == "forged": + seal_pager.forged(refusal.reason) + elif refusal.subject: + seal_pager.unverifiable(refusal.kind, refusal.subject, refusal.reason) + else: + seal_pager.page(f"{UNVERIFIABLE_SUBJECT_PREFIX}:*", refusal.reason) + except Exception as exc: # noqa: BLE001 - a page failure must never replace the answer + _log.warning("the API's seal refusal page failed: %s", type(exc).__name__) + client = client_ip(request) + await write_audit_soft( + lambda: store.record_audit( + refusal.action, detail=json.dumps(refusal.detail), client=client ), + log=_log, + message="the %s audit row for a seal refusal the API answered could not be written", + args=(refusal.action,), + # No defect raises: the refusal's own answer must still go out. + errors=(Exception,), + defects=(), ) - app.add_exception_handler(RowSealError, _row_seal_refused) + for refusal_type in _SEAL_BACKSTOP_TYPES: + app.add_exception_handler(refusal_type, _row_seal_refused) # --- authentication ------------------------------------------------------ @app.get("/auth/providers", response_model=ProvidersInfo) diff --git a/scripts/security/crypto_inventory_check.py b/scripts/security/crypto_inventory_check.py index 7f0cbbf5d6..3a32578b06 100644 --- a/scripts/security/crypto_inventory_check.py +++ b/scripts/security/crypto_inventory_check.py @@ -2171,9 +2171,15 @@ # owns no key and decides no TLS policy: the test that mints the throwaway certificate does. "harness/sinks/email.py": frozenset({"tls_context:.wrap_socket()"}), # BACKLOG #1167 (ASVS 11.2.4): both session-list routes flag the caller's own session by a - # constant-time compare of two token hashes. + # constant-time compare of two token hashes. Vault BACKLOG #8202 item 161: the seal refusal + # backstop keys its report throttle by seal_row_digest, an unkeyed SHA-256 of a row's kind and + # stored id held in memory only (ADR 0217, *A ref is for reading*), never a secret. "messagefoundry/api/auth_routes.py": frozenset( - {"compare:via messagefoundry.credential", "hash:via messagefoundry.auth.tokens"} + { + "compare:via messagefoundry.credential", + "hash:via messagefoundry.auth.tokens", + "hash:via messagefoundry.store.row_seal", + } ), "messagefoundry/tray/poller.py": frozenset({"tls_context:via messagefoundry.tray.probe"}), "messagefoundry/verify/federation.py": frozenset( diff --git a/tests/test_api_auth.py b/tests/test_api_auth.py index f206e8ddc0..aa3952f9e9 100644 --- a/tests/test_api_auth.py +++ b/tests/test_api_auth.py @@ -222,6 +222,102 @@ async def refused(_user_id: str) -> list[Any]: assert "integrity check" in r.json()["detail"] +def _seal_refusal(cause: str) -> Exception: + from messagefoundry.store.row_seal import ( + RowSealError, + RowSealUnverifiableError, + TransitSealUnavailableError, + TransitSealUnverifiableError, + ) + + return { + "forged": RowSealError("user", "u-synthetic"), + "unverifiable-write": RowSealUnverifiableError( + "user", "u-synthetic", stored_version=5, probe_version=3 + ), + "unverifiable-read": TransitSealUnverifiableError("user", 5, 3), + "outage": TransitSealUnavailableError(), + }[cause] + + +@pytest.mark.parametrize("cause", ["forged", "unverifiable-write", "unverifiable-read", "outage"]) +async def test_the_api_backstop_reports_and_answers_every_seal_refusal_type( + engine: Engine, monkeypatch: pytest.MonkeyPatch, cause: str +) -> None: + """Vault BACKLOG #8202 item 161, ADR 0217 (c) item 3: a seal refusal no route answered reaches + the API's backstop, which pages and audits it under its own cause before it answers: Forged 409 + with ``main``'s text, Unverifiable 409 with the recovery text, Outage 503 with ``Retry-After``, + never the generic 500. A Forged or Unverifiable row is reported once per throttle window; each + Outage-refused request writes its own row, and no Outage writes a seal failure.""" + from messagefoundry.auth.service import ( + AUTHORITY_SEAL_FAILED_ACTION, + AUTHORITY_SEAL_UNVERIFIABLE_ACTION, + ) + from messagefoundry.store.row_seal import ( + AUTHORITY_SEAL_FAILED_SUBJECT, + TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, + TRANSIT_OUTAGE_SUBJECT, + UNVERIFIABLE_SUBJECT_PREFIX, + ) + from messagefoundry.transports.http_listener import TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS + + service = await _service(engine) + await _add(service, "viewer", Role.VIEWER) + pages: list[str] = [] + engine.store.seal_pager().arm(lambda subject, _reason: pages.append(subject)) + async with _client(engine, service) as c: + token = (await _login(c, "viewer")).json()["token"] + + async def refused(_user_id: str) -> list[Any]: + raise _seal_refusal(cause) + + monkeypatch.setattr(service, "list_sessions", refused) + answers = [await c.get("/me/sessions", headers=_auth(token)) for _ in range(2)] + + actions = { + "forged": AUTHORITY_SEAL_FAILED_ACTION, + "unverifiable-write": AUTHORITY_SEAL_UNVERIFIABLE_ACTION, + "unverifiable-read": AUTHORITY_SEAL_UNVERIFIABLE_ACTION, + "outage": TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, + } + rows = await engine.store.list_audit(action=actions[cause], limit=50) + for r in answers: + detail = r.json()["detail"] + if cause == "outage": + assert r.status_code == 503 + assert r.headers["Retry-After"] == str(TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS) + else: + assert r.status_code == 409 + if cause.startswith("unverifiable"): + assert "could not be verified by Vault transit" in detail + assert "The seal may be planted" in detail + assert "forged" not in detail.lower() and "integrity check" not in detail + if cause == "forged": + assert "integrity check" in detail + assert "u-synthetic" not in json.dumps([r.json() for r in answers]) + if cause == "outage": + assert len(rows) == 2 # each refused request is audited + assert pages == [TRANSIT_OUTAGE_SUBJECT, TRANSIT_OUTAGE_SUBJECT] + for action in (AUTHORITY_SEAL_FAILED_ACTION, AUTHORITY_SEAL_UNVERIFIABLE_ACTION): + assert await engine.store.list_audit(action=action, limit=50) == [] + else: + assert len(rows) == 1 # throttled per row + detail = json.loads(str(rows[0]["detail"])) + assert detail["kind"] == "user" and detail["during"] == "api" + assert detail["route"] == "/me/sessions" + if cause == "unverifiable-read": + assert detail["ref"] == "" + assert pages == [f"{UNVERIFIABLE_SUBJECT_PREFIX}:*"] + else: + assert detail["ref"] == "u-synthetic" + if cause == "unverifiable-write": + assert len(pages) == 1 and pages[0].startswith(f"{UNVERIFIABLE_SUBJECT_PREFIX}:user:") + if cause.startswith("unverifiable"): + assert (detail["stored_version"], detail["probe_version"]) == (5, 3) + if cause == "forged": + assert pages == [AUTHORITY_SEAL_FAILED_SUBJECT] + + async def test_security_events_feed_lists_callers_auth_events(engine: Engine) -> None: # WP-L3-05 (ASVS 6.3.5/6.3.7): /me/security-events surfaces the caller's own audited auth.* events. service = await _service(engine) From ffdfd664d13632c36a8dbcd23b3cbf827f68a6cc Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 29 Nov 2026 20:46:20 -0600 Subject: [PATCH 3/7] Say what a retried revoke's held reports really do RevokeSealOutcome.committing said a retry that meets the same refusals reports each once. Only a refusal the committing retry also met is reported once, by that retry; one only failed attempts met can be reported once per held attempt, as deferred_revoke_reports says. The docstring now claims only that (vault BACKLOG #8202 item 2), and a test pins both the behaviour and the text. Verified-by: tests --- messagefoundry/store/store.py | 6 ++++-- tests/test_transit_row_seal_revoke.py | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/messagefoundry/store/store.py b/messagefoundry/store/store.py index 0959836117..ceb6c05806 100644 --- a/messagefoundry/store/store.py +++ b/messagefoundry/store/store.py @@ -1949,8 +1949,10 @@ async def committing( paged, and each held Forged or Unverifiable refusal is logged, audited softly and paged. The text does not claim the revoke rolled back: an error after a commit landed reaches here too. Inside a :func:`deferred_revoke_reports` scope, which a caller that retries a failed - revoke opens, the report is held for the scope instead, so a retry that meets the same - refusals reports each once (decision d20261110T063908944-857965, item 4). That report never + revoke opens, the report is held for the scope instead, so a refusal the committing retry + also met is reported by that retry alone (decision d20261110T063908944-857965, item 4); one + that only failed attempts met can be reported once per held attempt that met it, as + :func:`deferred_revoke_reports` says (vault BACKLOG #8202 item 2). That report never raises, so the transaction's exception is the one the caller sees; it runs to completion through a cancel, and a cancel that lands meanwhile is raised in place of a transaction exception that was not itself a cancel. diff --git a/tests/test_transit_row_seal_revoke.py b/tests/test_transit_row_seal_revoke.py index 8c49a6088b..98d3205ebb 100644 --- a/tests/test_transit_row_seal_revoke.py +++ b/tests/test_transit_row_seal_revoke.py @@ -1143,6 +1143,33 @@ async def test_a_refusal_only_a_failed_attempt_met_is_reported_as_retried( assert len(pages) == 1 and pages[0].endswith("a retry of the revoke then committed") +async def test_a_refusal_two_failed_attempts_met_is_reported_by_each_and_the_text_says_so( + transit: tuple[MessageStore, FakeBackend, Path], + pages: list[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Vault BACKLOG #8202 item 2: held failed attempts are not deduplicated against each other, so + a refusal two failed attempts met is audited by each, and ``committing``'s docstring no longer + says a retry that meets the same refusals reports each once.""" + from messagefoundry.store.store import deferred_revoke_reports + + store, _, path = transit + await _user(store, "u-1") + kept = await _session(store, "u-1") + _plant(path, "users", "authz_seal", "id", "u-1") + _forged_kept_session(monkeypatch, store) + async with deferred_revoke_reports(): + for _ in range(2): + with pytest.raises(RowSealError): + await store.revoke_user_sessions( + "u-1", except_token_hash=hash_token(kept), audit=no_audit_row + ) + assert len(await _audits(store, "integrity.authority_seal_unverifiable")) == 2 + doc = " ".join((RevokeSealOutcome.committing.__doc__ or "").split()) + assert "reports each once" not in doc + assert "once per held attempt that met it" in doc + + async def test_a_report_failure_is_logged_with_its_class_and_re_raised( caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: From c36bd54e640a7ce2321de878ff1397535b2c9eb5 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 29 Nov 2026 21:20:55 -0600 Subject: [PATCH 4/7] Bound and correct the seal backstop's reports, review round 1 Review round-50a1aa9135 found the backstop's throttle collapsed every subject-less refusal of one kind onto one key, so after the first, no other row of that kind was logged, audited or paged for five minutes, less than origin/main logged; and that an Outage audited and paged every request with no bound. Now every refusal is logged, a Forged one at WARNING as before and the others at ERROR, the generic handler's level; the page and audit row are throttled per row where the refusal names one, else per route and client address. Audit details name the row as AuthService's rows of the same actions do (user_id, session, else ref). The Outage 503 no longer reuses the admin-read helper whose docstring says nothing was read. The ADR 0217 notes, the gate's docstring and the changelog fragment now claim only what the code does, at least the gate's background reads, its system actor, the backstop's throttle and a refusal raised after a streamed response starts. Vault BACKLOG #8202 items 161 and 146. Verified-by: tests --- .../8202-seal-refusal-audit.security.md | 14 +- ...ciler-ends-sessions-rather-than-holding.md | 28 ++-- messagefoundry/api/approvals.py | 10 +- messagefoundry/api/auth_routes.py | 139 ++++++++++-------- tests/test_api_auth.py | 54 ++++--- 5 files changed, 143 insertions(+), 102 deletions(-) diff --git a/changelog.d/8202-seal-refusal-audit.security.md b/changelog.d/8202-seal-refusal-audit.security.md index a5015f1599..af0dcc1cbc 100644 --- a/changelog.d/8202-seal-refusal-audit.security.md +++ b/changelog.d/8202-seal-refusal-audit.security.md @@ -1,8 +1,10 @@ -- **A request a Vault transit Outage refuses is audited, and the API answers every seal refusal - type.** The approval gate writes an `authority.seal_unavailable` audit row, not a seal failure, - for each request it refuses on an Outage, and its page no longer says that nothing was done. - The API's seal backstop now answers the Unverifiable and Outage refusal types as well as a - Forged row, with a 409 or a 503 and `Retry-After` in place of the generic 500, and pages and - audits the refusal before it answers. See +- **A Vault transit Outage at an approval request's seal check is audited, and the API answers + more seal refusal types.** The approval gate writes an `authority.seal_unavailable` audit row, + not a seal failure, each time an Outage refuses its check of a request's seal, its own + background reads included, and its page no longer says that nothing was done. The API's seal + backstop now also answers the Unverifiable and Outage refusal types that a route lets escape, + with a 409 or a 503 and `Retry-After` in place of the generic 500. It logs each such refusal, + and pages and audits it at most once per report interval for each row, or, where the refusal + names no row, for each route and client address. Limits are in [ADR 0217](../docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md). (`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 723a1d0496..e627b0ff7a 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 @@ -314,8 +314,8 @@ A correction, added 2026-11-11: the Outage row's "the refused request itself is 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). *(Note 2026-11-29, vault BACKLOG #8202 item 146: the gate now writes an -`authority.seal_unavailable` row for each request it refuses on an Outage at -`ApprovalGate._verified`, so this correction no longer holds for that path; gap (3) says so.)* +`authority.seal_unavailable` row each time an Outage refuses its check at +`ApprovalGate._verified`; gap (3)'s note says what that row records.)* 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 @@ -1129,10 +1129,12 @@ session, approval, on SQLite, PostgreSQL and SQL Server): claim: an Unverifiable answer there goes to `ApprovalGate._store_fault`, which answers 503 and pages `audit_write_failed`; no `integrity.authority_seal_unverifiable` row is written. (3) A request refused by an Outage at `ApprovalGate._verified`: `_approval_seal_outage` pages and - writes no row. *(Note 2026-11-29, vault BACKLOG #8202 item 146: gap (3) is closed. - `_approval_seal_outage` now also writes a soft `authority.seal_unavailable` row, not an - `integrity.*` action, for each refused call, and its reason no longer says the request was - refused or that nothing was done (item 145).)* The owner ruled on 2026-11-11, in the Lander's session, that this ADR names them + writes no row. *(Note 2026-11-29, vault BACKLOG #8202 item 146: `_approval_seal_outage` now + also writes a soft `authority.seal_unavailable` row, not an `integrity.*` action, each time an + Outage refuses a check at `ApprovalGate._verified`, the gate's own background reads included. + The row names the request, with `system` as its actor and no client address, so it does not + say who was refused. Its reason no longer says the request was refused or that nothing was + done (item 145).)* 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). - **Open audit gaps, extended 2026-11-11.** The three paths above are not the whole list. At least @@ -1180,12 +1182,14 @@ session, approval, on SQLite, PostgreSQL and SQL Server): Outage with HTTP 503 and `Retry-After`" are not yet built on every path: a refusal no caller maps reaches the engine's generic handler as a 500. *(Note 2026-11-29, vault BACKLOG #8202 item 161: the API backstop in `api/auth_routes.py` is now registered for `RowSealError`, - `RowSealUnverifiableError`, `TransitSealUnverifiableError` and `TransitSealUnavailableError`. It - pages and soft-audits before it answers, a Forged or Unverifiable row at most once per report - interval and an Outage on every refused request, so a refusal of those types that an HTTP route lets - escape no longer reaches the generic 500. A refusal another type carries, such as the - `ApprovalError` of item 155, still can, and the catch census test and the CLI's handler are still - not built.)* The sign-in audit actions this ADR names, + `RowSealUnverifiableError`, `TransitSealUnverifiableError` and `TransitSealUnavailableError`. + It logs each refusal it answers. It pages and soft-audits at most once per report interval per + row where the refusal names one, else per route and client address, so the Outage row's "the + refused request itself is audited" does not hold for every request it answers. A refusal of + those types that an HTTP route lets escape before its response starts no longer reaches the + generic 500. At least a refusal another type carries, such as the `ApprovalError` of item 155, + and one raised after a streamed response has started, still can, and the catch census test and + the CLI's handler are still not built.)* The sign-in audit actions this ADR names, `auth.login_refused_unavailable` in the Outage row and in (e), `auth.login_refused_unverifiable` in (e), and the audit rows (e)'s *Control kept* and *The refusal cache* promise a sign-in refusal writes, are slice 2's sign-in refusals, which the 2026-11-08 build status line lists as not diff --git a/messagefoundry/api/approvals.py b/messagefoundry/api/approvals.py index 780de7517f..c1d3e2b4a0 100644 --- a/messagefoundry/api/approvals.py +++ b/messagefoundry/api/approvals.py @@ -3316,10 +3316,12 @@ async def _approval_seal_unverifiable( 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, then a - soft :data:`~messagefoundry.store.row_seal.TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION` row for the - refused call (vault BACKLOG #8202 item 146). Neither records a seal failure, so no - ``integrity.*`` action is written. The row is not throttled; the WARNING is, as - :meth:`_read` throttles a store fault's, since the queue reads on every page load. + soft :data:`~messagefoundry.store.row_seal.TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION` row naming + the request (vault BACKLOG #8202 item 146), on every check this refuses, the gate's own + background reads included. Neither records a seal failure, so no ``integrity.*`` action is + written. The row's actor is ``system`` and it carries no client address, since this check + is not told who asked. The row is not throttled; the WARNING is, as :meth:`_read` + throttles a store fault's, since the queue reads on every page load. The reason says only that the seal could not be made or checked (ADR 0217 (c) step 4, item 145): this check also runs where an operation or a write may already have run, at diff --git a/messagefoundry/api/auth_routes.py b/messagefoundry/api/auth_routes.py index 0ec2efbfe8..229f2ebc92 100644 --- a/messagefoundry/api/auth_routes.py +++ b/messagefoundry/api/auth_routes.py @@ -17,7 +17,8 @@ import logging import time from collections.abc import AsyncIterator, Iterable, Sequence -from typing import Annotated, Any +from dataclasses import dataclass +from typing import Annotated, Any, Literal from fastapi import Depends, FastAPI, HTTPException, Query, Request, Response, status from fastapi.exception_handlers import http_exception_handler @@ -189,8 +190,10 @@ from messagefoundry.credential import constant_time_equal from messagefoundry.spreadsheet import SPREADSHEET_FORMULA_TRIGGERS, spreadsheet_safe from messagefoundry.store.row_seal import ( + SESSION_KIND, TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, UNVERIFIABLE_SUBJECT_PREFIX, + USER_KIND, RowSealError, RowSealUnverifiableError, SealFailureThrottle, @@ -417,29 +420,30 @@ def _seal_outage_503() -> HTTPException: ) +@dataclass(frozen=True, slots=True) class _SealBackstop: """What the API's seal backstop reports and answers for one refusal no route answered.""" - __slots__ = ("action", "answer", "cause", "detail", "kind", "reason", "subject") + cause: Literal["forged", "unverifiable", "outage"] + kind: str + subject: str + action: str + detail: dict[str, object] + reason: str + answer: HTTPException - def __init__( - self, - cause: str, - *, - kind: str, - subject: str, - action: str, - detail: dict[str, object], - reason: str, - answer: HTTPException, - ) -> None: - self.cause = cause - self.kind = kind - self.subject = subject - self.action = action - self.detail = detail - self.reason = reason - self.answer = answer + +def _row_detail(kind: str, subject: str) -> dict[str, object]: + """How a backstop audit row names its row, in the keys ``AuthService``'s rows of the same + actions use: ``user_id`` for an account, ``session`` (its 12-character ref) for a session, else + ``ref``, the bounded :func:`seal_row_ref`. Empty where the raising site gave no subject.""" + if not subject: + return {} + if kind == USER_KIND: + return {"user_id": subject} + if kind == SESSION_KIND: + return {"session": seal_row_ref(kind, subject)} + return {"ref": seal_row_ref(kind, subject)} def _seal_backstop(exc: Exception, route: str) -> _SealBackstop: @@ -447,7 +451,8 @@ def _seal_backstop(exc: Exception, route: str) -> _SealBackstop: answering ``route`` (ADR 0217, *The four answers* and (c) items 3 and 4). A Forged row answers 409 with ``main``'s fixed text; an Unverifiable one 409 with (a)'s recovery text, never "forged"; an Outage 503 with ``Retry-After``, worded as the seal that "could not be made or - checked". A row is named only by its bounded ref (:func:`seal_row_ref`), never a row value.""" + checked". A reason names a row only by its bounded ref (:func:`seal_row_ref`), never a row + value.""" if isinstance(exc, TransitSealUnavailableError): return _SealBackstop( "outage", @@ -459,7 +464,13 @@ def _seal_backstop(exc: Exception, route: str) -> _SealBackstop: f"a row seal could not be made or checked through Vault transit while the API" f" answered {route}" ), - answer=_seal_outage_503(), + # Not _seal_outage_503, whose admin-read premise ("nothing was read") need not hold + # here: the text is the type's own fixed text, which claims nothing about what ran. + answer=HTTPException( + status.HTTP_503_SERVICE_UNAVAILABLE, + str(TransitSealUnavailableError()), + headers={"Retry-After": str(TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS)}, + ), ) if isinstance(exc, RowSealUnverifiableError | TransitSealUnverifiableError): subject = exc.subject if isinstance(exc, RowSealUnverifiableError) else "" @@ -472,7 +483,7 @@ def _seal_backstop(exc: Exception, route: str) -> _SealBackstop: action=AUTHORITY_SEAL_UNVERIFIABLE_AUDIT_ACTION, detail={ "kind": kind, - "ref": ref, + **_row_detail(kind, subject), "during": "api", "route": route, "stored_version": exc.stored_version, @@ -500,7 +511,7 @@ def _seal_backstop(exc: Exception, route: str) -> _SealBackstop: kind=kind, subject=subject, action=AUTHORITY_SEAL_FAILED_ACTION, - detail={"kind": kind, "ref": ref, "during": "api", "route": route}, + detail={"kind": kind, **_row_detail(kind, subject), "during": "api", "route": route}, reason=( f"a stored {kind} record failed its integrity check while the API answered {route}" + (f" ({kind} {ref})" if ref else "") @@ -807,9 +818,9 @@ async def _repeated_credential(request: Request, exc: Exception) -> Response: app.add_exception_handler(RepeatedCredentialError, _repeated_credential) - # One per app: a Forged or Unverifiable row the backstop meets is reported at most once per - # SEAL_FAILURE_REPORT_INTERVAL_SECONDS, keyed by cause and the SHA-256 of the kind and the - # whole ref, so one cause never holds back the other's report (ADR 0217). + # One per app: the backstop's page and audit row for one key go out at most once per + # SEAL_FAILURE_REPORT_INTERVAL_SECONDS (_seal_report_key says what a key is). Its log line is + # never throttled. seal_reports = SealFailureThrottle() async def _row_seal_refused(request: Request, exc: Exception) -> Response: @@ -822,51 +833,58 @@ async def _row_seal_refused(request: Request, exc: Exception) -> Response: # # Vault BACKLOG #8202 item 161, ADR 0217 (c) item 3: this is the API's backstop for every # seal refusal type no route answered, the Unverifiable and Outage types as well as Forged, - # and it reports before it answers. A Forged or Unverifiable refusal is logged, paged and - # audited under its own action, throttled per row; an Outage pages and writes a - # TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION row for each refused request, and records no seal - # failure. The code that raised may have reported the same refusal already, so a refusal - # can be reported twice; the backstop never reports less than the raising site did. + # and it reports before it answers. Every refusal is logged, a Forged one at WARNING as + # before, the others at ERROR, the level the generic handler gave them; the page and the + # soft audit row under the cause's own action are throttled per _seal_report_key. An + # Outage's row is TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, never a seal failure. The code that + # raised may have reported the same refusal already, so a refusal can be reported twice. assert isinstance(exc, _SEAL_BACKSTOP_TYPES) route = str(getattr(request.scope.get("route"), "path", "") or "an API route") + client = client_ip(request) refusal = _seal_backstop(exc, route) - if refusal.cause == "outage": - report = True - logged = seal_reports.due(("outage", route)) - else: - report = seal_reports.due( - (refusal.cause, seal_row_digest(refusal.kind, refusal.subject)) - ) - logged = report - if logged: - _log.warning("%s (BACKLOG #2592, #5505)", refusal.reason) - if report: - await _report_seal_refusal(request, refusal) + _log.log( + logging.WARNING if refusal.cause == "forged" else logging.ERROR, + "%s (BACKLOG #2592, #5505)", + refusal.reason, + ) + if seal_reports.due(_seal_report_key(refusal, route, client)): + await _report_seal_refusal(request, refusal, client) return await http_exception_handler(request, refusal.answer) - async def _report_seal_refusal(request: Request, refusal: _SealBackstop) -> None: + def _seal_report_key(refusal: _SealBackstop, route: str, client: str | None) -> object: + """The throttle key of one backstop report. A refusal that names its row is keyed by cause + and the SHA-256 of the kind and the whole subject (ADR 0217, *A ref is for reading*), so + one cause never holds back the other's report. One that names no row, and every Outage, + is keyed by cause, kind, route and client address instead, so a subject-less refusal on one + route or from one address never holds back another's. Within one key, a repeat inside the + window is logged only.""" + if refusal.subject: + return (refusal.cause, seal_row_digest(refusal.kind, refusal.subject)) + return (refusal.cause, refusal.kind, route, client) + + async def _report_seal_refusal( + request: Request, refusal: _SealBackstop, client: str | None + ) -> None: """Page, then audit softly, one refusal the backstop answers. Never raises, so the - refusal's own answer always goes out. With no auth service attached there is no store to - audit to or pager to page through, and the log line is the only record.""" + refusal's own answer always goes out; a failed audit write is logged at ERROR. With no auth + service attached there is no store to audit to or pager to page through, and the log line + is the only record.""" auth: AuthService | None = getattr(request.app.state, "auth", None) if auth is None: return store = auth.store pager = getattr(store, "seal_pager", None) if callable(pager): - try: - seal_pager = pager() - if refusal.cause == "outage": - seal_pager.outage(refusal.reason) - elif refusal.cause == "forged": - seal_pager.forged(refusal.reason) - elif refusal.subject: - seal_pager.unverifiable(refusal.kind, refusal.subject, refusal.reason) - else: - seal_pager.page(f"{UNVERIFIABLE_SUBJECT_PREFIX}:*", refusal.reason) - except Exception as exc: # noqa: BLE001 - a page failure must never replace the answer - _log.warning("the API's seal refusal page failed: %s", type(exc).__name__) - client = client_ip(request) + # SealPager's page methods never raise. + seal_pager = pager() + if refusal.cause == "outage": + seal_pager.outage(refusal.reason) + elif refusal.cause == "forged": + seal_pager.forged(refusal.reason) + elif refusal.subject: + seal_pager.unverifiable(refusal.kind, refusal.subject, refusal.reason) + else: + seal_pager.page(f"{UNVERIFIABLE_SUBJECT_PREFIX}:*", refusal.reason) await write_audit_soft( lambda: store.record_audit( refusal.action, detail=json.dumps(refusal.detail), client=client @@ -875,7 +893,6 @@ async def _report_seal_refusal(request: Request, refusal: _SealBackstop) -> None message="the %s audit row for a seal refusal the API answered could not be written", args=(refusal.action,), # No defect raises: the refusal's own answer must still go out. - errors=(Exception,), defects=(), ) diff --git a/tests/test_api_auth.py b/tests/test_api_auth.py index aa3952f9e9..accd272078 100644 --- a/tests/test_api_auth.py +++ b/tests/test_api_auth.py @@ -242,13 +242,14 @@ def _seal_refusal(cause: str) -> Exception: @pytest.mark.parametrize("cause", ["forged", "unverifiable-write", "unverifiable-read", "outage"]) async def test_the_api_backstop_reports_and_answers_every_seal_refusal_type( - engine: Engine, monkeypatch: pytest.MonkeyPatch, cause: str + engine: Engine, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, cause: str ) -> None: """Vault BACKLOG #8202 item 161, ADR 0217 (c) item 3: a seal refusal no route answered reaches the API's backstop, which pages and audits it under its own cause before it answers: Forged 409 with ``main``'s text, Unverifiable 409 with the recovery text, Outage 503 with ``Retry-After``, - never the generic 500. A Forged or Unverifiable row is reported once per throttle window; each - Outage-refused request writes its own row, and no Outage writes a seal failure.""" + never the generic 500. Every refusal is logged. The page and the row are throttled per row + where the refusal names one, else per route and client address, so a second address is + reported on its own; no Outage writes a seal failure.""" from messagefoundry.auth.service import ( AUTHORITY_SEAL_FAILED_ACTION, AUTHORITY_SEAL_UNVERIFIABLE_ACTION, @@ -265,14 +266,27 @@ async def test_the_api_backstop_reports_and_answers_every_seal_refusal_type( await _add(service, "viewer", Role.VIEWER) pages: list[str] = [] engine.store.seal_pager().arm(lambda subject, _reason: pages.append(subject)) - async with _client(engine, service) as c: - token = (await _login(c, "viewer")).json()["token"] - - async def refused(_user_id: str) -> list[Any]: - raise _seal_refusal(cause) - monkeypatch.setattr(service, "list_sessions", refused) - answers = [await c.get("/me/sessions", headers=_auth(token)) for _ in range(2)] + async def refused(_user_id: str) -> list[Any]: + raise _seal_refusal(cause) + + caplog.set_level(logging.WARNING, logger="messagefoundry.api.auth_routes") + answers = [] + app = create_app(engine, auth=service) # one app, so one backstop throttle, for both peers + for peer, calls in ((("127.0.0.1", 123), 2), (("127.0.0.2", 124), 1)): + transport = httpx.ASGITransport(app=app, client=peer) + async with httpx.AsyncClient(transport=transport, base_url="http://t") as c: + token = (await _login(c, "viewer")).json()["token"] + monkeypatch.setattr(service, "list_sessions", refused) + answers += [await c.get("/me/sessions", headers=_auth(token)) for _ in range(calls)] + monkeypatch.undo() + logged = [ + r + for r in caplog.records + if r.name == "messagefoundry.api.auth_routes" and "/me/sessions" in r.getMessage() + ] + assert len(logged) == 3 # every refusal is logged, throttled or not + assert all((r.levelno == logging.WARNING) == (cause == "forged") for r in logged) actions = { "forged": AUTHORITY_SEAL_FAILED_ACTION, @@ -295,21 +309,23 @@ async def refused(_user_id: str) -> list[Any]: if cause == "forged": assert "integrity check" in detail assert "u-synthetic" not in json.dumps([r.json() for r in answers]) + # A refusal that names its row is reported once for it; one that names none, once per address. + names_row = cause in ("forged", "unverifiable-write") + assert len(rows) == (1 if names_row else 2) + assert {r["client"] for r in rows} <= {"127.0.0.1", "127.0.0.2"} + detail = json.loads(str(rows[0]["detail"])) + assert detail["during"] == "api" and detail["route"] == "/me/sessions" if cause == "outage": - assert len(rows) == 2 # each refused request is audited - assert pages == [TRANSIT_OUTAGE_SUBJECT, TRANSIT_OUTAGE_SUBJECT] + assert pages == [TRANSIT_OUTAGE_SUBJECT] * 2 for action in (AUTHORITY_SEAL_FAILED_ACTION, AUTHORITY_SEAL_UNVERIFIABLE_ACTION): assert await engine.store.list_audit(action=action, limit=50) == [] else: - assert len(rows) == 1 # throttled per row - detail = json.loads(str(rows[0]["detail"])) - assert detail["kind"] == "user" and detail["during"] == "api" - assert detail["route"] == "/me/sessions" + assert detail["kind"] == "user" if cause == "unverifiable-read": - assert detail["ref"] == "" - assert pages == [f"{UNVERIFIABLE_SUBJECT_PREFIX}:*"] + assert "user_id" not in detail + assert pages == [f"{UNVERIFIABLE_SUBJECT_PREFIX}:*"] * 2 else: - assert detail["ref"] == "u-synthetic" + assert detail["user_id"] == "u-synthetic" if cause == "unverifiable-write": assert len(pages) == 1 and pages[0].startswith(f"{UNVERIFIABLE_SUBJECT_PREFIX}:user:") if cause.startswith("unverifiable"): From 6339bf1acbe2fa948e267c53e4270ec3fae25664 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 29 Nov 2026 21:55:19 -0600 Subject: [PATCH 5/7] Throttle the gate's Outage row and name the backstop's raising site, review round 2 Review round-859981b4cb found that the gate's unthrottled Outage row could stall every queue load on an audit append that itself needs Transit, and that its lost-row page folded into the request's other lost rows; it is now written once per report interval per request, and pages under approval::seal_unavailable. The backstop logs each refusal with its method, route and raising site, which the generic handler's traceback used to show; keys a subject-less refusal per route rather than per client address, so keys stay bounded; audits on the engine's store where no auth service is attached; names the row as "subject", since a raising site may give a ref; reuses revoke_seal_refusals() and _seal_outage_503(); and its Unverifiable 409 no longer says the request was refused. The ADR 0217 notes and the changelog fragment claim only that. Vault BACKLOG #8202 items 146 and 161. Verified-by: tests --- .../8202-seal-refusal-audit.security.md | 14 +- ...ciler-ends-sessions-rather-than-holding.md | 14 +- messagefoundry/api/approvals.py | 18 ++- messagefoundry/api/auth_routes.py | 124 +++++++++--------- tests/test_api_auth.py | 23 ++-- tests/test_transit_approval_gate.py | 17 ++- 6 files changed, 117 insertions(+), 93 deletions(-) diff --git a/changelog.d/8202-seal-refusal-audit.security.md b/changelog.d/8202-seal-refusal-audit.security.md index af0dcc1cbc..c1f6ee63a8 100644 --- a/changelog.d/8202-seal-refusal-audit.security.md +++ b/changelog.d/8202-seal-refusal-audit.security.md @@ -1,10 +1,10 @@ - **A Vault transit Outage at an approval request's seal check is audited, and the API answers - more seal refusal types.** The approval gate writes an `authority.seal_unavailable` audit row, - not a seal failure, each time an Outage refuses its check of a request's seal, its own - background reads included, and its page no longer says that nothing was done. The API's seal - backstop now also answers the Unverifiable and Outage refusal types that a route lets escape, - with a 409 or a 503 and `Retry-After` in place of the generic 500. It logs each such refusal, - and pages and audits it at most once per report interval for each row, or, where the refusal - names no row, for each route and client address. Limits are in + more seal refusal types.** Where the audit append still works, the approval gate writes an + `authority.seal_unavailable` audit row, not a seal failure, for a request an Outage refuses at + its seal check, at most once per report interval per request in each process, and pages each + such refusal; its page no longer says that nothing was done. The API's seal backstop now also + answers the Unverifiable and Outage refusal types that a route lets escape, with a 409 or a 503 + and `Retry-After` in place of the generic 500. It logs each such refusal, and pages and audits + it, throttled per row, or per route where the refusal names no row. Limits are in [ADR 0217](../docs/adr/0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md). (`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 e627b0ff7a..60868245de 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 @@ -1130,11 +1130,13 @@ session, approval, on SQLite, PostgreSQL and SQL Server): pages `audit_write_failed`; no `integrity.authority_seal_unverifiable` row is written. (3) A request refused by an Outage at `ApprovalGate._verified`: `_approval_seal_outage` pages and writes no row. *(Note 2026-11-29, vault BACKLOG #8202 item 146: `_approval_seal_outage` now - also writes a soft `authority.seal_unavailable` row, not an `integrity.*` action, each time an + also writes a soft `authority.seal_unavailable` row, not an `integrity.*` action, when an Outage refuses a check at `ApprovalGate._verified`, the gate's own background reads included. - The row names the request, with `system` as its actor and no client address, so it does not - say who was refused. Its reason no longer says the request was refused or that nothing was - done (item 145).)* The owner ruled on 2026-11-11, in the Lander's session, that this ADR names them + It writes at most one per report interval per request in each process, and only where the + audit append still works, which on a `vault_transit` store may itself need Transit. The row + names the request, with `system` as its actor and no client address, so it does not say who + was refused. Its reason no longer says the request was refused or that nothing was done + (item 145).)* 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). - **Open audit gaps, extended 2026-11-11.** The three paths above are not the whole list. At least @@ -1183,8 +1185,8 @@ session, approval, on SQLite, PostgreSQL and SQL Server): reaches the engine's generic handler as a 500. *(Note 2026-11-29, vault BACKLOG #8202 item 161: the API backstop in `api/auth_routes.py` is now registered for `RowSealError`, `RowSealUnverifiableError`, `TransitSealUnverifiableError` and `TransitSealUnavailableError`. - It logs each refusal it answers. It pages and soft-audits at most once per report interval per - row where the refusal names one, else per route and client address, so the Outage row's "the + It logs each refusal it answers, with the raising site. It pages and soft-audits throttled per + row where the refusal names one, else per route, within each process, so the Outage row's "the refused request itself is audited" does not hold for every request it answers. A refusal of those types that an HTTP route lets escape before its response starts no longer reaches the generic 500. At least a refusal another type carries, such as the `ApprovalError` of item 155, diff --git a/messagefoundry/api/approvals.py b/messagefoundry/api/approvals.py index c1d3e2b4a0..611c6a7b6b 100644 --- a/messagefoundry/api/approvals.py +++ b/messagefoundry/api/approvals.py @@ -706,6 +706,10 @@ 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 refused is audited again (vault BACKLOG #8202 + # item 146): the queue reads on every page load, and on a vault_transit store the audit + # append may itself wait on Transit, so an unthrottled row would stall every load. + 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 @@ -3317,11 +3321,14 @@ 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, then a soft :data:`~messagefoundry.store.row_seal.TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION` row naming - the request (vault BACKLOG #8202 item 146), on every check this refuses, the gate's own + the request (vault BACKLOG #8202 item 146), from any check this refuses, the gate's own background reads included. Neither records a seal failure, so no ``integrity.*`` action is - written. The row's actor is ``system`` and it carries no client address, since this check - is not told who asked. The row is not throttled; the WARNING is, as :meth:`_read` - throttles a store fault's, since the queue reads on every page load. + written. The row is written where the audit append still works, at most once per + :data:`~messagefoundry.store.row_seal.SEAL_FAILURE_REPORT_INTERVAL_SECONDS` per request in + this process; its actor is ``system`` and it carries no client address, since this check is + not told who asked. A lost row pages ``audit_write_failed`` under a key of its own, so it + never folds into a lost row of the request's other actions. The WARNING is throttled, as + :meth:`_read` throttles a store fault's, since the queue reads on every page load. The reason says only that the seal could not be made or checked (ADR 0217 (c) step 4, item 145): this check also runs where an operation or a write may already have run, at @@ -3337,6 +3344,8 @@ async def _approval_seal_outage(self, approval_id: str) -> None: pager = getattr(self._store, "seal_pager", None) if callable(pager): pager().outage(reason) + if not self._seal_outage_reported.due(approval_id): + return await self._record_audit_soft( ref, TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, @@ -3346,6 +3355,7 @@ async def _approval_seal_outage(self, approval_id: str) -> None: ), client=None, context="a request's integrity seal could not be made or checked through Vault transit", + alert_key=f"approval:{ref}:seal_unavailable", ) async def _approval_seal_failed(self, approval_id: str) -> None: diff --git a/messagefoundry/api/auth_routes.py b/messagefoundry/api/auth_routes.py index 229f2ebc92..9e0e19bf45 100644 --- a/messagefoundry/api/auth_routes.py +++ b/messagefoundry/api/auth_routes.py @@ -190,15 +190,14 @@ from messagefoundry.credential import constant_time_equal from messagefoundry.spreadsheet import SPREADSHEET_FORMULA_TRIGGERS, spreadsheet_safe from messagefoundry.store.row_seal import ( - SESSION_KIND, TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, UNVERIFIABLE_SUBJECT_PREFIX, - USER_KIND, RowSealError, RowSealUnverifiableError, SealFailureThrottle, TransitSealUnavailableError, TransitSealUnverifiableError, + revoke_seal_refusals, seal_row_digest, seal_row_ref, ) @@ -400,8 +399,10 @@ async def _check_custom_role_name(service: AuthService, role_id: str, display_na def _seal_outage_503() -> HTTPException: - """The 503 an admin user read answers when Vault transit could not check a record's seal (ADR - 0217, the Outage row): nothing was read, so retry once Vault answers.""" + """The 503 a route answers when Vault transit could not make or check a record's seal (ADR + 0217, the Outage row): the type's own fixed text, which claims nothing about what ran, and + ``Retry-After``. An admin user read answers it having read nothing; the seal backstop answers + it for whatever route let the Outage escape.""" return HTTPException( status.HTTP_503_SERVICE_UNAVAILABLE, str(TransitSealUnavailableError()), @@ -410,14 +411,9 @@ def _seal_outage_503() -> HTTPException: #: The seal refusal types the API's backstop answers (ADR 0217 (c) item 3; vault BACKLOG #8202 item -#: 161): Forged (``RowSealError``), both Unverifiable types and the Outage. Every distinct class is -#: named, since the Unverifiable and Outage types are siblings of ``RowSealError``, never subclasses. -_SEAL_BACKSTOP_TYPES: tuple[type[Exception], ...] = ( - RowSealError, - RowSealUnverifiableError, - TransitSealUnverifiableError, - TransitSealUnavailableError, -) +#: 161): Forged (``RowSealError``), both Unverifiable types and the Outage, the store's own set, so +#: a type added there is answered here too. +_SEAL_BACKSTOP_TYPES: tuple[type[Exception], ...] = revoke_seal_refusals() @dataclass(frozen=True, slots=True) @@ -434,16 +430,11 @@ class _SealBackstop: def _row_detail(kind: str, subject: str) -> dict[str, object]: - """How a backstop audit row names its row, in the keys ``AuthService``'s rows of the same - actions use: ``user_id`` for an account, ``session`` (its 12-character ref) for a session, else - ``ref``, the bounded :func:`seal_row_ref`. Empty where the raising site gave no subject.""" - if not subject: - return {} - if kind == USER_KIND: - return {"user_id": subject} - if kind == SESSION_KIND: - return {"session": seal_row_ref(kind, subject)} - return {"ref": seal_row_ref(kind, subject)} + """How a backstop audit row names its row: ``subject``, the raising site's subject bounded with + :func:`seal_row_ref`. Not ``user_id`` or ``session``, as ``AuthService``'s rows of the same + actions name theirs, since a raising site may give a ref already shortened rather than the + stored id (``RowSealError``). Empty where the raising site gave no subject.""" + return {"subject": seal_row_ref(kind, subject)} if subject else {} def _seal_backstop(exc: Exception, route: str) -> _SealBackstop: @@ -464,13 +455,7 @@ def _seal_backstop(exc: Exception, route: str) -> _SealBackstop: f"a row seal could not be made or checked through Vault transit while the API" f" answered {route}" ), - # Not _seal_outage_503, whose admin-read premise ("nothing was read") need not hold - # here: the text is the type's own fixed text, which claims nothing about what ran. - answer=HTTPException( - status.HTTP_503_SERVICE_UNAVAILABLE, - str(TransitSealUnavailableError()), - headers={"Retry-After": str(TEMPORARY_REFUSAL_RETRY_AFTER_SECONDS)}, - ), + answer=_seal_outage_503(), ) if isinstance(exc, RowSealUnverifiableError | TransitSealUnverifiableError): subject = exc.subject if isinstance(exc, RowSealUnverifiableError) else "" @@ -495,8 +480,10 @@ def _seal_backstop(exc: Exception, route: str) -> _SealBackstop: ), answer=HTTPException( status.HTTP_409_CONFLICT, - f"a stored {kind} record's integrity seal could not be verified by Vault transit," - " so the request was refused. The seal may be planted: check that Vault is healthy" + # It never says the request was refused or that nothing was done: the backstop + # answers whatever route let the refusal escape, perhaps after a write. + f"a stored {kind} record's integrity seal could not be verified by Vault transit." + " The seal may be planted: check that Vault is healthy" " and that every node holds the audit key's latest version, then retry; a record" " that still does not verify is untrusted and is re-created from an authoritative" " source, never from its stored values", @@ -818,9 +805,9 @@ async def _repeated_credential(request: Request, exc: Exception) -> Response: app.add_exception_handler(RepeatedCredentialError, _repeated_credential) - # One per app: the backstop's page and audit row for one key go out at most once per - # SEAL_FAILURE_REPORT_INTERVAL_SECONDS (_seal_report_key says what a key is). Its log line is - # never throttled. + # One per app, so per process: the backstop's page and audit row for one key go out again + # only once SEAL_FAILURE_REPORT_INTERVAL_SECONDS has passed, while the throttle still holds + # the key (_seal_report_key says what a key is). Its log line is never throttled. seal_reports = SealFailureThrottle() async def _row_seal_refused(request: Request, exc: Exception) -> Response: @@ -833,46 +820,65 @@ async def _row_seal_refused(request: Request, exc: Exception) -> Response: # # Vault BACKLOG #8202 item 161, ADR 0217 (c) item 3: this is the API's backstop for every # seal refusal type no route answered, the Unverifiable and Outage types as well as Forged, - # and it reports before it answers. Every refusal is logged, a Forged one at WARNING as - # before, the others at ERROR, the level the generic handler gave them; the page and the - # soft audit row under the cause's own action are throttled per _seal_report_key. An - # Outage's row is TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, never a seal failure. The code that - # raised may have reported the same refusal already, so a refusal can be reported twice. + # and it reports before it answers. Every refusal is logged with the method, the route and + # the raising site, since no catch census names the code that let it escape yet: a Forged + # one at WARNING as before, the others at ERROR, the level the generic handler gave them. + # The page and the soft audit row under the cause's own action are throttled per + # _seal_report_key. An Outage's row is TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, never a seal + # failure. The code that raised may have reported the same refusal already, so a refusal + # can be reported twice. assert isinstance(exc, _SEAL_BACKSTOP_TYPES) route = str(getattr(request.scope.get("route"), "path", "") or "an API route") - client = client_ip(request) refusal = _seal_backstop(exc, route) _log.log( logging.WARNING if refusal.cause == "forged" else logging.ERROR, - "%s (BACKLOG #2592, #5505)", + "%s (%s %s, raised at %s; BACKLOG #2592, #5505)", refusal.reason, + scrub_log_argument(request.method), + route, + _raising_site(exc), ) - if seal_reports.due(_seal_report_key(refusal, route, client)): - await _report_seal_refusal(request, refusal, client) + if seal_reports.due(_seal_report_key(refusal, route)): + await _report_seal_refusal(request, refusal) return await http_exception_handler(request, refusal.answer) - def _seal_report_key(refusal: _SealBackstop, route: str, client: str | None) -> object: + def _raising_site(exc: Exception) -> str: + """``module:function:line`` of the innermost frame ``exc`` passed through: code names only, + never a local or a row value.""" + tb = exc.__traceback__ + if tb is None: + return "an unknown site" + while tb.tb_next is not None: + tb = tb.tb_next + code = tb.tb_frame.f_code + module = str(tb.tb_frame.f_globals.get("__name__", "?")) + return f"{module}:{code.co_qualname}:{tb.tb_lineno}" + + def _seal_report_key(refusal: _SealBackstop, route: str) -> object: """The throttle key of one backstop report. A refusal that names its row is keyed by cause and the SHA-256 of the kind and the whole subject (ADR 0217, *A ref is for reading*), so one cause never holds back the other's report. One that names no row, and every Outage, - is keyed by cause, kind, route and client address instead, so a subject-less refusal on one - route or from one address never holds back another's. Within one key, a repeat inside the - window is logged only.""" + is keyed by cause, kind and route instead, so the keys stay bounded by the routes and a + refusal on one route never holds back another's. Within one key, a repeat inside the window + is logged only.""" if refusal.subject: return (refusal.cause, seal_row_digest(refusal.kind, refusal.subject)) - return (refusal.cause, refusal.kind, route, client) - - async def _report_seal_refusal( - request: Request, refusal: _SealBackstop, client: str | None - ) -> None: - """Page, then audit softly, one refusal the backstop answers. Never raises, so the - refusal's own answer always goes out; a failed audit write is logged at ERROR. With no auth - service attached there is no store to audit to or pager to page through, and the log line - is the only record.""" - auth: AuthService | None = getattr(request.app.state, "auth", None) - if auth is None: + return (refusal.cause, refusal.kind, route) + + async def _report_seal_refusal(request: Request, refusal: _SealBackstop) -> None: + """Page, then audit softly, one refusal the backstop answers, on the auth service's store, + or the engine's where no auth service is attached. Never raises, so the refusal's own + answer always goes out; a failed audit write is logged at ERROR. With neither store there, + the log line is the only record.""" + auth = get_auth(request) + store: Any = ( + auth.store + if auth is not None + else getattr(getattr(request.app.state, "engine", None), "store", None) + ) + if store is None: return - store = auth.store + client = client_ip(request) pager = getattr(store, "seal_pager", None) if callable(pager): # SealPager's page methods never raise. diff --git a/tests/test_api_auth.py b/tests/test_api_auth.py index accd272078..db08310011 100644 --- a/tests/test_api_auth.py +++ b/tests/test_api_auth.py @@ -247,9 +247,9 @@ async def test_the_api_backstop_reports_and_answers_every_seal_refusal_type( """Vault BACKLOG #8202 item 161, ADR 0217 (c) item 3: a seal refusal no route answered reaches the API's backstop, which pages and audits it under its own cause before it answers: Forged 409 with ``main``'s text, Unverifiable 409 with the recovery text, Outage 503 with ``Retry-After``, - never the generic 500. Every refusal is logged. The page and the row are throttled per row - where the refusal names one, else per route and client address, so a second address is - reported on its own; no Outage writes a seal failure.""" + never the generic 500. Every refusal is logged with its raising site. The page and the row are + throttled per row where the refusal names one, else per route, so a second caller address + within the window is logged only; no Outage writes a seal failure.""" from messagefoundry.auth.service import ( AUTHORITY_SEAL_FAILED_ACTION, AUTHORITY_SEAL_UNVERIFIABLE_ACTION, @@ -287,6 +287,8 @@ async def refused(_user_id: str) -> list[Any]: ] assert len(logged) == 3 # every refusal is logged, throttled or not assert all((r.levelno == logging.WARNING) == (cause == "forged") for r in logged) + assert all("GET /me/sessions, raised at " in r.getMessage() for r in logged) + assert all(".refused:" in r.getMessage() for r in logged) # the frame that raised actions = { "forged": AUTHORITY_SEAL_FAILED_ACTION, @@ -309,23 +311,22 @@ async def refused(_user_id: str) -> list[Any]: if cause == "forged": assert "integrity check" in detail assert "u-synthetic" not in json.dumps([r.json() for r in answers]) - # A refusal that names its row is reported once for it; one that names none, once per address. - names_row = cause in ("forged", "unverifiable-write") - assert len(rows) == (1 if names_row else 2) - assert {r["client"] for r in rows} <= {"127.0.0.1", "127.0.0.2"} + # Reported once in the window: per row where the refusal names one, else per route. + assert len(rows) == 1 + assert rows[0]["client"] == "127.0.0.1" detail = json.loads(str(rows[0]["detail"])) assert detail["during"] == "api" and detail["route"] == "/me/sessions" if cause == "outage": - assert pages == [TRANSIT_OUTAGE_SUBJECT] * 2 + assert pages == [TRANSIT_OUTAGE_SUBJECT] for action in (AUTHORITY_SEAL_FAILED_ACTION, AUTHORITY_SEAL_UNVERIFIABLE_ACTION): assert await engine.store.list_audit(action=action, limit=50) == [] else: assert detail["kind"] == "user" if cause == "unverifiable-read": - assert "user_id" not in detail - assert pages == [f"{UNVERIFIABLE_SUBJECT_PREFIX}:*"] * 2 + assert "subject" not in detail + assert pages == [f"{UNVERIFIABLE_SUBJECT_PREFIX}:*"] else: - assert detail["user_id"] == "u-synthetic" + assert detail["subject"] == "u-synthetic" if cause == "unverifiable-write": assert len(pages) == 1 and pages[0].startswith(f"{UNVERIFIABLE_SUBJECT_PREFIX}:user:") if cause.startswith("unverifiable"): diff --git a/tests/test_transit_approval_gate.py b/tests/test_transit_approval_gate.py index d52affddc7..0bce8b6dea 100644 --- a/tests/test_transit_approval_gate.py +++ b/tests/test_transit_approval_gate.py @@ -185,24 +185,29 @@ async def test_an_outage_refuses_the_route_with_a_503_audits_the_refusal_and_rec ] -async def test_each_outage_refused_call_writes_its_own_audit_row( +async def test_each_outage_refused_request_is_audited_once_per_window_and_paged_each_time( transit: tuple[MessageStore, FakeBackend, Path], ) -> None: - """Vault BACKLOG #8202 item 146: the refused request itself is audited, so a second refused - call writes a second row rather than riding on a throttle.""" + """Vault BACKLOG #8202 item 146: each request an Outage refuses gets its own audit row, once + per report window, so a queue that reads on every page load does not wait on an audit append + each time; every refusal is still paged.""" store, backend, path = transit await _executing(store, path, "a-1") + await _executing(store, path, "a-2") store._row_sealer = TransitRowSealer(backend) + pages = _arm(store) gate = _gate(store) backend.down = True try: - for _ in range(2): + for approval_id in ("a-1", "a-1", "a-2"): with pytest.raises(ApprovalError): - await gate.interrupt_stranded("a-1", actor="op", actor_user_id="op-id") + await gate.interrupt_stranded(approval_id, actor="op", actor_user_id="op-id") finally: backend.down = False - assert len(await _rows(store, TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, "a-1")) == 2 + assert len(await _rows(store, TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, "a-1")) == 1 + assert len(await _rows(store, TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, "a-2")) == 1 + assert pages == [TRANSIT_OUTAGE_SUBJECT] * 3 def test_the_outage_retry_after_has_one_source() -> None: From 50369428a5690614b26a982450fe6a47e103d06f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 29 Nov 2026 22:20:08 -0600 Subject: [PATCH 6/7] Record the fail-before for the seal refusal audit work and the unrepaired round Fail-before, vault BACKLOG #8202 items 2, 145, 146, 153 and 161: with messagefoundry/api/approvals.py, messagefoundry/api/auth_routes.py and messagefoundry/store/store.py checked out at origin/main 84da2a4b932, and store/row_seal.py at this branch, which only adds the audit action constant the tests import, ten test cases: the five in tests/test_transit_approval_gate.py, the four of tests/test_api_auth.py::test_the_api_backstop_reports_and_answers_every_seal_refusal_type and tests/test_transit_row_seal_revoke.py::test_a_refusal_two_failed_attempts_met_is_reported_by_each_and_the_text_says_so ran 9 failed, 1 passed (the pre-existing Unverifiable test). One line per limb: item 146 "assert 0 == 1" (no outage audit row); item 145 "assert 'nothing was done' not in ..."; item 153 "assert not True" (the duplicate constant); item 161 "RowSealUnverifiableError: the user row's integrity seal cannot be verified" escaping to the generic handler, and "assert 0 == 3" for the Forged case's log lines; item 2 "assert 'reports each once' not in ...". At 6339bf1acbe: 10 passed. Review round-fa5ae8c7f3 ran on the pushed head after the round-2 fix commit and is shipped unrepaired; its findings are in the Builder's report. Proposed PR title: Audit Vault transit Outage refusals at the approval gate and answer every seal refusal type at the API backstop (BACKLOG #8202) Proposed banner #8202: PARTIAL. Built, each with a test that fails at origin/main 84da2a4b932 (9 failed, 1 passed there, 10 passed at 6339bf1acbe): item 146 (the approval gate writes a soft authority.seal_unavailable row, once per report interval per request, for a check an Outage refuses), item 145 (its page reason and 503 no longer say the request was refused or nothing was done), item 161 (the API backstop is registered for RowSealError, RowSealUnverifiableError and both Transit types, logs each refusal and pages and audits it throttled per row or per route), item 153 (one Retry-After source) and item 2 (the committing docstring claims the minimum). Open: item 10 (retired_transit_audit_keys needs config/settings.py and store/crypto_transit.py, outside this build), item 117 (owner), the unrepaired round-fa5ae8c7f3 findings filed under R2, and every other item, not reached. Verified-by: tests Verified-by: code-review xhigh From fcdec4e10cab400b659bba07e1ecf8af1102cf8d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 29 Nov 2026 22:33:55 -0600 Subject: [PATCH 7/7] Read the backstop's method from the scope so a WebSocket refusal is reported Starlette hands the seal backstop a WebSocket for a refusal on a WebSocket route such as /ws/stats, and a WebSocket has no method, so at 50369428a56 the handler raised AttributeError before it logged, paged or audited, and the handshake was not answered with origin/main's denial. The backstop now reads the method from the scope, falling back to the scope type, and otherwise reads only what both planes' HTTPConnection carries (scope, app, and the client through client_ip). Vault BACKLOG #8202, finding 1 of review round-fa5ae8c7f3, repaired at the Manager's direction past the two-round cap. New test tests/test_api_auth.py::test_the_api_backstop_reports_a_seal_refusal_on_a_websocket_route: at 50369428a56 1 failed ("AttributeError: 'WebSocket' object has no attribute 'method'"); at this commit 1 passed. Its 403 denial is the status origin/main answers, measured there. Proposed PR title: Audit Vault transit Outage refusals at the approval gate and answer every seal refusal type at the API backstop (BACKLOG #8202) Proposed banner #8202: PARTIAL. Built, each with a test that fails at origin/main 84da2a4b932 (9 failed, 1 passed there, 10 passed at 6339bf1acbe): item 146 (the approval gate writes a soft authority.seal_unavailable row, once per report interval per request, for a check an Outage refuses), item 145 (its page reason and 503 no longer say the request was refused or nothing was done), item 161 (the API backstop is registered for RowSealError, RowSealUnverifiableError and both Transit types, logs each refusal and pages and audits it throttled per row or per route, on HTTP and WebSocket routes; the WebSocket case fails at 50369428a56, 1 failed, and passes here), item 153 (one Retry-After source) and item 2 (the committing docstring claims the minimum). Open: item 10 (retired_transit_audit_keys needs config/settings.py and store/crypto_transit.py, outside this build), item 117 (owner), the other round-fa5ae8c7f3 findings filed under R2, and every other item, not reached. Verified-by: tests --- messagefoundry/api/auth_routes.py | 8 +++- tests/test_api_auth.py | 64 +++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/messagefoundry/api/auth_routes.py b/messagefoundry/api/auth_routes.py index 9e0e19bf45..d540b883d2 100644 --- a/messagefoundry/api/auth_routes.py +++ b/messagefoundry/api/auth_routes.py @@ -827,14 +827,20 @@ async def _row_seal_refused(request: Request, exc: Exception) -> Response: # _seal_report_key. An Outage's row is TRANSIT_OUTAGE_REFUSED_AUDIT_ACTION, never a seal # failure. The code that raised may have reported the same refusal already, so a refusal # can be reported twice. + # + # Starlette calls this for a WebSocket route too, with a WebSocket, which has no + # ``method`` (vault BACKLOG #8202, the round-fa5ae8c7f3 regression). So it reads only what + # both planes' HTTPConnection carries: ``scope``, ``app`` and, through client_ip, the + # client. A WebSocket's "method" is its scope type. assert isinstance(exc, _SEAL_BACKSTOP_TYPES) route = str(getattr(request.scope.get("route"), "path", "") or "an API route") + method = str(request.scope.get("method") or request.scope.get("type", "")).upper() refusal = _seal_backstop(exc, route) _log.log( logging.WARNING if refusal.cause == "forged" else logging.ERROR, "%s (%s %s, raised at %s; BACKLOG #2592, #5505)", refusal.reason, - scrub_log_argument(request.method), + scrub_log_argument(method), route, _raising_site(exc), ) diff --git a/tests/test_api_auth.py b/tests/test_api_auth.py index db08310011..d5c400ca23 100644 --- a/tests/test_api_auth.py +++ b/tests/test_api_auth.py @@ -335,6 +335,70 @@ async def refused(_user_id: str) -> list[Any]: assert pages == [AUTHORITY_SEAL_FAILED_SUBJECT] +def test_the_api_backstop_reports_a_seal_refusal_on_a_websocket_route( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + """Vault BACKLOG #8202, the round-fa5ae8c7f3 regression: Starlette hands the backstop a + ``WebSocket`` for a refusal on ``/ws/stats``, which has no ``method``. The backstop still logs, + pages and audits it, and the handshake is refused with the 403 denial response origin/main + answered (measured there). The control is the same socket opening before the refusal is + planted.""" + import functools + + from starlette.testclient import TestClient, WebSocketDenialResponse + + from messagefoundry.api import create_managed_app + from messagefoundry.auth.service import AUTHORITY_SEAL_FAILED_ACTION + from messagefoundry.store.row_seal import AUTHORITY_SEAL_FAILED_SUBJECT, RowSealError + + app = create_managed_app( + db_path=tmp_path / "ws-seal.db", + poll_interval=0.05, + auth_settings=AuthSettings( + require_mfa=False, notify_security_events=False, login_rate_limit_enabled=False + ), + egress_settings=EgressSettings(deny_by_default=False), + ) + with TestClient(app) as tc: + assert tc.portal is not None + auth = app.state.auth + tc.portal.call(functools.partial(_add, auth, "root", Role.ADMINISTRATOR)) + login = tc.post( + "/auth/login", json={"username": "root", "password": PW, "provider": "local"} + ) + assert login.status_code == 200, login.text + bearer = {"Authorization": f"Bearer {login.json()['token']}"} + with tc.websocket_connect("/ws/stats", headers=bearer) as ws: # the control + assert "outbox_by_status" in ws.receive_json() + + pages: list[str] = [] + auth.store.seal_pager().arm(lambda subject, _reason: pages.append(subject)) + + async def refused(_token: str) -> Any: + raise RowSealError("user", "u-synthetic") + + auth.identity_for_token = refused + caplog.set_level(logging.WARNING, logger="messagefoundry.api.auth_routes") + with ( + pytest.raises(WebSocketDenialResponse) as denied, + tc.websocket_connect("/ws/stats", headers=bearer), + ): + pass + rows = tc.portal.call( + functools.partial(auth.store.list_audit, action=AUTHORITY_SEAL_FAILED_ACTION, limit=50) + ) + assert denied.value.status_code == 403 + (line,) = [ + r.getMessage() + for r in caplog.records + if r.name == "messagefoundry.api.auth_routes" and "/ws/stats" in r.getMessage() + ] + assert "WEBSOCKET /ws/stats, raised at " in line + assert pages == [AUTHORITY_SEAL_FAILED_SUBJECT] + (row,) = rows + assert json.loads(str(row["detail"]))["route"] == "/ws/stats" + + async def test_security_events_feed_lists_callers_auth_events(engine: Engine) -> None: # WP-L3-05 (ASVS 6.3.5/6.3.7): /me/security-events surfaces the caller's own audited auth.* events. service = await _service(engine)