From 0b930a405fe87ef69b46d58e16ef695bd517df25 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:32:39 -0600 Subject: [PATCH 01/31] Vault token preflight: close the refusal gaps, bound the probes, report it in posture The Vault privilege preflight (ADR 0216) would have let an enforcing first deployment start on a token able to disable an audit device, seal Vault, read storage raw, start a root generation or rekey, delete or rewrite the store key, trim, import over, restore or export one version of it; and on a connector-secret token able to export the store key. - VAULT_ADMIN_PATHS asks about sys/audit, sys/seal, sys/raw, sys/generate-root and sys/rekey. - A Transit key is asked about trim, import, import_version, restore and versioned export, for every token, the other hop's keys included. - create, update, patch, delete, sudo or root on a Transit key's own path is in the refusing class; other extras there still warn. - VAULT_REFUSING_CLASS states the class once; the refusal and the AUDIT line use it. - A denied lookup-self says the policy-write check did not run, and serve_verdict says a hop judged on part of its token covers only that. - The probes run side by side, each bounded (a timeout only warns). - The audit row caps the refusing reasons; the log caps the detail. - GET /security/posture carries vault_privilege. Seam bumped. BACKLOG #4851 Verified-by: tests --- messagefoundry/api/_ui_seam.py | 2 +- messagefoundry/api/app.py | 27 +- messagefoundry/api/models.py | 33 ++ messagefoundry/privilege_check.py | 102 +++++-- messagefoundry/privilege_probes.py | 34 ++- messagefoundry/vault_preflight.py | 77 +++-- messagefoundry_webconsole/__init__.py | 2 +- tests/golden/webconsole_seam.snapshot | 6 +- tests/test_vault_ldap_privilege_probes.py | 5 +- tests/test_vault_privilege_preflight_4851.py | 303 +++++++++++++++++++ 10 files changed, 544 insertions(+), 47 deletions(-) create mode 100644 tests/test_vault_privilege_preflight_4851.py diff --git a/messagefoundry/api/_ui_seam.py b/messagefoundry/api/_ui_seam.py index fca7544d2b..ab64d3f20a 100644 --- a/messagefoundry/api/_ui_seam.py +++ b/messagefoundry/api/_ui_seam.py @@ -1016,7 +1016,7 @@ #: proof is that commit 40a4d5d9 added a REQUIRED ``UploadedFileList.scope`` field the console renders #: unconditionally while touching no seam file at all. Regenerate with #: ``python scripts/webconsole_seam_snapshot.py --write``; never hand-edit it to silence a gate. -ENGINE_UI_SEAM: str = "4033184244d47e90" +ENGINE_UI_SEAM: str = "c4b5ccf2426b91bb" @dataclass(frozen=True, slots=True) diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index d2d994c527..73f12a6f63 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -234,6 +234,8 @@ UploadedMessageSummary, UploadResendRequest, UploadResendResult, + VaultPrivilegeHopView, + VaultPrivilegeView, ) from messagefoundry.api.multipart import ( MultipartError, @@ -6017,6 +6019,27 @@ async def security_posture( detail=store_privilege.detail, ) ) + # Vault BACKLOG #4851: each Vault token as the startup preflight judged it; None means no + # preflight ran in this process, which reads as not_probed, never as clean. + vault_privilege = getattr(request.app.state, "vault_privilege", None) + vault_privilege_view = ( + VaultPrivilegeView(status=STORE_PRIVILEGE_NOT_PROBED) + if vault_privilege is None + else VaultPrivilegeView( + status="probed", + hops=[ + VaultPrivilegeHopView( + hop=h.hop, + state=h.state.value, + refusing=list(h.refusing), + unexcused=list(h.unexcused), + partial=h.partial, + detail=h.detail, + ) + for h in vault_privilege + ], + ) + ) # FIPS-provider attestation of the interpreter's ssl/_hashlib OpenSSL (report-only, #73 / ADR 0120): # metadata (a boolean + version string), never key material, never enforced. fips_mode, openssl_version = fips_attestation() @@ -6064,6 +6087,7 @@ async def security_posture( loosenings=loosenings, loosenings_scope=loosenings_scope, store_privilege=store_privilege_view, + vault_privilege=vault_privilege_view, static_credential_hops=static_hops, static_credential_hops_scope=static_hops_scope, interpreter=interpreter_view, @@ -13936,7 +13960,8 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: ) ).posture() if static_credential_settings is not None: - await run_vault_privilege_preflight( + # Vault BACKLOG #4851: kept for GET /security/posture, as the store's is above. + app.state.vault_privilege = await run_vault_privilege_preflight( static_credential_settings, store, enforcing=_enforcing, diff --git a/messagefoundry/api/models.py b/messagefoundry/api/models.py index c62b478490..7f76048244 100644 --- a/messagefoundry/api/models.py +++ b/messagefoundry/api/models.py @@ -1563,6 +1563,34 @@ class StorePrivilegeView(BaseModel): detail: str = "" +class VaultPrivilegeHopView(BaseModel): + """One Vault token as the startup preflight judged it (vault BACKLOG #4851, ADR 0216). + + ``state`` is a :class:`~messagefoundry.privilege_check.HopState` value. ``refusing`` holds the + reasons in the class that refuses an enforcing start, ``unexcused`` each probe failure that + left the token unjudged, and ``partial`` says part of the token could not be read. ``detail`` + names policy names, paths and capabilities, never a token, an accessor or a digest of either.""" + + hop: str + state: str + refusing: list[str] = Field(default_factory=list) + unexcused: list[str] = Field(default_factory=list) + partial: bool = False + detail: str = "" + + +class VaultPrivilegeView(BaseModel): + """What the startup preflight read of each Vault token the engine uses (vault BACKLOG #4851). + + ``status`` is ``probed`` (the preflight ran; ``hops`` holds one entry per token, and is empty + when no Vault consumer is configured) or ``not_probed`` (no preflight ran in this process: an + embedding, or an app built without the service settings that name the tokens). ``not_probed`` + is never a pass.""" + + status: str + hops: list[VaultPrivilegeHopView] = Field(default_factory=list) + + class StartupCodeItemView(BaseModel): """One file that runs when the engine's interpreter starts (vault BACKLOG #2701): a ``.pth`` file with an ``import`` line, or a ``sitecustomize`` / ``usercustomize`` module. @@ -1721,6 +1749,11 @@ class SecurityPosture(BaseModel): store_privilege: StorePrivilegeView = Field( default_factory=lambda: StorePrivilegeView(status=STORE_PRIVILEGE_NOT_PROBED) ) + # Vault BACKLOG #4851 (ADR 0216): each Vault token as the startup preflight judged it. The + # default is the explicit ``not_probed`` status, as for ``store_privilege`` above. + vault_privilege: VaultPrivilegeView = Field( + default_factory=lambda: VaultPrivilegeView(status=STORE_PRIVILEGE_NOT_PROBED) + ) # BACKLOG #1182 (ASVS 13.2.1): every backend hop that presents an unchanging credential or none. # This is the INVENTORY, reported whether or not the opt-in refusal # ([security].require_nonstatic_credentials, echoed in `security` above) is on. The scope is always diff --git a/messagefoundry/privilege_check.py b/messagefoundry/privilege_check.py index deb26ed5ab..f1f4e9dd8e 100644 --- a/messagefoundry/privilege_check.py +++ b/messagefoundry/privilege_check.py @@ -68,6 +68,7 @@ "EXIT_UNOBSERVABLE", "VAULT_ADMIN_PATHS", "VAULT_OVER_GRANT_OPT_OUT", + "VAULT_REFUSING_CLASS", "HopPrivilege", "HopState", "VaultConsumer", @@ -127,7 +128,10 @@ class HopPrivilege: ``unexcused`` names each probe failure on a Vault hop that is not a network failure, a timeout or a 403 (:func:`~messagefoundry.privilege_probes.excused_failure`). It left the token unjudged, - so it refuses a start under ``enforce`` (:func:`vault_preflight_outcome`).""" + so it refuses a start under ``enforce`` (:func:`vault_preflight_outcome`). + + ``partial`` is true when part of a Vault token could not be read, whatever the hop's state, so + an over-grant seen on what WAS read is not taken for the whole token (vault BACKLOG #4851).""" hop: str state: HopState @@ -136,6 +140,7 @@ class HopPrivilege: detail: str refusing: tuple[str, ...] = () unexcused: tuple[str, ...] = () + partial: bool = False def as_dict(self) -> dict[str, str | list[str]]: return { @@ -210,10 +215,12 @@ def store_hop(report: StorePrivilegeReport, store: StoreSettings) -> HopPrivileg # --- Vault: one hop per token ------------------------------------------------------------------ #: Paths the engine never calls, asked about in the same capabilities read as the paths it does. -#: Any capability but ``deny`` on one means the token can widen its own reach: write a policy -#: (``sys/policies/acl/`` and the older ``sys/policy/``), attach a policy through an identity group, -#: mount a secrets or auth engine, or mint a token. The names after the last slash are placeholders -#: no deployment uses; Vault answers with the policy that would apply to them. +#: Any capability but ``deny`` on one means the token can widen its own reach or run Vault itself: +#: write a policy (``sys/policies/acl/`` and the older ``sys/policy/``), attach a policy through an +#: identity group, mount a secrets or auth engine, mint a token, turn an audit device off, seal +#: Vault, read or write its storage raw, or start a root-token generation or a rekey (vault BACKLOG +#: #4851). The names after the last slash are placeholders no deployment uses; Vault answers with +#: the policy that would apply to them. VAULT_ADMIN_PATHS: tuple[str, ...] = ( "sys/policies/acl/messagefoundry-check-privileges", "sys/policy/messagefoundry-check-privileges", @@ -222,29 +229,60 @@ def store_hop(report: StorePrivilegeReport, store: StoreSettings) -> HopPrivileg "sys/mounts/messagefoundry-check-privileges", "sys/auth/messagefoundry-check-privileges", "auth/token/create", + "sys/audit/messagefoundry-check-privileges", + "sys/seal", + "sys/raw/messagefoundry-check-privileges", + "sys/generate-root/attempt", + "sys/rekey/init", ) -#: The Transit operations on a key the engine uses that would let a token change the key or take it -#: out of Vault: its config (which can set ``exportable``), a rotation, an export and a backup. +#: The Transit operations on a key the engine uses that would let a token change the key, replace +#: it or take it out of Vault: its config (which can set ``exportable``), a rotation, a trim of its +#: old versions, an import over it, an export of the latest or of one version (``latest`` stands +#: for any version a ``*`` or ``+`` grant would match), a backup and a restore (vault BACKLOG #4851). _TRANSIT_KEY_ADMIN = ( "{mount}/keys/{key}/config", "{mount}/keys/{key}/rotate", + "{mount}/keys/{key}/trim", + "{mount}/keys/{key}/import", + "{mount}/keys/{key}/import_version", "{mount}/export/encryption-key/{key}", + "{mount}/export/encryption-key/{key}/latest", "{mount}/export/hmac-key/{key}", + "{mount}/export/hmac-key/{key}/latest", "{mount}/backup/{key}", + "{mount}/restore/{key}", +) + +#: The capabilities on a Transit key's own path (``/keys/``) that create, rewrite or +#: delete the key. The engine needs only ``read`` there, so any of these is in the refusing class +#: (vault BACKLOG #4851); any other extra capability there only warns. +_TRANSIT_KEY_CONTROL_CAPS = frozenset({"create", "update", "patch", "delete", "sudo", "root"}) + +#: The refusing class, in the words every refusal and audit line uses, stated once here (ADR 0216). +VAULT_REFUSING_CLASS = ( + "the root policy, or a grant on an administrative path, on a Transit key's control, export, " + "backup or restore path, or one that creates, rewrites or deletes a Transit key" ) def vault_admin_paths( - required: Mapping[str, frozenset[str]], policies: Iterable[str], *, transit_mount: str + required: Mapping[str, frozenset[str]], + policies: Iterable[str], + *, + transit_mount: str, + other_keys: Iterable[str] = (), ) -> tuple[str, ...]: """Every path to ask a token about that the engine never calls, in a fixed order. :data:`VAULT_ADMIN_PATHS`, then a write of each policy the token carries (``sys/policies/acl/`` and ``sys/policy/``), which the placeholder names cannot catch when a policy grants writes only - on names like its own, then each Transit key's config, rotate, export and backup paths, which - would let the token make the store key exportable and read it out. At least these: grants on - other paths are not read.""" + on names like its own, then each Transit key's control, export, backup and restore paths + (:data:`_TRANSIT_KEY_ADMIN`), which would let the token make the store key exportable and read + it out. The keys are the ones ``required`` names, and the ones ``other_keys`` names: the Transit + key paths ANOTHER hop requires, so a token that never calls the store key is still asked + whether it can export it (vault BACKLOG #4851). At least these: grants on other paths are not + read.""" out = list(VAULT_ADMIN_PATHS) for policy in policies: if policy != "root": # root is judged on its own, and has no path to write @@ -252,7 +290,7 @@ def vault_admin_paths( # ``transit_mount`` is the caller's: the Transit mount the providers call, so this module stays # free of the Vault provider imports. prefix = f"{transit_mount}/keys/" - for path in required: + for path in [*required, *other_keys]: # Only the Transit mount's key metadata path, /keys/ with no further segment: # a KV path whose mount happens to contain "keys" is not a Transit key. key = path.removeprefix(prefix) @@ -434,8 +472,17 @@ def vault_hop( got = set(reading.capabilities[path]) excess = got - needed - {"deny"} # needed never holds root, so a root grant is excess missing = set() if "root" in got else needed - got - if excess: - over.append(f"{path} also grants {_caps(excess)} (needs {_caps(needed)})") + # A Transit key's own path is one whose config path was asked about too, so no mount name + # is needed here to tell it from a KV path. + is_key = f"{path}/config" in reading.admin_paths + control = excess & _TRANSIT_KEY_CONTROL_CAPS if is_key else set() + if control: + grave.append( + f"{path} grants {_caps(control)}, which creates, rewrites or deletes the key " + f"(needs {_caps(needed)})" + ) + if excess - control: + over.append(f"{path} also grants {_caps(excess - control)} (needs {_caps(needed)})") if missing: notes.append(f"{path} lacks {_caps(missing)}, so the engine's own call would fail") for path in reading.admin_paths: @@ -450,6 +497,14 @@ def vault_hop( f"the same token serves {other_hop}, so it also holds {_caps(extra)} on {path}" ) + unread = list(reading.problems) + if not reading.looked_up and reading.capabilities: + # The policy names come from lookup-self, so without it a write of the token's own + # policies was never asked about (vault BACKLOG #4851). Said, so a reading that is + # otherwise clean is not taken for one. + unread.append( + "the token's own policies are unknown, so whether it can rewrite them was not asked" + ) seen: list[str] = [] if reading.looked_up: if reading.ttl == 0: @@ -468,7 +523,7 @@ def vault_hop( seen.append("; ".join(f"{p}: {_caps(reading.capabilities[p])}" for p in checked)) if grave or over: state = HopState.OVER_GRANTED - elif reading.problems or reading.unexcused: + elif unread or reading.unexcused: state = HopState.UNOBSERVABLE else: state = HopState.CLEAN @@ -478,7 +533,7 @@ def vault_hop( *seen, *notes, ] - parts += [f"could not observe: {p}" for p in reading.problems] + parts += [f"could not observe: {p}" for p in unread] if state is HopState.CLEAN: parts.append( "paths the engine does not call were read only for the administrative ones; " @@ -496,6 +551,7 @@ def vault_hop( detail, refusing=tuple(grave), unexcused=reading.unexcused, + partial=bool(unread), ) @@ -557,8 +613,8 @@ def vault_refusal_reason(hops: Iterable[HopPrivilege], *, over_grant_accepted: b reasons: list[str] = [] if granted: reasons.append( - f"a Vault token on {', '.join(granted)} holds the root policy or a grant on an " - "administrative path, under [security].enforcement = 'enforce'. Reduce the token's " + f"a Vault token on {', '.join(granted)} holds {VAULT_REFUSING_CLASS}, under " + "[security].enforcement = 'enforce'. Reduce the token's " f"policy to the grant docs/SECURITY.md prescribes, or set {VAULT_OVER_GRANT_OPT_OUT} " "= true to accept it (audited)" ) @@ -810,6 +866,7 @@ def serve_verdict( vault: dict[PreflightOutcome, list[str]] = {} refused_hops: list[HopPrivilege] = [] unread: list[str] = [] + partly: list[str] = [] unjudged = [h for h in hops if h.hop.startswith("vault") and h.unexcused] for h in hops: if not h.hop.startswith("vault"): @@ -822,6 +879,8 @@ def serve_verdict( # The grants seen are judged here; an unexcused failure is named in a note instead, since # this run's environment may meet one serve's does not, such as an unset key name. judged = replace(h, unexcused=()) + if h.partial: + partly.append(h.hop) outcome = vault_preflight_outcome( judged, enforcing=enforcing, over_grant_accepted=accepting ) @@ -848,6 +907,13 @@ def serve_verdict( ) if warned := vault.get(PreflightOutcome.WARN): notes.append(f"{', '.join(warned)} warns only; it does not refuse a start") + if partly: + # Judged on part of its token: what was not read may hold a grant that refuses (vault + # BACKLOG #4851), so the verdict covers only what was read. + notes.append( + f"part of the token on {', '.join(partly)} could not be read here, so the verdict on " + "it covers only what was read" + ) if unread: notes.append( f"{', '.join(unread)} could not be read here, so this line cannot say what serve " diff --git a/messagefoundry/privilege_probes.py b/messagefoundry/privilege_probes.py index 60d7471953..3105d70ce1 100644 --- a/messagefoundry/privilege_probes.py +++ b/messagefoundry/privilege_probes.py @@ -36,7 +36,7 @@ import hashlib import logging import socket -from collections.abc import Callable, Mapping +from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any @@ -285,6 +285,7 @@ def read_vault_token( address: Callable[[], str], build_client: Callable[[str, str], Any], required: Callable[[], Mapping[str, frozenset[str]]], + other_keys: Callable[[], Iterable[str]] | None = None, ) -> VaultTokenReading: """Read one token's own policies and capabilities through the engine's client for that hop. @@ -296,6 +297,11 @@ def read_vault_token( ``config/secretprovider_vault.py``). The variables and the paths are all read before anything is returned, so one run names every one that is missing. + ``other_keys`` returns the Transit key paths another hop requires, so this token is asked + about their control and export paths too (vault BACKLOG #4851). A failure to name them is a + problem of that other hop, which reports it on its own reading; here it is logged and the + token is asked about its own keys alone. + Every failure is recorded as a problem. One that :func:`excused_failure` does not excuse is also named in ``unexcused``, so a code defect swallowed here still refuses an enforcing start.""" problems: list[str] = [] @@ -374,7 +380,13 @@ def why(exc: BaseException) -> str: from messagefoundry.store.keyprovider_vault import TRANSIT_MOUNT - admin = vault_admin_paths(needed, policies, transit_mount=TRANSIT_MOUNT) + foreign: tuple[str, ...] = () + if other_keys is not None: + try: + foreign = tuple(other_keys()) + except Exception as exc: # noqa: BLE001 - the other hop's own reading reports it + logger.info("privilege probe: another hop's Transit keys not named: %s", _why(exc)) + admin = vault_admin_paths(needed, policies, transit_mount=TRANSIT_MOUNT, other_keys=foreign) capabilities: dict[str, tuple[str, ...]] = {} paths = [*needed, *admin] try: @@ -442,6 +454,7 @@ def probe_vault( posture=posture, ), lambda: kv_required_capabilities(consumer.refs), + other_keys=functools.partial(_store_transit_keys, settings), ) from messagefoundry.store.keyprovider_vault import ( kek_required_capabilities, @@ -473,6 +486,23 @@ def probe_vault( raise ValueError(f"no Vault probe for consumer kind {kind!r}") +def _store_transit_keys(settings: ServiceSettings) -> tuple[str, ...]: + """The Transit key paths the store hop requires, or none when the store uses no Vault key. + The connector-secret token is asked about these keys' control and export paths too, so a token + that never calls the store key still reads over-granted when it can export it (vault BACKLOG + #4851). Raises as the store's own required-path helper does, for an unset key name.""" + store = settings.store + if store.cipher_provider == "vault_transit": + from messagefoundry.store.crypto_transit import transit_cipher_required_capabilities + + return tuple(transit_cipher_required_capabilities()) + if store.key_provider == "vault": + from messagefoundry.store.keyprovider_vault import kek_required_capabilities + + return tuple(kek_required_capabilities()) + return () + + def read_ldap_bind(settings: ServiceSettings, posture: HopPosture | None) -> BindAccountReading: """Build the AD authenticator with the arguments ``AuthService`` gives it and read its bind account. The bind password resolves through ``[secrets]`` as it does under ``serve``, except diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index 48fad32259..b1770e9444 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -48,6 +48,7 @@ from messagefoundry.controlchars import scrub_log_argument from messagefoundry.privilege_check import ( VAULT_OVER_GRANT_OPT_OUT, + VAULT_REFUSING_CLASS, HopPrivilege, HopState, VaultConsumer, @@ -77,11 +78,22 @@ #: The audit action of the row each probed Vault hop writes at every start. VAULT_PRIVILEGE_AUDIT_ACTION = "vault_privilege_preflight" -#: The longest hop detail an audit row keeps. The detail lists each path asked about with its -#: capabilities, so a token with many policies makes a long one; the refusing reasons are kept -#: whole in their own field. +#: The longest hop detail an audit row or a log line keeps. The detail lists each path asked about +#: with its capabilities, so a token with many policies makes a long one. _AUDIT_DETAIL_LIMIT = 2000 +#: The most refusing reasons an audit row lists, and the longest each one is kept (vault BACKLOG +#: #4851). A reason names a server-chosen policy name or path, so neither is bounded by the server; +#: the row's ``refusing_count`` keeps the true number. +_AUDIT_REFUSING_LIMIT = 20 +_AUDIT_REASON_LIMIT = 300 + +#: How long, in seconds, the preflight waits for each Vault probe (vault BACKLOG #4851). The probes +#: run side by side, so this is about the longest a start waits on them all. Each probe sends two +#: requests on a client with hvac's 30-second default; this bounds the rest too, such as a name +#: that does not resolve. +VAULT_PROBE_TIMEOUT_S = 75.0 + class VaultPrivilegeError(RuntimeError): """Raised by the preflight when ``vault_preflight_outcome`` refuses a Vault hop under @@ -143,26 +155,47 @@ def _alert(sink: VaultPrivilegeAlertSink, hop: HopPrivilege, outcome: PreflightO log.exception("vault privilege preflight: the alert sink raised") -def _probe_all( - consumers: list[VaultConsumer], probe: Callable[[VaultConsumer], VaultTokenReading] -) -> list[VaultTokenReading]: - """Each consumer's reading. A probe that raises never aborts the start here: the probe reports +def _probe_one( + consumer: VaultConsumer, probe: Callable[[VaultConsumer], VaultTokenReading] +) -> VaultTokenReading: + """One consumer's reading. A probe that raises never aborts the start here: the probe reports its own failures, but a token re-read or an unrouted consumer kind can still raise, and under ``enforcement = warn`` nothing here may refuse. The raise becomes a reading with one problem. Unless :func:`~messagefoundry.privilege_probes.excused_failure` excuses it, the reading also names it in ``unexcused``, which refuses under ``enforce``: a code defect is never a pass. Only the exception's type is kept, so no library or server text reaches the log or the audit row.""" - out: list[VaultTokenReading] = [] - for consumer in consumers: + try: + return probe(consumer) + except Exception as exc: # noqa: BLE001 - classified below, never a pass + problem = f"the probe raised {type(exc).__name__}" + log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) + cause = unexcused_cause(exc) + unexcused = () if cause is None else (cause,) + return VaultTokenReading(problems=(problem,), unexcused=unexcused) + + +async def _probe_all( + consumers: list[VaultConsumer], + probe: Callable[[VaultConsumer], VaultTokenReading], + timeout: float, +) -> list[VaultTokenReading]: + """Every consumer's reading, the probes run side by side, each off the event loop and each + bounded by ``timeout`` seconds (vault BACKLOG #4851). A probe still running at the bound reads + as a timeout, which the owner ruling of 2026-10-04 lets only warn. Its thread cannot be + stopped and runs on until the client's own request timeouts end it; nothing waits on it, and + its reading is dropped.""" + + async def bounded(consumer: VaultConsumer) -> VaultTokenReading: try: - out.append(probe(consumer)) - except Exception as exc: # noqa: BLE001 - classified below, never a pass - problem = f"the probe raised {type(exc).__name__}" + return await asyncio.wait_for( + asyncio.to_thread(_probe_one, consumer, probe), timeout=timeout + ) + except TimeoutError: + problem = f"the probe did not finish within {timeout:g}s (a timeout)" log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) - cause = unexcused_cause(exc) - unexcused = () if cause is None else (cause,) - out.append(VaultTokenReading(problems=(problem,), unexcused=unexcused)) - return out + return VaultTokenReading(problems=(problem,)) + + return list(await asyncio.gather(*(bounded(c) for c in consumers))) async def run_vault_privilege_preflight( @@ -173,6 +206,7 @@ async def run_vault_privilege_preflight( over_grant_accepted: bool, probe: Callable[[VaultConsumer], VaultTokenReading], alert_sink: VaultPrivilegeAlertSink | None = None, + probe_timeout: float = VAULT_PROBE_TIMEOUT_S, ) -> list[HopPrivilege]: """Probe every Vault token ``settings`` puts to use, report each, and refuse where :func:`~messagefoundry.privilege_check.vault_preflight_outcome` says so. @@ -191,7 +225,7 @@ async def run_vault_privilege_preflight( consumers = vault_consumers(settings) if not consumers: return [] - readings = await asyncio.to_thread(_probe_all, consumers, probe) + readings = await _probe_all(consumers, probe, probe_timeout) hops = vault_hops(consumers, readings) outcomes = [ vault_preflight_outcome(hop, enforcing=enforcing, over_grant_accepted=over_grant_accepted) @@ -211,23 +245,24 @@ async def run_vault_privilege_preflight( hop.hop, hop.state.value, enforcing, - scrub_log_argument(hop.detail), + scrub_log_argument(hop.detail[:_AUDIT_DETAIL_LIMIT]), "; REFUSING to start" if refusing else "", ) if accepted: log.warning( "AUDIT: starting an enforcing instance on an over-granted Vault token (%s) because " - "%s=true -- the token holds the root policy or a grant on an administrative path " - "(Vault privilege opt-out override)", + "%s=true -- the token holds %s (Vault privilege opt-out override)", hop.hop, VAULT_OVER_GRANT_OPT_OUT, + VAULT_REFUSING_CLASS, ) if alert_sink is not None: _alert(alert_sink, hop, outcome) detail = { "hop": hop.hop, "state": hop.state.value, - "refusing": list(hop.refusing), + "refusing": [r[:_AUDIT_REASON_LIMIT] for r in hop.refusing[:_AUDIT_REFUSING_LIMIT]], + "refusing_count": len(hop.refusing), "unexcused": list(hop.unexcused), "detail": hop.detail[:_AUDIT_DETAIL_LIMIT], "enforcing": enforcing, diff --git a/messagefoundry_webconsole/__init__.py b/messagefoundry_webconsole/__init__.py index 603ff5201b..f45db2dedf 100644 --- a/messagefoundry_webconsole/__init__.py +++ b/messagefoundry_webconsole/__init__.py @@ -45,7 +45,7 @@ # If cross-seam support is ever genuinely wanted, re-widen this set AND add the CI matrix that # installs the MIN and MAX supported engine builds — the claim and its test land together, or not # at all. -SUPPORTED_ENGINE_SEAMS: frozenset[str] = frozenset({"4033184244d47e90"}) +SUPPORTED_ENGINE_SEAMS: frozenset[str] = frozenset({"c4b5ccf2426b91bb"}) #: The vendored static assets shipped in THIS wheel (mounted at /ui/static by :func:`mount_ui`). STATIC_DIR = Path(__file__).parent / "static" diff --git a/tests/golden/webconsole_seam.snapshot b/tests/golden/webconsole_seam.snapshot index ec4b374410..3e0d631bfe 100644 --- a/tests/golden/webconsole_seam.snapshot +++ b/tests/golden/webconsole_seam.snapshot @@ -7,7 +7,7 @@ # by hand (BACKLOG #1220) - so a newly rendered DTO is covered with nobody editing a list. ## ENGINE_UI_SEAM -4033184244d47e90 +c4b5ccf2426b91bb ## dataclass messagefoundry.api._ui_seam.UiDeps engine_seam @@ -331,7 +331,7 @@ messagefoundry.api.models.ResendRequest: idempotency_key, source, to messagefoundry.api.models.SearchPresetCreateRequest: criteria, name messagefoundry.api.models.SearchPresetCriteria: channel_id, content, control_id, field_path, field_value, limit, message_type, status, target messagefoundry.api.models.SecurityLoosening: risk, switch -messagefoundry.api.models.SecurityPosture: allow_unencrypted_phi, backend, client_address_monoculture, client_denied_last, client_network_denials, encryption_enabled, enforcement, environment, fips_mode, interpreter, kex_groups, key_id, key_source, loosenings, loosenings_scope, memory_encryption_note, memory_encryption_operator_declared, memory_encryption_readout_contradicts_declaration, memory_encryption_readout_source, memory_encryption_self_reported_active, memory_encryption_self_reported_capability, memory_encryption_self_reported_mechanism, openssl_version, plaintext_columns, production, require_encryption, security, static_credential_hops, static_credential_hops_scope, store_privilege, transit_bound_attestation, undeclared_route_refusals +messagefoundry.api.models.SecurityPosture: allow_unencrypted_phi, backend, client_address_monoculture, client_denied_last, client_network_denials, encryption_enabled, enforcement, environment, fips_mode, interpreter, kex_groups, key_id, key_source, loosenings, loosenings_scope, memory_encryption_note, memory_encryption_operator_declared, memory_encryption_readout_contradicts_declaration, memory_encryption_readout_source, memory_encryption_self_reported_active, memory_encryption_self_reported_capability, memory_encryption_self_reported_mechanism, openssl_version, plaintext_columns, production, require_encryption, security, static_credential_hops, static_credential_hops_scope, store_privilege, transit_bound_attestation, undeclared_route_refusals, vault_privilege messagefoundry.api.models.ServiceStatusInfo: enabled, service_name, state messagefoundry.api.models.StartupCodeItemView: expected, kind, owner, path, verdict messagefoundry.api.models.StaticCredentialHopView: accepted, compliant_kind, credential, detail, name @@ -347,6 +347,8 @@ messagefoundry.api.models.UploadedFileList: files, limit, offset, scope, total messagefoundry.api.models.UploadedMessageSearchRequest: content, control_id, field_path, field_value, limit, message_type, offset, target messagefoundry.api.models.UploadedMessageSummary: control_id, index, message_type, size messagefoundry.api.models.UploadedMessagesResult: file_id, filename, matched, messages, scanned, total_messages, truncated +messagefoundry.api.models.VaultPrivilegeHopView: detail, hop, partial, refusing, state, unexcused +messagefoundry.api.models.VaultPrivilegeView: hops, status ## enum members reachable from those DTOs messagefoundry.config.ai_policy.SecurityEnforcement: ENFORCE, WARN diff --git a/tests/test_vault_ldap_privilege_probes.py b/tests/test_vault_ldap_privilege_probes.py index 03bc1a5129..9badfe7d95 100644 --- a/tests/test_vault_ldap_privilege_probes.py +++ b/tests/test_vault_ldap_privilege_probes.py @@ -218,7 +218,10 @@ def test_a_root_capability_on_a_path_is_an_over_grant() -> None: caps = _least_caps() | {f"transit/keys/{_KEK}": ["root"]} hop = vault_hop(_STORE, _reading(_FakeVault(caps=caps))) assert hop.state is HopState.OVER_GRANTED - assert f"transit/keys/{_KEK} also grants root" in hop.detail + # On a Transit key's own path a root grant controls the key, so it is in the refusing class + # since vault BACKLOG #4851, worded as one. + assert f"transit/keys/{_KEK} grants root, which creates, rewrites or deletes" in hop.detail + assert hop.refusing def test_any_grant_on_an_administrative_path_is_an_over_grant() -> None: diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py new file mode 100644 index 0000000000..3ea186efa0 --- /dev/null +++ b/tests/test_vault_privilege_preflight_4851.py @@ -0,0 +1,303 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""Vault BACKLOG #4851: the open findings on the Vault token preflight (ADR 0216, #2903 slice A). + +In the conditional this repo requires (a not-deployed beta): an enforcing first deployment would +have started on a Vault token able to turn off an audit device, seal Vault, read its storage raw, +start a root-token generation or a rekey, delete or restore the store key, trim it or export one +version of it, and on a connector-secret token able to export the store key. ``GET +/security/posture`` would not have said what the preflight read, and a probe that hung would have +held the start for as long as hvac let it. + +Every Vault answer is MOCKED by the fake client the ``check-privileges`` tests use, and every token +is a synthetic string. No test opens a socket. +""" + +from __future__ import annotations + +import threading +import time +from pathlib import Path +from typing import Any + +import pytest + +from messagefoundry import vault_preflight +from messagefoundry.config.settings import SecuritySettings +from messagefoundry.privilege_check import ( + VAULT_REFUSING_CLASS, + HopState, + VaultConsumer, + serve_verdict, + vault_admin_paths, + vault_hop, + vault_preflight_outcome, +) +from messagefoundry.privilege_probes import VaultTokenReading, probe_vault, read_vault_token +from messagefoundry.store.privilege import PreflightOutcome +from messagefoundry.vault_preflight import VaultPrivilegeError, run_vault_privilege_preflight +from tests.test_vault_ldap_privilege_probes import ( + _KEK, + _TOKEN, + _VAULT_ADDR, + Forbidden, + _FakeVault, + _least_caps, + _reading, +) +from tests.test_vault_privilege_preflight import ( + _KV, + _KV_PATH, + _STORE, + _VAULT_SETTINGS, + _AuditStore, + _hop, + _managed_app, + _probe, + _sqlite_report, + _vault_env, +) + +# --- refusal gaps: sys paths and Transit key paths --------------------------------------------- + + +@pytest.mark.parametrize( + "path", + [ + "sys/audit/messagefoundry-check-privileges", + "sys/seal", + "sys/raw/messagefoundry-check-privileges", + "sys/generate-root/attempt", + "sys/rekey/init", + f"transit/keys/{_KEK}/trim", + f"transit/keys/{_KEK}/import", + f"transit/keys/{_KEK}/import_version", + f"transit/export/encryption-key/{_KEK}/latest", + f"transit/export/hmac-key/{_KEK}/latest", + f"transit/restore/{_KEK}", + ], +) +def test_each_newly_asked_path_is_in_the_refusing_class(path: str) -> None: + hop = _hop(caps=_least_caps() | {path: ["update"]}) + assert hop.state is HopState.OVER_GRANTED + assert any(r.startswith(f"{path} grants update") for r in hop.refusing) + assert vault_preflight_outcome(hop, enforcing=True, over_grant_accepted=False) is ( + PreflightOutcome.REFUSE + ) + + +@pytest.mark.parametrize("cap", ["delete", "update", "create"]) +def test_a_grant_that_deletes_or_rewrites_the_store_key_refuses(cap: str) -> None: + hop = _hop(caps=_least_caps() | {f"transit/keys/{_KEK}": ["read", cap]}) + assert hop.state is HopState.OVER_GRANTED + assert any(f"transit/keys/{_KEK} grants {cap}" in r for r in hop.refusing) + assert vault_preflight_outcome(hop, enforcing=True, over_grant_accepted=False) is ( + PreflightOutcome.REFUSE + ) + + +def test_list_beside_delete_on_the_key_splits_into_the_two_classes() -> None: + hop = _hop(caps=_least_caps() | {f"transit/keys/{_KEK}": ["delete", "list", "read"]}) + assert [r for r in hop.refusing if "list" in r] == [] + assert f"transit/keys/{_KEK} also grants list" in hop.detail + + +def test_a_kv_path_holding_delete_is_not_read_as_a_transit_key() -> None: + """The control: only a path whose config path was asked about is a Transit key.""" + vault = _FakeVault(caps={_KV_PATH: ["delete", "read"]}) + reading = read_vault_token( + lambda: _TOKEN, + lambda: _VAULT_ADDR, + lambda a, t: vault, + lambda: {_KV_PATH: frozenset({"read"})}, + ) + hop = vault_hop(_KV, reading) + assert hop.refusing == () + assert f"{_KV_PATH} also grants delete" in hop.detail + + +# --- a connector-secret token holding export on the store key ---------------------------------- + + +def _kv_reading(vault: _FakeVault, other_keys: Any = None) -> VaultTokenReading: + return read_vault_token( + lambda: _TOKEN, + lambda: _VAULT_ADDR, + lambda a, t: vault, + lambda: {_KV_PATH: frozenset({"read"})}, + other_keys=other_keys, + ) + + +def test_a_secrets_token_that_can_export_the_store_key_refuses() -> None: + export = f"transit/export/encryption-key/{_KEK}" + vault = _FakeVault(caps={_KV_PATH: ["read"], export: ["read"]}) + hop = vault_hop(_KV, _kv_reading(vault, other_keys=lambda: [f"transit/keys/{_KEK}"])) + assert any(r.startswith(f"{export} grants read") for r in hop.refusing) + # The control: without the store's key named, the same grant is never asked about. + alone = vault_hop(_KV, _kv_reading(_FakeVault(caps={_KV_PATH: ["read"], export: ["read"]}))) + assert alone.refusing == () + + +def test_a_failure_naming_the_other_hops_keys_still_reads_the_token() -> None: + def unset() -> list[str]: + raise ValueError("no key name") + + reading = _kv_reading(_FakeVault(caps={_KV_PATH: ["read"]}), other_keys=unset) + assert reading.capabilities and reading.problems == () + + +def test_probe_vault_hands_the_store_keys_to_the_secrets_probe( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("MEFOR_STORE_VAULT_TRANSIT_KEY", _KEK) + seen: dict[str, Any] = {} + + def fake(*args: Any, other_keys: Any = None) -> VaultTokenReading: + seen["keys"] = other_keys() if other_keys is not None else None + return VaultTokenReading() + + monkeypatch.setattr("messagefoundry.privilege_probes.read_vault_token", fake) + probe_vault(_KV, _VAULT_SETTINGS) + assert f"transit/keys/{_KEK}" in seen["keys"] + assert set(vault_admin_paths({}, (), transit_mount="transit", other_keys=seen["keys"])) >= { + f"transit/export/encryption-key/{_KEK}" + } + + +# --- a denied lookup-self ---------------------------------------------------------------------- + + +def test_a_denied_lookup_self_says_the_policy_write_check_did_not_run() -> None: + caps = _least_caps() | {f"transit/keys/{_KEK}": ["list", "read"]} + hop = _hop(caps=caps, lookup_error=Forbidden("denied")) + assert hop.partial + assert "whether it can rewrite them was not asked" in hop.detail + verdict = serve_verdict(_sqlite_report(), _VAULT_SETTINGS, [hop]) + assert "part of the token on vault.store could not be read here" in verdict + # The control: the same grant read whole says nothing of the kind. + whole = _hop(caps=caps) + assert not whole.partial + assert "could not be read" not in serve_verdict(_sqlite_report(), _VAULT_SETTINGS, [whole]) + + +# --- the refusal names the whole class --------------------------------------------------------- + + +async def test_the_refusal_names_the_transit_export_class() -> None: + caps = _least_caps() | {f"transit/export/encryption-key/{_KEK}": ["read"]} + with pytest.raises(VaultPrivilegeError) as refused: + await run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=_probe(_FakeVault(caps=caps)), + ) + assert VAULT_REFUSING_CLASS in str(refused.value) + assert "export" in VAULT_REFUSING_CLASS + + +# --- length caps ------------------------------------------------------------------------------- + + +async def test_the_audit_row_caps_the_refusing_reasons() -> None: + required = {p: frozenset(c) for p, c in _least_caps().items()} + every = vault_admin_paths(required, ("default", "x" * 500), transit_mount="transit") + caps = _least_caps() | {p: ["update"] for p in every} + store = _AuditStore() + with pytest.raises(VaultPrivilegeError): + await run_vault_privilege_preflight( + _VAULT_SETTINGS, + store, + enforcing=True, + over_grant_accepted=False, + probe=_probe(_FakeVault(caps=caps, policies=("default", "x" * 500))), + ) + [(_, detail)] = store.audits + assert detail["refusing_count"] > 20 + assert len(detail["refusing"]) == 20 + assert all(len(r) <= 300 for r in detail["refusing"]) + + +# --- the probes are bounded and run side by side ----------------------------------------------- + + +async def test_a_probe_that_hangs_is_cut_off_and_only_warns() -> None: + release = threading.Event() + + def hang(consumer: VaultConsumer) -> VaultTokenReading: + release.wait(10) + return VaultTokenReading() + + store = _AuditStore() + started = time.monotonic() + try: + hops = await run_vault_privilege_preflight( + _VAULT_SETTINGS, + store, + enforcing=True, + over_grant_accepted=False, + probe=hang, + probe_timeout=0.2, + ) + finally: + release.set() + assert time.monotonic() - started < 5 + [hop] = hops + assert hop.state is HopState.UNOBSERVABLE and hop.unexcused == () + assert "did not finish within 0.2s" in hop.detail + assert store.audits[0][1]["refused"] is False + + +async def test_the_probes_run_side_by_side(monkeypatch: pytest.MonkeyPatch) -> None: + """Two probes that each wait for the other finish only if they run at once.""" + monkeypatch.setattr(vault_preflight, "vault_consumers", lambda settings: [_STORE, _KV]) + barrier = threading.Barrier(2, timeout=5) + + def meet(consumer: VaultConsumer) -> VaultTokenReading: + barrier.wait() + return _reading(_FakeVault(caps=_least_caps())) + + hops = await run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=meet, + ) + assert [h.hop for h in hops] == ["vault.store", "vault.secrets"] + assert all("did not finish" not in h.detail for h in hops) + + +def test_the_default_bound_is_finite() -> None: + assert 0 < vault_preflight.VAULT_PROBE_TIMEOUT_S < 600 + + +# --- the result reaches GET /security/posture -------------------------------------------------- + + +def test_posture_reports_each_vault_token_the_preflight_read( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from starlette.testclient import TestClient + + caps = _least_caps() | {f"transit/keys/{_KEK}": ["list", "read"]} + _vault_env(monkeypatch, _FakeVault(caps=caps)) + with TestClient(_managed_app(tmp_path, SecuritySettings())) as client: + resp = client.get("/security/posture") + assert resp.status_code == 200, resp.text + view = resp.json()["vault_privilege"] + assert view["status"] == "probed" + [hop] = view["hops"] + assert hop["hop"] == "vault.store" and hop["state"] == "over_granted" + assert hop["refusing"] == [] and "also grants list" in hop["detail"] + assert _TOKEN not in resp.text + + +async def test_posture_without_a_preflight_says_not_probed() -> None: + from messagefoundry.api.models import SecurityPosture + + fields = SecurityPosture.model_fields + default = fields["vault_privilege"].get_default(call_default_factory=True) + assert default.status == "not_probed" and default.hops == [] From 8c8286f5ee11ccac74911b0a5231f2d6362525a9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:39:51 -0600 Subject: [PATCH 02/31] Vault token preflight docs: the wider refusing class, the bound, the posture field SECURITY.md lists the sys paths and Transit key paths now asked about, the key-control grants, the 75-second bound, the denied lookup-self and the posture field. SECURITY-LOOSENING.md links the class rather than restating it. The vault_hop and vault_preflight docstrings name VAULT_REFUSING_CLASS, and the preflight's says why the token it re-reads is the one the provider read. crypto_inventory_check's two privilege probe comments name serve's preflight and the second client. A changelog fragment. BACKLOG #4851 Verified-by: tests --- ...1-vault-preflight-refusal-gaps.security.md | 1 + docs/SECURITY-LOOSENING.md | 7 ++++--- docs/SECURITY.md | 21 +++++++++++++++---- messagefoundry/privilege_check.py | 8 +++---- messagefoundry/vault_preflight.py | 12 +++++++---- scripts/security/crypto_inventory_check.py | 12 ++++++----- 6 files changed, 41 insertions(+), 20 deletions(-) create mode 100644 changelog.d/4851-vault-preflight-refusal-gaps.security.md diff --git a/changelog.d/4851-vault-preflight-refusal-gaps.security.md b/changelog.d/4851-vault-preflight-refusal-gaps.security.md new file mode 100644 index 0000000000..c932d3ffc0 --- /dev/null +++ b/changelog.d/4851-vault-preflight-refusal-gaps.security.md @@ -0,0 +1 @@ +- The Vault token preflight now also refuses an enforcing start on a token that can turn off an audit device, seal Vault, read or write its storage raw, start a root-token generation or a rekey, create, rewrite or delete a Transit key the engine uses, or trim, import over, restore or export one version of it; and on a connector-secret token that can export or control the store key. The probes run side by side, each cut off after 75 seconds as a timeout, which only warns. A token whose lookup-self is denied says its own policies went unasked. `GET /security/posture` reports what the preflight read of each token, under `vault_privilege`. (BACKLOG #4851) diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index 87d39d70f4..3a92348bbb 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -2292,9 +2292,10 @@ count is above `0` (vault BACKLOG #2613). > **A switch.** `[security].allow_over_granted_vault_token`, default `false`. > [ADR 0216](../docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md), ASVS 13.2.2. - **What you lose:** the refusal under `enforce` that a Vault token the engine uses earns when the - startup probe finds it holding the root policy, any grant on an administrative path (a policy - write, including one of its own policies, an identity group, a mount, an auth method or - `auth/token/create`), or a Transit key's `config`, `rotate`, `export` or `backup`. Any grant there + startup probe finds it holding a grant in the refusing class, which + [SECURITY.md](SECURITY.md#each-backend-hops-least-privilege-the-engine-probes-the-store-vault-and-ldap) lists: at least the root policy, any + grant on an administrative path, a Transit key's control, export, backup or restore path, or a + grant that creates, rewrites or deletes a Transit key. Any grant on such a path but `deny` counts, a read included. A write there lets the token widen its own reach, or take the store key out of Vault, and any code path that reaches the token inherits that. - **When acceptable:** on a lab box run with a Vault dev-server root token. Not as a steady state. diff --git a/docs/SECURITY.md b/docs/SECURITY.md index d04af36033..3657e7f3bb 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1176,8 +1176,15 @@ The administrative paths it is asked about are at least these: itself; - two identity-group paths that can attach a policy, `identity/group` and `identity/group/name/`; - a secrets mount (`sys/mounts/`), an auth method (`sys/auth/`) and `auth/token/create`; +- an audit device (`sys/audit/`), `sys/seal`, raw storage (`sys/raw/`), a root-token generation + (`sys/generate-root/attempt`) and a rekey (`sys/rekey/init`); - for each Transit key the engine uses, its `config` (which can make the key exportable), `rotate`, - `export` and `backup` paths. + `trim`, `import`, `import_version`, `export` (the latest and one version), `backup` and `restore` + paths. Every token is asked about these, the connector-secret token included, so a token that + never calls the store key still reads over-granted when it can export it. + +On a Transit key's own path, where the engine needs only `read`, a `create`, `update`, `patch`, +`delete`, `sudo` or `root` grant creates, rewrites or deletes the key. Grants on other paths the engine does not call are not read, so a clean token still needs its policy read by hand. @@ -1253,9 +1260,10 @@ uses with the probe `check-privileges` runs. It builds its client with the provi constructor and reads the token from the same variable or secrets-directory file the provider reads, at that moment. The over-grants above fall in two classes: -- **The refusing class:** the `root` policy, and any grant on an administrative path the probe asks - about, which includes a write of the token's own policies and a Transit key's `config`, `rotate`, - `export` and `backup`. Under the shipped `enforcement = enforce` such a token **refuses to start**. +- **The refusing class:** the `root` policy, any grant on an administrative path the probe asks + about (the list above, which includes a write of the token's own policies and each Transit key's + control, export, backup and restore paths), and a grant that creates, rewrites or deletes a + Transit key. Under the shipped `enforcement = enforce` such a token **refuses to start**. The audited opt-out is `[security].allow_over_granted_vault_token = true`: it logs an `AUDIT:` line, marks the `vault_privilege_preflight` audit row `over_grant_accepted`, and is named on `GET /security/posture`. @@ -1271,6 +1279,11 @@ token variable, another Vault error status, and an answer that names no capabili Under `enforce` such a failure **refuses to start**, the audit row names it under `unexcused`, and the opt-out does not lift it. +The probes run side by side, and a probe still running after 75 seconds is cut off and reads as a +timeout, which only warns. A token whose `auth/token/lookup-self` is denied (a 403, so only a +warning) cannot name its own policies, so whether it can rewrite them is not asked; its hop says +so. What the preflight read of each token is on `GET /security/posture`, under `vault_privilege`. + Under `enforcement = warn` nothing refuses. The probe's limits stay: it asks about exact paths only, so a wildcard grant such as `secret/data/*` would read clean, and a token made with `-no-default-policy` reads as not observed at every start unless its policy grants the two paths the probe reads. Neither diff --git a/messagefoundry/privilege_check.py b/messagefoundry/privilege_check.py index f1f4e9dd8e..ed1a5084de 100644 --- a/messagefoundry/privilege_check.py +++ b/messagefoundry/privilege_check.py @@ -437,10 +437,10 @@ def vault_hop( the engine's own call would fail. Unobservable: any part of the reading could not be made, and no over-grant was seen. Over-grant wins, as it does in the exit code. - **Two classes (ADR 0216, owner ruling 2026-10-04).** The root policy and any grant on an - administrative path -- :data:`VAULT_ADMIN_PATHS`, a write of the token's own policies, and a - Transit key's ``config``, ``rotate``, ``export`` and ``backup`` -- are the REFUSING class, kept - in :attr:`HopPrivilege.refusing`. Everything else is the WARNING class, at least: a token shared + **Two classes (ADR 0216, owner ruling 2026-10-04).** :data:`VAULT_REFUSING_CLASS` is the + REFUSING class, kept in :attr:`HopPrivilege.refusing`: the paths :func:`vault_admin_paths` + names, and :data:`_TRANSIT_KEY_CONTROL_CAPS` on a Transit key's own path. Everything else is the + WARNING class, at least: a token shared by two hops, an extra capability on a path the engine calls, and a policy name the probe cannot tell from root by reading it, which means it cannot judge rather than that it saw root.""" grave: list[str] = [] diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index b1770e9444..9a009307de 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -7,13 +7,17 @@ preflight (:mod:`messagefoundry.store.privilege`, ADR 0199) and under the same teardown discipline. It probes each Vault consumer with the probe ``check-privileges`` runs (:func:`messagefoundry.privilege_probes.probe_vault`): a client built by the provider's own -constructor, with the token read again from the source the provider reads it from, so a token -replaced between the store open and this read is the one judged. It judges the readings with -:func:`messagefoundry.privilege_check.vault_hops`. +constructor, with the token read again from the source the provider reads it from, the process +environment. The store provider read the same variable when the store opened, and nothing in the +engine writes it in between, so the two read one token; a token replaced later is judged at the +next start. It judges the readings with :func:`messagefoundry.privilege_check.vault_hops`. The +probes run side by side, each bounded by :data:`VAULT_PROBE_TIMEOUT_S`, and the judged hops are +kept for ``GET /security/posture``. **What it refuses is** :func:`~messagefoundry.privilege_check.vault_preflight_outcome` **and nothing else**, which ADR 0216 and ``docs/SECURITY.md`` (*What serve does with a Vault finding*) describe: -under ``[security].enforcement = enforce``, a grant in the refusing class unless +under ``[security].enforcement = enforce``, a grant in the refusing class +(:data:`~messagefoundry.privilege_check.VAULT_REFUSING_CLASS`) unless ``[security].allow_over_granted_vault_token`` accepts it (audited), and a probe failure that is not a network failure, a timeout or a 403 (:func:`~messagefoundry.privilege_probes.excused_failure`), which the opt-out does not lift. Every other finding warns and writes an audit row. Under ``warn`` diff --git a/scripts/security/crypto_inventory_check.py b/scripts/security/crypto_inventory_check.py index 7f0cbbf5d6..0a554f8aa7 100644 --- a/scripts/security/crypto_inventory_check.py +++ b/scripts/security/crypto_inventory_check.py @@ -834,10 +834,11 @@ "messagefoundry.store.keyprovider", } ), - # BACKLOG #305 (ASVS 13.2.2): check-privileges reads each Vault token's own policies and - # capabilities through the providers' own client builders (store_vault_client, the Transit - # cipher's and the KEK's required-path helpers), so it carries their TLS narrowing, anchor and - # cleartext refusal and builds no client of its own. tls_policy and keyprovider are imported only + # BACKLOG #305 (ASVS 13.2.2): check-privileges, and serve's startup preflight (vault BACKLOG + # #2903), read each Vault token's own policies and capabilities through a client each builds + # with the providers' own constructors (store_vault_client, the Transit cipher's and the KEK's + # required-path helpers), so it carries their TLS narrowing, anchor and cleartext refusal; it is + # a second client, not the provider's. tls_policy and keyprovider are imported only # to recognise the engine's fixed-text refusals (InsecureHopRefused, KeyProviderError). hashlib: # a SHA-256 digest of each Vault token, held in memory only to tell whether two hops hold the # same token, and never printed. No encrypt, decrypt, MAC or key load. @@ -1750,7 +1751,8 @@ "hash:via messagefoundry.store.crypto", } ), - # BACKLOG #305: check-privileges digests each Vault token with SHA-256 to tell whether two hops + # BACKLOG #305: the privilege probe (check-privileges and serve's startup preflight) digests + # each Vault token with SHA-256 to tell whether two hops # hold the same token. An identity comparison held in memory, never printed or stored. "messagefoundry/privilege_probes.py": frozenset({"hash:hashlib.sha256"}), # BACKLOG #300: `_build_client` takes the Vault hop's narrowed context from From 3c8a128b576c7b334a0eaeda642b4d99ece9dd67 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:03:04 -0600 Subject: [PATCH 03/31] Vault token preflight: review round one repairs - The connector-secret token is asked about the store key's own path, where create, update, patch, delete, sudo or root refuses and any other grant warns; and only when both hops name the same Vault. - A failure to name the store's keys is a problem on that hop, so it never reads clean on a read that skipped them. - restore with no name and BYOK export are asked about. - Each probe runs on a daemon thread, so neither the loop's shutdown nor exit waits on a probe the bound gave up on. The bound is 150 seconds, above two requests at hvac's 30-second connect and read limits. - partial is in as_dict and the audit row, and "could not observe" comes before the warning-class text, so a length cap keeps it. - A channel-scoped posture reader sees each Vault hop's state and counts, not its text, which names KV paths. - The settings loosening text and the alert docstring name the class. - The preflight docstring says a re-read token is the one judged. - Seam re-derived; its history names the move. BACKLOG #4851 Verified-by: tests --- messagefoundry/api/_ui_seam.py | 6 +- messagefoundry/api/app.py | 8 +- messagefoundry/api/models.py | 6 +- messagefoundry/config/settings.py | 9 +- messagefoundry/pipeline/alerts.py | 2 +- messagefoundry/privilege_check.py | 48 ++++++-- messagefoundry/privilege_probes.py | 77 ++++++++----- messagefoundry/vault_preflight.py | 48 ++++++-- messagefoundry_webconsole/__init__.py | 2 +- tests/golden/webconsole_seam.snapshot | 6 +- tests/test_vault_privilege_preflight_4851.py | 112 +++++++++++++++++-- 11 files changed, 252 insertions(+), 72 deletions(-) diff --git a/messagefoundry/api/_ui_seam.py b/messagefoundry/api/_ui_seam.py index ab64d3f20a..789beafb02 100644 --- a/messagefoundry/api/_ui_seam.py +++ b/messagefoundry/api/_ui_seam.py @@ -1011,12 +1011,16 @@ #: failure is what refuses that pair. Re-derived with ``--write``, from ``605d329d7e840bb8`` to #: ``4033184244d47e90``. #: +#: Vault BACKLOG #4851: ``SecurityPosture`` gains ``vault_privilege``, each Vault token as the +#: startup preflight judged it, with its two new view models. Re-derived with ``--write``, from +#: ``4033184244d47e90`` to ``55c01eec8a5e8c61``. +#: #: The digest below covers the surface DISCOVERED from the console's own imports and uses, which is #: strictly larger than the five hand-maintained tuples it replaced -- those had drifted, and the #: proof is that commit 40a4d5d9 added a REQUIRED ``UploadedFileList.scope`` field the console renders #: unconditionally while touching no seam file at all. Regenerate with #: ``python scripts/webconsole_seam_snapshot.py --write``; never hand-edit it to silence a gate. -ENGINE_UI_SEAM: str = "c4b5ccf2426b91bb" +ENGINE_UI_SEAM: str = "55c01eec8a5e8c61" @dataclass(frozen=True, slots=True) diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 73f12a6f63..017752500e 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -6021,20 +6021,24 @@ async def security_posture( ) # Vault BACKLOG #4851: each Vault token as the startup preflight judged it; None means no # preflight ran in this process, which reads as not_probed, never as clean. + # A hop's detail and reasons name KV paths, which can name a connection, so a channel-scoped + # reader (BACKLOG #3189) is shown each hop's state and counts, never its text. vault_privilege = getattr(request.app.state, "vault_privilege", None) vault_privilege_view = ( VaultPrivilegeView(status=STORE_PRIVILEGE_NOT_PROBED) if vault_privilege is None else VaultPrivilegeView( status="probed", + scope=None if visible is None else POSTURE_NARROWED_TO_SCOPE, hops=[ VaultPrivilegeHopView( hop=h.hop, state=h.state.value, - refusing=list(h.refusing), + refusing=list(h.refusing) if visible is None else [], + refusing_count=len(h.refusing), unexcused=list(h.unexcused), partial=h.partial, - detail=h.detail, + detail=h.detail if visible is None else "", ) for h in vault_privilege ], diff --git a/messagefoundry/api/models.py b/messagefoundry/api/models.py index 7f76048244..fad67ae944 100644 --- a/messagefoundry/api/models.py +++ b/messagefoundry/api/models.py @@ -1574,6 +1574,7 @@ class VaultPrivilegeHopView(BaseModel): hop: str state: str refusing: list[str] = Field(default_factory=list) + refusing_count: int = 0 unexcused: list[str] = Field(default_factory=list) partial: bool = False detail: str = "" @@ -1585,9 +1586,12 @@ class VaultPrivilegeView(BaseModel): ``status`` is ``probed`` (the preflight ran; ``hops`` holds one entry per token, and is empty when no Vault consumer is configured) or ``not_probed`` (no preflight ran in this process: an embedding, or an app built without the service settings that name the tokens). ``not_probed`` - is never a pass.""" + is never a pass. ``scope`` is ``None`` for a whole reading; for a channel-scoped reader + (BACKLOG #3189) it says the reading is narrowed, and each hop's ``detail`` and ``refusing`` are + withheld, since they name KV paths that can name a connection. ``refusing_count`` stays.""" status: str + scope: str | None = None hops: list[VaultPrivilegeHopView] = Field(default_factory=list) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 944b98e146..0e76e99e24 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -8266,8 +8266,8 @@ class SecuritySettings(_Section): # ── Vault token privileges (ASVS 13.2.2, ADR 0216) ─────────────── # The audited opt-out from the refusal the gravest Vault grants earn under enforcement = enforce: # the startup preflight (messagefoundry/vault_preflight.py) found a Vault token the engine uses - # holding the root policy, a grant on an administrative path, or a Transit key's config, rotate, - # export or backup, and the operator accepts that in writing. It lifts that one refusal and + # holding a grant in the refusing class (privilege_check.VAULT_REFUSING_CLASS), and the + # operator accepts that in writing. It lifts that one refusal and # nothing else: every other Vault over-grant only warns, and so does a probe stopped by a network # failure, a timeout or a 403; a probe that failed otherwise refuses under enforce whatever this # says (privilege_probes.excused_failure). Default FALSE. @@ -11929,8 +11929,9 @@ def security_loosenings( out.append( ( "allow_over_granted_vault_token", - "a Vault token holding the root policy or a grant on an administrative path is " - "permitted to start an enforcing instance (ADR 0216) — the refusal the startup " + "a Vault token holding a grant in the refusing class (the root policy, or a grant " + "on an administrative path or on a Transit key's control, export, backup or " + "restore) is permitted to start an enforcing instance (ADR 0216) — the refusal the startup " "Vault privilege preflight would otherwise raise is acknowledged away", ) ) diff --git a/messagefoundry/pipeline/alerts.py b/messagefoundry/pipeline/alerts.py index 284e525ddd..0b2465b9a0 100644 --- a/messagefoundry/pipeline/alerts.py +++ b/messagefoundry/pipeline/alerts.py @@ -992,7 +992,7 @@ def vault_privilege_warning( """The Vault privilege preflight found a Vault token over-granted, or could not read it, at start (BACKLOG #2903, ADR 0216). ``finding`` is ``"over_granted"`` or ``"unobservable"``. ``refusing_count`` is how many of the over-grants are in the class that refuses a start - under ``enforce`` (the root policy, a grant on an administrative path); it is 0 for a token + under ``enforce`` (``privilege_check.VAULT_REFUSING_CLASS``); it is 0 for a token whose over-grants are all in the warning class, and means nothing for ``"unobservable"``. ``name`` is the subject, ``vault:`` (``vault:store`` or ``vault:secrets``). ``detail`` is the hop's judgment with control characters escaped: policy names, paths and capabilities diff --git a/messagefoundry/privilege_check.py b/messagefoundry/privilege_check.py index ed1a5084de..c0ea7dcf65 100644 --- a/messagefoundry/privilege_check.py +++ b/messagefoundry/privilege_check.py @@ -142,7 +142,7 @@ class HopPrivilege: unexcused: tuple[str, ...] = () partial: bool = False - def as_dict(self) -> dict[str, str | list[str]]: + def as_dict(self) -> dict[str, str | bool | list[str]]: return { "hop": self.hop, "state": self.state.value, @@ -151,6 +151,7 @@ def as_dict(self) -> dict[str, str | list[str]]: "detail": self.detail, "refusing": list(self.refusing), "unexcused": list(self.unexcused), + "partial": self.partial, } @@ -218,9 +219,11 @@ def store_hop(report: StorePrivilegeReport, store: StoreSettings) -> HopPrivileg #: Any capability but ``deny`` on one means the token can widen its own reach or run Vault itself: #: write a policy (``sys/policies/acl/`` and the older ``sys/policy/``), attach a policy through an #: identity group, mount a secrets or auth engine, mint a token, turn an audit device off, seal -#: Vault, read or write its storage raw, or start a root-token generation or a rekey (vault BACKLOG -#: #4851). The names after the last slash are placeholders no deployment uses; Vault answers with -#: the policy that would apply to them. +#: Vault, read or write its storage raw, or reach the root-token generation and rekey endpoints +#: (vault BACKLOG #4851). Vault serves those two without a token unless +#: ``disable_unauthed_rekey_endpoints`` is set, so a token clean there does not mean nobody can +#: start one; a grant there is still a grant nobody needs. The names after the last slash are +#: placeholders no deployment uses; Vault answers with the policy that would apply to them. VAULT_ADMIN_PATHS: tuple[str, ...] = ( "sys/policies/acl/messagefoundry-check-privileges", "sys/policy/messagefoundry-check-privileges", @@ -238,8 +241,9 @@ def store_hop(report: StorePrivilegeReport, store: StoreSettings) -> HopPrivileg #: The Transit operations on a key the engine uses that would let a token change the key, replace #: it or take it out of Vault: its config (which can set ``exportable``), a rotation, a trim of its -#: old versions, an import over it, an export of the latest or of one version (``latest`` stands -#: for any version a ``*`` or ``+`` grant would match), a backup and a restore (vault BACKLOG #4851). +#: old versions, an import over it, an export of every version or of one (``latest`` stands for any +#: version a ``*`` or ``+`` grant would match), a BYOK export (the destination name is a +#: placeholder), a backup and a restore (vault BACKLOG #4851). _TRANSIT_KEY_ADMIN = ( "{mount}/keys/{key}/config", "{mount}/keys/{key}/rotate", @@ -250,8 +254,11 @@ def store_hop(report: StorePrivilegeReport, store: StoreSettings) -> HopPrivileg "{mount}/export/encryption-key/{key}/latest", "{mount}/export/hmac-key/{key}", "{mount}/export/hmac-key/{key}/latest", + "{mount}/byok-export/messagefoundry-check-privileges/{key}", "{mount}/backup/{key}", "{mount}/restore/{key}", + # A restore with no name takes the name in the backup, so it can overwrite this key too. + "{mount}/restore", ) #: The capabilities on a Transit key's own path (``/keys/``) that create, rewrite or @@ -281,8 +288,9 @@ def vault_admin_paths( (:data:`_TRANSIT_KEY_ADMIN`), which would let the token make the store key exportable and read it out. The keys are the ones ``required`` names, and the ones ``other_keys`` names: the Transit key paths ANOTHER hop requires, so a token that never calls the store key is still asked - whether it can export it (vault BACKLOG #4851). At least these: grants on other paths are not - read.""" + whether it can export it (vault BACKLOG #4851). Such a key's own path is asked about too, so a + grant that deletes or rewrites it is seen; :func:`vault_hop` judges that path by + :data:`_TRANSIT_KEY_CONTROL_CAPS` alone. At least these: grants on other paths are not read.""" out = list(VAULT_ADMIN_PATHS) for policy in policies: if policy != "root": # root is judged on its own, and has no path to write @@ -290,11 +298,13 @@ def vault_admin_paths( # ``transit_mount`` is the caller's: the Transit mount the providers call, so this module stays # free of the Vault provider imports. prefix = f"{transit_mount}/keys/" - for path in [*required, *other_keys]: + for path, foreign in [*((p, False) for p in required), *((p, True) for p in other_keys)]: # Only the Transit mount's key metadata path, /keys/ with no further segment: # a KV path whose mount happens to contain "keys" is not a Transit key. key = path.removeprefix(prefix) if path.startswith(prefix) and key and "/" not in key: + if foreign and path not in required: + out.append(path) out += [ template.format(mount=transit_mount, key=key) for template in _TRANSIT_KEY_ADMIN ] @@ -487,7 +497,21 @@ def vault_hop( notes.append(f"{path} lacks {_caps(missing)}, so the engine's own call would fail") for path in reading.admin_paths: extra = set(reading.capabilities.get(path, ())) - {"deny"} - if extra: + if f"{path}/config" in reading.admin_paths: + # Another hop's Transit key: only a grant that creates, rewrites or deletes it is in + # the refusing class, as on the hop's own key path above; any other grant warns. + control = extra & _TRANSIT_KEY_CONTROL_CAPS + if control: + grave.append( + f"{path} grants {_caps(control)}, which creates, rewrites or deletes the key; " + "the engine never calls it with this token" + ) + if extra - control: + over.append( + f"{path} grants {_caps(extra - control)}; the engine never calls it with this " + "token" + ) + elif extra: grave.append(f"{path} grants {_caps(extra)}; the engine never calls it") for other_hop, other in (shared or {}).items(): for path in other.required: @@ -527,13 +551,15 @@ def vault_hop( state = HopState.UNOBSERVABLE else: state = HopState.CLEAN + # What could not be read comes right after the refusing reasons, so a detail cut to a length + # cap (the log line, the audit row) still says the token was read only in part. parts = [ *(f"over-granted, refusing class: {g}" for g in grave), + *(f"could not observe: {p}" for p in unread), *(f"over-granted: {o}" for o in over), *seen, *notes, ] - parts += [f"could not observe: {p}" for p in unread] if state is HopState.CLEAN: parts.append( "paths the engine does not call were read only for the administrative ones; " diff --git a/messagefoundry/privilege_probes.py b/messagefoundry/privilege_probes.py index 3105d70ce1..c71859b028 100644 --- a/messagefoundry/privilege_probes.py +++ b/messagefoundry/privilege_probes.py @@ -298,9 +298,9 @@ def read_vault_token( is returned, so one run names every one that is missing. ``other_keys`` returns the Transit key paths another hop requires, so this token is asked - about their control and export paths too (vault BACKLOG #4851). A failure to name them is a - problem of that other hop, which reports it on its own reading; here it is logged and the - token is asked about its own keys alone. + about their own, control and export paths too (vault BACKLOG #4851). A failure to name them is + recorded as a problem, not as unexcused, since the other hop's own reading names the cause; the + token is then asked about its own keys alone. Every failure is recorded as a problem. One that :func:`excused_failure` does not excuse is also named in ``unexcused``, so a code defect swallowed here still refuses an enforcing start.""" @@ -384,8 +384,16 @@ def why(exc: BaseException) -> str: if other_keys is not None: try: foreign = tuple(other_keys()) - except Exception as exc: # noqa: BLE001 - the other hop's own reading reports it - logger.info("privilege probe: another hop's Transit keys not named: %s", _why(exc)) + except Exception as exc: # recorded: this token was then not asked about those keys + # Not in ``unexcused``: the cause is the other hop's (an unset key name or address), + # and that hop's own reading names it. It is a problem here, so this hop never reads + # clean, nor resolves an open warning, on a read that skipped the store keys. + problems.append( + _problem( + "the store hop's Transit keys could not be named, so this token was not asked " + f"whether it can export or delete them: {_why(exc)}" + ) + ) admin = vault_admin_paths(needed, policies, transit_mount=TRANSIT_MOUNT, other_keys=foreign) capabilities: dict[str, tuple[str, ...]] = {} paths = [*needed, *admin] @@ -457,7 +465,6 @@ def probe_vault( other_keys=functools.partial(_store_transit_keys, settings), ) from messagefoundry.store.keyprovider_vault import ( - kek_required_capabilities, store_vault_address, store_vault_client, store_vault_token, @@ -469,38 +476,56 @@ def probe_vault( revocation_reason=settings.store.vault_revocation_attested_reason, posture=posture, ) - if kind == "transit": - from messagefoundry.store.crypto_transit import transit_cipher_required_capabilities - + if kind in ("transit", "kek"): return read_vault_token( store_vault_token, store_vault_address, store_client, - transit_cipher_required_capabilities, - ) - if kind == "kek": - return read_vault_token( - store_vault_token, store_vault_address, store_client, kek_required_capabilities + functools.partial(_store_required, kind), ) # Unreachable while VaultKind has three members; a fourth must be routed here, not defaulted. raise ValueError(f"no Vault probe for consumer kind {kind!r}") -def _store_transit_keys(settings: ServiceSettings) -> tuple[str, ...]: - """The Transit key paths the store hop requires, or none when the store uses no Vault key. - The connector-secret token is asked about these keys' control and export paths too, so a token - that never calls the store key still reads over-granted when it can export it (vault BACKLOG - #4851). Raises as the store's own required-path helper does, for an unset key name.""" - store = settings.store - if store.cipher_provider == "vault_transit": +def _store_required(kind: str) -> Mapping[str, frozenset[str]]: + """The paths the store consumer of ``kind`` calls, from the provider's own helper. One map for + :func:`probe_vault` and :func:`_store_transit_keys`, so the two cannot disagree.""" + if kind == "transit": from messagefoundry.store.crypto_transit import transit_cipher_required_capabilities - return tuple(transit_cipher_required_capabilities()) - if store.key_provider == "vault": - from messagefoundry.store.keyprovider_vault import kek_required_capabilities + return transit_cipher_required_capabilities() + from messagefoundry.store.keyprovider_vault import kek_required_capabilities - return tuple(kek_required_capabilities()) - return () + return kek_required_capabilities() + + +def _same_vault(a: str, b: str) -> bool: + """Whether two configured Vault addresses name one server, read as written: the case and a + trailing slash are ignored, and nothing is resolved. Two spellings of one server read as two, + and the cost is that the store keys go unasked of the other token, never a false refusal.""" + return a.rstrip("/").casefold() == b.rstrip("/").casefold() + + +def _store_transit_keys(settings: ServiceSettings) -> tuple[str, ...]: + """The Transit key paths the store hop requires, when the connector-secret token talks to the + same Vault; otherwise none. The connector-secret token is asked about these keys' own, control + and export paths too, so a token that never calls the store key still reads over-granted when + it can export or delete it (vault BACKLOG #4851). The store consumer is the one + :func:`~messagefoundry.privilege_check.vault_consumers` names, so the dispatch is that + function's. Raises as the store's helpers do, for an unset address or key name.""" + from messagefoundry.privilege_check import vault_consumers + + store = next((c for c in vault_consumers(settings) if c.kind in ("kek", "transit")), None) + if store is None: + return () + from messagefoundry.config.secretprovider_vault import secrets_vault_address + from messagefoundry.store.keyprovider_vault import store_vault_address + + # A key of the same name on another Vault is another key: asking this token about it would + # refuse a start for a grant that reaches nothing of the store's. + if not _same_vault(store_vault_address(), secrets_vault_address()): + return () + return tuple(_store_required(store.kind)) def read_ldap_bind(settings: ServiceSettings, posture: HopPosture | None) -> BindAccountReading: diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index 9a009307de..e62067b907 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -7,10 +7,12 @@ preflight (:mod:`messagefoundry.store.privilege`, ADR 0199) and under the same teardown discipline. It probes each Vault consumer with the probe ``check-privileges`` runs (:func:`messagefoundry.privilege_probes.probe_vault`): a client built by the provider's own -constructor, with the token read again from the source the provider reads it from, the process -environment. The store provider read the same variable when the store opened, and nothing in the -engine writes it in between, so the two read one token; a token replaced later is judged at the -next start. It judges the readings with :func:`messagefoundry.privilege_check.vault_hops`. The +constructor, with the token read again from the source the provider reads it from (the variable, +or the secrets-directory file, which is read afresh on every call). So a token replaced between +the store open and this read is the one judged, while a provider that keeps the client it built, +such as the Transit cipher, goes on using the token it read; a token replaced after this read is +judged only at the next start. It judges the readings with +:func:`messagefoundry.privilege_check.vault_hops`. The probes run side by side, each bounded by :data:`VAULT_PROBE_TIMEOUT_S`, and the judged hops are kept for ``GET /security/posture``. @@ -44,6 +46,7 @@ import asyncio import json import logging +import threading from collections.abc import Callable from functools import partial from typing import TYPE_CHECKING, Protocol @@ -94,9 +97,11 @@ #: How long, in seconds, the preflight waits for each Vault probe (vault BACKLOG #4851). The probes #: run side by side, so this is about the longest a start waits on them all. Each probe sends two -#: requests on a client with hvac's 30-second default; this bounds the rest too, such as a name -#: that does not resolve. -VAULT_PROBE_TIMEOUT_S = 75.0 +#: requests on a client with hvac's 30-second default, which requests applies to the connect and +#: to each read apart, so a Vault that answers within those limits finishes inside 2 x (30 + 30) +#: seconds; the rest is margin. The bound ends what those limits do not, at least a name that does +#: not resolve and a reply that trickles in. A probe it ends reads as a timeout, which only warns. +VAULT_PROBE_TIMEOUT_S = 150.0 class VaultPrivilegeError(RuntimeError): @@ -186,14 +191,32 @@ async def _probe_all( """Every consumer's reading, the probes run side by side, each off the event loop and each bounded by ``timeout`` seconds (vault BACKLOG #4851). A probe still running at the bound reads as a timeout, which the owner ruling of 2026-10-04 lets only warn. Its thread cannot be - stopped and runs on until the client's own request timeouts end it; nothing waits on it, and - its reading is dropped.""" + stopped and runs on until the client's own request timeouts end it, and its reading is + dropped. It is a daemon thread of its own, not the loop's default executor, so neither the + loop's shutdown nor the interpreter's exit waits on it.""" + loop = asyncio.get_running_loop() async def bounded(consumer: VaultConsumer) -> VaultTokenReading: + done: asyncio.Future[VaultTokenReading] = loop.create_future() + + def deliver(reading: VaultTokenReading) -> None: + if not done.done(): # cancelled by the bound, so nobody reads it + done.set_result(reading) + + def run() -> None: + reading = _probe_one(consumer, probe) + try: + loop.call_soon_threadsafe(deliver, reading) + except RuntimeError: # the loop closed after the bound gave up on this probe + log.debug( + "vault privilege preflight: %s finished after its loop closed", consumer.hop + ) + + threading.Thread( + target=run, name=f"vault-privilege-probe-{consumer.hop}", daemon=True + ).start() try: - return await asyncio.wait_for( - asyncio.to_thread(_probe_one, consumer, probe), timeout=timeout - ) + return await asyncio.wait_for(done, timeout=timeout) except TimeoutError: problem = f"the probe did not finish within {timeout:g}s (a timeout)" log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) @@ -267,6 +290,7 @@ async def run_vault_privilege_preflight( "state": hop.state.value, "refusing": [r[:_AUDIT_REASON_LIMIT] for r in hop.refusing[:_AUDIT_REFUSING_LIMIT]], "refusing_count": len(hop.refusing), + "partial": hop.partial, "unexcused": list(hop.unexcused), "detail": hop.detail[:_AUDIT_DETAIL_LIMIT], "enforcing": enforcing, diff --git a/messagefoundry_webconsole/__init__.py b/messagefoundry_webconsole/__init__.py index f45db2dedf..7abfee548d 100644 --- a/messagefoundry_webconsole/__init__.py +++ b/messagefoundry_webconsole/__init__.py @@ -45,7 +45,7 @@ # If cross-seam support is ever genuinely wanted, re-widen this set AND add the CI matrix that # installs the MIN and MAX supported engine builds — the claim and its test land together, or not # at all. -SUPPORTED_ENGINE_SEAMS: frozenset[str] = frozenset({"c4b5ccf2426b91bb"}) +SUPPORTED_ENGINE_SEAMS: frozenset[str] = frozenset({"55c01eec8a5e8c61"}) #: The vendored static assets shipped in THIS wheel (mounted at /ui/static by :func:`mount_ui`). STATIC_DIR = Path(__file__).parent / "static" diff --git a/tests/golden/webconsole_seam.snapshot b/tests/golden/webconsole_seam.snapshot index 3e0d631bfe..351a73c631 100644 --- a/tests/golden/webconsole_seam.snapshot +++ b/tests/golden/webconsole_seam.snapshot @@ -7,7 +7,7 @@ # by hand (BACKLOG #1220) - so a newly rendered DTO is covered with nobody editing a list. ## ENGINE_UI_SEAM -c4b5ccf2426b91bb +55c01eec8a5e8c61 ## dataclass messagefoundry.api._ui_seam.UiDeps engine_seam @@ -347,8 +347,8 @@ messagefoundry.api.models.UploadedFileList: files, limit, offset, scope, total messagefoundry.api.models.UploadedMessageSearchRequest: content, control_id, field_path, field_value, limit, message_type, offset, target messagefoundry.api.models.UploadedMessageSummary: control_id, index, message_type, size messagefoundry.api.models.UploadedMessagesResult: file_id, filename, matched, messages, scanned, total_messages, truncated -messagefoundry.api.models.VaultPrivilegeHopView: detail, hop, partial, refusing, state, unexcused -messagefoundry.api.models.VaultPrivilegeView: hops, status +messagefoundry.api.models.VaultPrivilegeHopView: detail, hop, partial, refusing, refusing_count, state, unexcused +messagefoundry.api.models.VaultPrivilegeView: hops, scope, status ## enum members reachable from those DTOs messagefoundry.config.ai_policy.SecurityEnforcement: ENFORCE, WARN diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index 3ea186efa0..70759a2303 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -15,6 +15,7 @@ from __future__ import annotations +import json import threading import time from pathlib import Path @@ -74,7 +75,9 @@ f"transit/keys/{_KEK}/import_version", f"transit/export/encryption-key/{_KEK}/latest", f"transit/export/hmac-key/{_KEK}/latest", + f"transit/byok-export/messagefoundry-check-privileges/{_KEK}", f"transit/restore/{_KEK}", + "transit/restore", ], ) def test_each_newly_asked_path_is_in_the_refusing_class(path: str) -> None: @@ -139,18 +142,35 @@ def test_a_secrets_token_that_can_export_the_store_key_refuses() -> None: assert alone.refusing == () -def test_a_failure_naming_the_other_hops_keys_still_reads_the_token() -> None: +@pytest.mark.parametrize("cap", ["delete", "update"]) +def test_a_secrets_token_that_can_delete_or_rewrite_the_store_key_refuses(cap: str) -> None: + key = f"transit/keys/{_KEK}" + vault = _FakeVault(caps={_KV_PATH: ["read"], key: [cap]}) + hop = vault_hop(_KV, _kv_reading(vault, other_keys=lambda: [key])) + assert any(r.startswith(f"{key} grants {cap}, which creates") for r in hop.refusing) + + +def test_a_secrets_token_reading_the_store_key_only_warns() -> None: + key = f"transit/keys/{_KEK}" + vault = _FakeVault(caps={_KV_PATH: ["read"], key: ["read"]}) + hop = vault_hop(_KV, _kv_reading(vault, other_keys=lambda: [key])) + assert hop.state is HopState.OVER_GRANTED and hop.refusing == () + assert f"{key} grants read; the engine never calls it with this token" in hop.detail + + +def test_a_failure_naming_the_other_hops_keys_is_a_problem_not_a_clean_read() -> None: def unset() -> list[str]: raise ValueError("no key name") reading = _kv_reading(_FakeVault(caps={_KV_PATH: ["read"]}), other_keys=unset) - assert reading.capabilities and reading.problems == () + assert reading.capabilities + assert any("store hop's Transit keys could not be named" in p for p in reading.problems) + assert reading.unexcused == () + hop = vault_hop(_KV, reading) + assert hop.state is HopState.UNOBSERVABLE and hop.partial -def test_probe_vault_hands_the_store_keys_to_the_secrets_probe( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setenv("MEFOR_STORE_VAULT_TRANSIT_KEY", _KEK) +def _probe_kv_keys(monkeypatch: pytest.MonkeyPatch) -> Any: seen: dict[str, Any] = {} def fake(*args: Any, other_keys: Any = None) -> VaultTokenReading: @@ -159,12 +179,32 @@ def fake(*args: Any, other_keys: Any = None) -> VaultTokenReading: monkeypatch.setattr("messagefoundry.privilege_probes.read_vault_token", fake) probe_vault(_KV, _VAULT_SETTINGS) - assert f"transit/keys/{_KEK}" in seen["keys"] - assert set(vault_admin_paths({}, (), transit_mount="transit", other_keys=seen["keys"])) >= { - f"transit/export/encryption-key/{_KEK}" + return seen["keys"] + + +def test_probe_vault_hands_the_store_keys_to_the_secrets_probe( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("MEFOR_STORE_VAULT_TRANSIT_KEY", _KEK) + monkeypatch.setenv("MEFOR_STORE_VAULT_ADDR", _VAULT_ADDR) + monkeypatch.setenv("MEFOR_SECRETS_VAULT_ADDR", _VAULT_ADDR + "/") + keys = _probe_kv_keys(monkeypatch) + assert f"transit/keys/{_KEK}" in keys + assert set(vault_admin_paths({}, (), transit_mount="transit", other_keys=keys)) >= { + f"transit/keys/{_KEK}", + f"transit/export/encryption-key/{_KEK}", } +def test_the_store_keys_are_not_asked_of_a_token_on_another_vault( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("MEFOR_STORE_VAULT_TRANSIT_KEY", _KEK) + monkeypatch.setenv("MEFOR_STORE_VAULT_ADDR", _VAULT_ADDR) + monkeypatch.setenv("MEFOR_SECRETS_VAULT_ADDR", "https://other-vault.mefor.invalid:8200") + assert _probe_kv_keys(monkeypatch) == () + + # --- a denied lookup-self ---------------------------------------------------------------------- @@ -173,6 +213,9 @@ def test_a_denied_lookup_self_says_the_policy_write_check_did_not_run() -> None: hop = _hop(caps=caps, lookup_error=Forbidden("denied")) assert hop.partial assert "whether it can rewrite them was not asked" in hop.detail + assert hop.as_dict()["partial"] is True + # What was not read comes before the warning-class text, so a length cap keeps it. + assert hop.detail.index("could not observe") < hop.detail.index("over-granted:") verdict = serve_verdict(_sqlite_report(), _VAULT_SETTINGS, [hop]) assert "part of the token on vault.store could not be read here" in verdict # The control: the same grant read whole says nothing of the kind. @@ -215,6 +258,7 @@ async def test_the_audit_row_caps_the_refusing_reasons() -> None: probe=_probe(_FakeVault(caps=caps, policies=("default", "x" * 500))), ) [(_, detail)] = store.audits + assert detail["partial"] is False assert detail["refusing_count"] > 20 assert len(detail["refusing"]) == 20 assert all(len(r) <= 300 for r in detail["refusing"]) @@ -267,7 +311,8 @@ def meet(consumer: VaultConsumer) -> VaultTokenReading: probe=meet, ) assert [h.hop for h in hops] == ["vault.store", "vault.secrets"] - assert all("did not finish" not in h.detail for h in hops) + # Run one after the other, the first would break the barrier and read as a probe that raised. + assert [h.state for h in hops] == [HopState.CLEAN, HopState.CLEAN] def test_the_default_bound_is_finite() -> None: @@ -301,3 +346,50 @@ async def test_posture_without_a_preflight_says_not_probed() -> None: fields = SecurityPosture.model_fields default = fields["vault_privilege"].get_default(call_default_factory=True) assert default.status == "not_probed" and default.hops == [] + + +async def test_a_channel_scoped_reader_sees_no_vault_hop_text(tmp_path: Path) -> None: + """The secrets hop's detail names KV paths, which can name another channel's connection.""" + import httpx + + from messagefoundry.api import create_app + from messagefoundry.api.models import POSTURE_NARROWED_TO_SCOPE + from messagefoundry.auth import Role + from messagefoundry.auth.identity import ALL_CHANNELS + from messagefoundry.config.settings import EgressSettings + from messagefoundry.pipeline import Engine + from tests._bound_proof import reproving_transport + from tests.test_channel_scope_posture_users_reload import MINE, PW, _login, _service, _user + + engine = await Engine.create( + tmp_path / "scope4851.db", + poll_interval=0.02, + egress_settings=EgressSettings(deny_by_default=False), + ) + try: + service = await _service(engine) + await _user(service, "scoped", [Role.VIEWER.value], [MINE]) + await _user(service, "wide", [Role.VIEWER.value], [ALL_CHANNELS]) + app = create_app(engine, auth=service) + caps = {_KV_PATH: ["list", "read"], "auth/token/create": ["update"]} + reading = read_vault_token( + lambda: _TOKEN, + lambda: _VAULT_ADDR, + lambda a, t: _FakeVault(caps=caps), + lambda: {_KV_PATH: frozenset({"read"})}, + ) + app.state.vault_privilege = [vault_hop(_KV, reading)] + transport = reproving_transport(PW, app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://t") as c: + scoped = (await c.get("/security/posture", headers=await _login(c, "scoped"))).json() + wide = (await c.get("/security/posture", headers=await _login(c, "wide"))).json() + finally: + await engine.stop() + assert _KV_PATH in json.dumps(wide["vault_privilege"]) + assert wide["vault_privilege"]["scope"] is None + view = scoped["vault_privilege"] + assert _KV_PATH not in json.dumps(view) + assert view["scope"] == POSTURE_NARROWED_TO_SCOPE + [hop] = view["hops"] + assert hop["state"] == "over_granted" + assert hop["refusing_count"] == 1 and hop["refusing"] == [] From 8b22a4d2d2b11e2635286e798f9daeadb1f2ae59 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:03:40 -0600 Subject: [PATCH 04/31] Vault token preflight docs: review round one repairs SECURITY.md says export covers every version and one version, adds BYOK export and an unnamed restore, says the connector-secret token is asked about the store's keys only on the same Vault address, says the root-generation and rekey endpoints are served without a token unless disable_unauthed_rekey_endpoints is set, gives the 150-second bound and the scoped posture reader. SECURITY-LOOSENING.md and DEPLOY-SERVER-DB.md name the class rather than root and administrative paths alone. The changelog fragment follows. BACKLOG #4851 Verified-by: tests --- ...1-vault-preflight-refusal-gaps.security.md | 2 +- docs/DEPLOY-SERVER-DB.md | 6 +++-- docs/SECURITY-LOOSENING.md | 6 ++--- docs/SECURITY.md | 24 ++++++++++++------- 4 files changed, 23 insertions(+), 15 deletions(-) diff --git a/changelog.d/4851-vault-preflight-refusal-gaps.security.md b/changelog.d/4851-vault-preflight-refusal-gaps.security.md index c932d3ffc0..6a1f75db4a 100644 --- a/changelog.d/4851-vault-preflight-refusal-gaps.security.md +++ b/changelog.d/4851-vault-preflight-refusal-gaps.security.md @@ -1 +1 @@ -- The Vault token preflight now also refuses an enforcing start on a token that can turn off an audit device, seal Vault, read or write its storage raw, start a root-token generation or a rekey, create, rewrite or delete a Transit key the engine uses, or trim, import over, restore or export one version of it; and on a connector-secret token that can export or control the store key. The probes run side by side, each cut off after 75 seconds as a timeout, which only warns. A token whose lookup-self is denied says its own policies went unasked. `GET /security/posture` reports what the preflight read of each token, under `vault_privilege`. (BACKLOG #4851) +- The Vault token preflight now also refuses an enforcing start on a token holding a grant on an audit device, `sys/seal`, raw storage, or the root-token generation or rekey endpoints, or one that can create, rewrite or delete a Transit key the engine uses, or trim, import over, BYOK-export, restore or export one version of it; and on a connector-secret token, on the same Vault address as the store, that can do so to the store key. The probes run side by side, each cut off after 150 seconds as a timeout, which only warns. A token whose lookup-self is denied says its own policies went unasked. `GET /security/posture` reports what the preflight read of each token, under `vault_privilege`. (BACKLOG #4851) diff --git a/docs/DEPLOY-SERVER-DB.md b/docs/DEPLOY-SERVER-DB.md index 5696601efa..23aac7d92c 100644 --- a/docs/DEPLOY-SERVER-DB.md +++ b/docs/DEPLOY-SERVER-DB.md @@ -194,8 +194,10 @@ It also probes each Vault token the engine uses and the AD bind account, when th configured. A Vault token that holds more than the engine needs, or an AD bind account in an administrative group, makes it exit 3. A Vault or AD probe that cannot run makes it exit 4. An AD finding is reported only and never stops a start. `serve` probes each Vault token too, at every -start: under `enforcement = enforce` a token holding the root policy or a grant on an administrative -path refuses the start, and every other Vault finding only warns +start: under `enforcement = enforce` a token holding a grant in the refusing class +([SECURITY.md](SECURITY.md#each-backend-hops-least-privilege-the-engine-probes-the-store-vault-and-ldap) +lists it) refuses the start, and at least the warning-class grants and a probe stopped by a network +failure, a timeout or a 403 only warn ([ADR 0216](adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md)). The `serve:` line says which applies. diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index 3a92348bbb..0b8c2d524f 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -201,7 +201,7 @@ Earlier versions of this guide called this an open owner question. The 2026-10-2 | | `max_session_hours` | `12` (a value above `12` is named. A value below `1` or above `8760` hours is refused at load) | | Alert transport | `allow_unverified_alert_smtp_tls` | `false` | | Store principal | `allow_over_granted_store_principal` | `false` (ADR 0199: accept an over-granted store login under `enforce`, audited) | -| Vault token | `allow_over_granted_vault_token` | `false` (ADR 0216: accept a Vault token holding the root policy or an administrative grant under `enforce`, audited) | +| Vault token | `allow_over_granted_vault_token` | `false` (ADR 0216: accept a Vault token holding a refusing-class grant under `enforce`, audited) | | Interpreter | `allow_remote_debugging` | `false` (vault BACKLOG #2700: lifts the start refusal under `enforce` while the interpreter's remote debugging is on; reported) | | Backend credentials | `require_nonstatic_credentials` | `false` (*not* a loosening — it TIGHTENS, refusing backend hops on a static credential or none. Opt-in by owner decision, because several hops have no compliant kind in the product) | | | `static_credential_accepted` | `{}` (each opt-out is a loosening while `require_nonstatic_credentials` is on, and is reported as `static_credential_accepted`; with the refusal off an opt-out does nothing and is not reported) | @@ -2295,8 +2295,8 @@ count is above `0` (vault BACKLOG #2613). startup probe finds it holding a grant in the refusing class, which [SECURITY.md](SECURITY.md#each-backend-hops-least-privilege-the-engine-probes-the-store-vault-and-ldap) lists: at least the root policy, any grant on an administrative path, a Transit key's control, export, backup or restore path, or a - grant that creates, rewrites or deletes a Transit key. Any grant on such a path - but `deny` counts, a read included. A write there lets the token widen its own reach, or take the + grant that creates, rewrites or deletes a Transit key. On an administrative, control, export, + backup or restore path any grant but `deny` counts, a read included. A write there lets the token widen its own reach, or take the store key out of Vault, and any code path that reaches the token inherits that. - **When acceptable:** on a lab box run with a Vault dev-server root token. Not as a steady state. - **It is never silent:** a WARNING line starting `AUDIT:` at every start it lets through, diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 3657e7f3bb..c6bf15e058 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1176,15 +1176,20 @@ The administrative paths it is asked about are at least these: itself; - two identity-group paths that can attach a policy, `identity/group` and `identity/group/name/`; - a secrets mount (`sys/mounts/`), an auth method (`sys/auth/`) and `auth/token/create`; -- an audit device (`sys/audit/`), `sys/seal`, raw storage (`sys/raw/`), a root-token generation - (`sys/generate-root/attempt`) and a rekey (`sys/rekey/init`); +- an audit device (`sys/audit/`), `sys/seal`, raw storage (`sys/raw/`), and the root-token + generation and rekey endpoints (`sys/generate-root/attempt`, `sys/rekey/init`). Vault serves + those two without a token unless `disable_unauthed_rekey_endpoints` is set, so a token clean + there does not mean nobody can start one; - for each Transit key the engine uses, its `config` (which can make the key exportable), `rotate`, - `trim`, `import`, `import_version`, `export` (the latest and one version), `backup` and `restore` - paths. Every token is asked about these, the connector-secret token included, so a token that - never calls the store key still reads over-granted when it can export it. + `trim`, `import`, `import_version`, `export` (every version, and one version), BYOK export, + `backup`, and `restore` with and without the key's name. When the connector-secret token talks + to the same Vault address as the store, it is asked about the store's keys too, their own path + included, so a token that never calls the store key still reads over-granted when it can export + or delete it. -On a Transit key's own path, where the engine needs only `read`, a `create`, `update`, `patch`, -`delete`, `sudo` or `root` grant creates, rewrites or deletes the key. +On a Transit key's own path a `create`, `update`, `patch`, `delete`, `sudo` or `root` grant creates, +rewrites or deletes the key, and is in the refusing class. Any other grant there that the engine +does not need, such as `list`, only warns. Grants on other paths the engine does not call are not read, so a clean token still needs its policy read by hand. @@ -1279,10 +1284,11 @@ token variable, another Vault error status, and an answer that names no capabili Under `enforce` such a failure **refuses to start**, the audit row names it under `unexcused`, and the opt-out does not lift it. -The probes run side by side, and a probe still running after 75 seconds is cut off and reads as a +The probes run side by side, and a probe still running after 150 seconds is cut off and reads as a timeout, which only warns. A token whose `auth/token/lookup-self` is denied (a 403, so only a warning) cannot name its own policies, so whether it can rewrite them is not asked; its hop says -so. What the preflight read of each token is on `GET /security/posture`, under `vault_privilege`. +so. What the preflight read of each token is on `GET /security/posture`, under `vault_privilege`; +a channel-scoped reader is shown each hop's state and counts, not its text. Under `enforcement = warn` nothing refuses. The probe's limits stay: it asks about exact paths only, so a wildcard grant such as `secret/data/*` would read clean, and a token made with `-no-default-policy` reads From f326a775e6ecf35496e0b4567aca1c371c6ac91f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:23:23 -0600 Subject: [PATCH 05/31] Vault token preflight: review round two repairs - The connector-secret token is asked about every path the store hop calls, so a grant that decrypts with the store key refuses; a token shared by both hops still only warns, reported once. - The reading names its Transit key paths and the other hop's paths, rather than vault_hop guessing a key from a path's shape. - A code defect naming the store's paths is unexcused; only the engine's own unset-name refusal is a plain problem. - _same_vault compares scheme and host without case, path as written. _store_required refuses an unknown kind. - identity/entity, entity-alias, auth/token/roles and sys/plugins/catalog are asked about. - A BaseException in a probe is delivered and refuses under enforce, rather than reading as a timeout; the probe runs in a copy of the caller's context. - The log line carries partial. The settings loosening text and the lifespan comment name the whole class. BACKLOG #4851 Verified-by: tests --- messagefoundry/api/app.py | 4 +- messagefoundry/config/settings.py | 2 +- messagefoundry/privilege_check.py | 88 +++++++++++------- messagefoundry/privilege_probes.py | 80 +++++++++++------ messagefoundry/vault_preflight.py | 19 +++- tests/test_vault_privilege_preflight_4851.py | 94 +++++++++++++++++--- 6 files changed, 208 insertions(+), 79 deletions(-) diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 017752500e..d320521ddf 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -13939,8 +13939,8 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: # server principal), so the default single-node path is a log line and nothing else. # BACKLOG #2903 (ADR 0216, ASVS 13.2.2): then probe each Vault token the engine uses, with the # probe check-privileges runs and a client from the provider's own constructor, in the same - # try and so under the same teardown. Under [security].enforcement=enforce the root policy or any grant - # on an administrative path refuses unless [security].allow_over_granted_vault_token accepts + # try and so under the same teardown. Under [security].enforcement=enforce a grant in the refusing + # class (privilege_check.VAULT_REFUSING_CLASS) refuses unless [security].allow_over_granted_vault_token accepts # it (audited), and so does a probe failure that is not a network failure, a timeout or a # 403, which the opt-out does not lift; every other finding warns and audits # (vault_preflight_outcome). Every finding raises vault_privilege_warning, and a clean read diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 0e76e99e24..1426447a3a 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -11931,7 +11931,7 @@ def security_loosenings( "allow_over_granted_vault_token", "a Vault token holding a grant in the refusing class (the root policy, or a grant " "on an administrative path or on a Transit key's control, export, backup or " - "restore) is permitted to start an enforcing instance (ADR 0216) — the refusal the startup " + "restore path, or one that creates, rewrites or deletes a Transit key) is permitted to start an enforcing instance (ADR 0216) — the refusal the startup " "Vault privilege preflight would otherwise raise is acknowledged away", ) ) diff --git a/messagefoundry/privilege_check.py b/messagefoundry/privilege_check.py index c0ea7dcf65..e6737c7c1f 100644 --- a/messagefoundry/privilege_check.py +++ b/messagefoundry/privilege_check.py @@ -81,6 +81,7 @@ "serve_verdict", "settings_hops", "store_hop", + "transit_key_paths", "vault_consumers", "vault_admin_paths", "vault_hop", @@ -220,18 +221,25 @@ def store_hop(report: StorePrivilegeReport, store: StoreSettings) -> HopPrivileg #: write a policy (``sys/policies/acl/`` and the older ``sys/policy/``), attach a policy through an #: identity group, mount a secrets or auth engine, mint a token, turn an audit device off, seal #: Vault, read or write its storage raw, or reach the root-token generation and rekey endpoints -#: (vault BACKLOG #4851). Vault serves those two without a token unless -#: ``disable_unauthed_rekey_endpoints`` is set, so a token clean there does not mean nobody can -#: start one; a grant there is still a grant nobody needs. The names after the last slash are -#: placeholders no deployment uses; Vault answers with the policy that would apply to them. +#: (vault BACKLOG #4851); and attach a policy through an identity entity or alias, write a token +#: role, or register a plugin. Vault serves the root-generation and rekey endpoints without a +#: token (``disable_unauthed_rekey_endpoints`` closes only the rekey one to unauthenticated +#: callers), so a token clean there does not mean nobody can start one; a grant there is still a +#: grant nobody needs. The names after the last slash are placeholders no deployment uses; Vault +#: answers with the policy that would apply to them. VAULT_ADMIN_PATHS: tuple[str, ...] = ( "sys/policies/acl/messagefoundry-check-privileges", "sys/policy/messagefoundry-check-privileges", "identity/group", "identity/group/name/messagefoundry-check-privileges", + "identity/entity", + "identity/entity/name/messagefoundry-check-privileges", + "identity/entity-alias", "sys/mounts/messagefoundry-check-privileges", "sys/auth/messagefoundry-check-privileges", "auth/token/create", + "auth/token/roles/messagefoundry-check-privileges", + "sys/plugins/catalog/messagefoundry-check-privileges", "sys/audit/messagefoundry-check-privileges", "sys/seal", "sys/raw/messagefoundry-check-privileges", @@ -273,41 +281,46 @@ def store_hop(report: StorePrivilegeReport, store: StoreSettings) -> HopPrivileg ) +def transit_key_paths(paths: Iterable[str], *, transit_mount: str) -> tuple[str, ...]: + """Each of ``paths`` that is a Transit key's own path, ``/keys/`` with no further + segment: a KV path whose mount happens to contain "keys" is not a Transit key. ``transit_mount`` + is the caller's, so this module stays free of the Vault provider imports.""" + prefix = f"{transit_mount}/keys/" + out = [] + for path in paths: + key = path.removeprefix(prefix) + if path.startswith(prefix) and key and "/" not in key: + out.append(path) + return tuple(dict.fromkeys(out)) + + def vault_admin_paths( required: Mapping[str, frozenset[str]], policies: Iterable[str], *, transit_mount: str, - other_keys: Iterable[str] = (), + other_required: Iterable[str] = (), ) -> tuple[str, ...]: - """Every path to ask a token about that the engine never calls, in a fixed order. + """Every path to ask a token about that the engine never calls with it, in a fixed order. :data:`VAULT_ADMIN_PATHS`, then a write of each policy the token carries (``sys/policies/acl/`` and ``sys/policy/``), which the placeholder names cannot catch when a policy grants writes only - on names like its own, then each Transit key's control, export, backup and restore paths - (:data:`_TRANSIT_KEY_ADMIN`), which would let the token make the store key exportable and read - it out. The keys are the ones ``required`` names, and the ones ``other_keys`` names: the Transit - key paths ANOTHER hop requires, so a token that never calls the store key is still asked - whether it can export it (vault BACKLOG #4851). Such a key's own path is asked about too, so a - grant that deletes or rewrites it is seen; :func:`vault_hop` judges that path by - :data:`_TRANSIT_KEY_CONTROL_CAPS` alone. At least these: grants on other paths are not read.""" + on names like its own, then each path ``other_required`` names that ``required`` does not: the + paths ANOTHER hop calls (vault BACKLOG #4851), so a connector-secret token is asked whether it + can decrypt with, delete or rewrite the store key. Then each Transit key's control, export, + backup and restore paths (:data:`_TRANSIT_KEY_ADMIN`), for the keys either set names, which + would let the token make the store key exportable and read it out. At least these: grants on + other paths are not read.""" out = list(VAULT_ADMIN_PATHS) for policy in policies: if policy != "root": # root is judged on its own, and has no path to write out += [f"sys/policies/acl/{policy}", f"sys/policy/{policy}"] - # ``transit_mount`` is the caller's: the Transit mount the providers call, so this module stays - # free of the Vault provider imports. + other = [p for p in other_required if p not in required] + out += other prefix = f"{transit_mount}/keys/" - for path, foreign in [*((p, False) for p in required), *((p, True) for p in other_keys)]: - # Only the Transit mount's key metadata path, /keys/ with no further segment: - # a KV path whose mount happens to contain "keys" is not a Transit key. + for path in transit_key_paths([*required, *other], transit_mount=transit_mount): key = path.removeprefix(prefix) - if path.startswith(prefix) and key and "/" not in key: - if foreign and path not in required: - out.append(path) - out += [ - template.format(mount=transit_mount, key=key) for template in _TRANSIT_KEY_ADMIN - ] + out += [template.format(mount=transit_mount, key=key) for template in _TRANSIT_KEY_ADMIN] return tuple(dict.fromkeys(out)) @@ -482,9 +495,7 @@ def vault_hop( got = set(reading.capabilities[path]) excess = got - needed - {"deny"} # needed never holds root, so a root grant is excess missing = set() if "root" in got else needed - got - # A Transit key's own path is one whose config path was asked about too, so no mount name - # is needed here to tell it from a KV path. - is_key = f"{path}/config" in reading.admin_paths + is_key = path in reading.transit_keys control = excess & _TRANSIT_KEY_CONTROL_CAPS if is_key else set() if control: grave.append( @@ -495,23 +506,33 @@ def vault_hop( over.append(f"{path} also grants {_caps(excess - control)} (needs {_caps(needed)})") if missing: notes.append(f"{path} lacks {_caps(missing)}, so the engine's own call would fail") + # A path a hop holding this same token calls is that hop's grant: the shared-token loop below + # reports it, in the warning class the owner ruling puts a shared token in. + shared_paths = {p for other in (shared or {}).values() for p in other.required} for path in reading.admin_paths: extra = set(reading.capabilities.get(path, ())) - {"deny"} - if f"{path}/config" in reading.admin_paths: + if path in shared_paths or not extra: + continue + if path in reading.other_paths and path in reading.transit_keys: # Another hop's Transit key: only a grant that creates, rewrites or deletes it is in # the refusing class, as on the hop's own key path above; any other grant warns. control = extra & _TRANSIT_KEY_CONTROL_CAPS if control: grave.append( f"{path} grants {_caps(control)}, which creates, rewrites or deletes the key; " - "the engine never calls it with this token" + "the engine calls it only with another hop's token" ) if extra - control: over.append( - f"{path} grants {_caps(extra - control)}; the engine never calls it with this " - "token" + f"{path} grants {_caps(extra - control)}; the engine calls it only with " + "another hop's token" ) - elif extra: + elif path in reading.other_paths: + grave.append( + f"{path} grants {_caps(extra)}, which uses another hop's key; the engine calls it " + "only with that hop's token" + ) + else: grave.append(f"{path} grants {_caps(extra)}; the engine never calls it") for other_hop, other in (shared or {}).items(): for path in other.required: @@ -552,7 +573,8 @@ def vault_hop( else: state = HopState.CLEAN # What could not be read comes right after the refusing reasons, so a detail cut to a length - # cap (the log line, the audit row) still says the token was read only in part. + # cap (the log line, the audit row) keeps it unless those reasons alone fill the cap; the + # audit row and the log line also carry ``partial`` on their own. parts = [ *(f"over-granted, refusing class: {g}" for g in grave), *(f"could not observe: {p}" for p in unread), diff --git a/messagefoundry/privilege_probes.py b/messagefoundry/privilege_probes.py index c71859b028..69babd5d60 100644 --- a/messagefoundry/privilege_probes.py +++ b/messagefoundry/privilege_probes.py @@ -39,6 +39,7 @@ from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any +from urllib.parse import urlsplit from messagefoundry.controlchars import scrub_log_argument, strip_control_chars from messagefoundry.exception_origin import ( @@ -48,7 +49,7 @@ raised_by_the_engine, raised_through, ) -from messagefoundry.privilege_check import vault_admin_paths +from messagefoundry.privilege_check import transit_key_paths, vault_admin_paths from messagefoundry.transports.bounded_read import TruncatedResponseError logger = logging.getLogger(__name__) @@ -96,6 +97,11 @@ class VaultTokenReading: problems: tuple[str, ...] = () unexcused: tuple[str, ...] = () token_ref: str | None = field(default=None, repr=False, compare=False) + #: The Transit key paths among the paths asked about, this hop's and another's, named by the + #: probe rather than guessed from a path's shape (vault BACKLOG #4851). + transit_keys: tuple[str, ...] = () + #: The paths another hop calls that this token was asked about (vault BACKLOG #4851). + other_paths: tuple[str, ...] = () def same_token_as(self, other: VaultTokenReading) -> bool: """Whether both readings were taken with the same token. ``False`` when either has no @@ -285,7 +291,7 @@ def read_vault_token( address: Callable[[], str], build_client: Callable[[str, str], Any], required: Callable[[], Mapping[str, frozenset[str]]], - other_keys: Callable[[], Iterable[str]] | None = None, + other_required: Callable[[], Iterable[str]] | None = None, ) -> VaultTokenReading: """Read one token's own policies and capabilities through the engine's client for that hop. @@ -297,10 +303,10 @@ def read_vault_token( ``config/secretprovider_vault.py``). The variables and the paths are all read before anything is returned, so one run names every one that is missing. - ``other_keys`` returns the Transit key paths another hop requires, so this token is asked - about their own, control and export paths too (vault BACKLOG #4851). A failure to name them is - recorded as a problem, not as unexcused, since the other hop's own reading names the cause; the - token is then asked about its own keys alone. + ``other_required`` returns the paths another hop calls, so this token is asked about them, and + about their Transit keys' control and export paths, too (vault BACKLOG #4851). A failure to + name them is a problem; it is also unexcused unless it is the engine's own refusal of an unset + name, which the other hop's reading names. The token is then asked about its own paths alone. Every failure is recorded as a problem. One that :func:`excused_failure` does not excuse is also named in ``unexcused``, so a code defect swallowed here still refuses an enforcing start.""" @@ -378,23 +384,30 @@ def why(exc: BaseException) -> str: except Exception as exc: # Vault answered and refused, or answered in an unexpected shape problems.append(_problem(f"token lookup-self failed: {why(exc)}")) + from messagefoundry.config.secretprovider import SecretProviderError + from messagefoundry.store.keyprovider import KeyProviderError from messagefoundry.store.keyprovider_vault import TRANSIT_MOUNT foreign: tuple[str, ...] = () - if other_keys is not None: + if other_required is not None: try: - foreign = tuple(other_keys()) - except Exception as exc: # recorded: this token was then not asked about those keys - # Not in ``unexcused``: the cause is the other hop's (an unset key name or address), - # and that hop's own reading names it. It is a problem here, so this hop never reads - # clean, nor resolves an open warning, on a read that skipped the store keys. + foreign = tuple(dict.fromkeys(other_required())) + except Exception as exc: # recorded: this token was then not asked about those paths + # The engine's own refusal of an unset key name or address is the other hop's cause, + # which that hop's own reading names, so it is a problem here and not unexcused. Any + # other failure, a code defect included, is unexcused, as everywhere in this probe. + # Either way this hop never reads clean on a read that skipped the store's paths. + fail_closed = isinstance(exc, (KeyProviderError, SecretProviderError)) + text = _why(exc) if fail_closed else why(exc) problems.append( _problem( - "the store hop's Transit keys could not be named, so this token was not asked " - f"whether it can export or delete them: {_why(exc)}" + "the store hop's Vault paths could not be named, so this token was not asked " + f"whether it can use, export or delete the store key: {text}" ) ) - admin = vault_admin_paths(needed, policies, transit_mount=TRANSIT_MOUNT, other_keys=foreign) + admin = vault_admin_paths(needed, policies, transit_mount=TRANSIT_MOUNT, other_required=foreign) + other_paths = tuple(p for p in foreign if p not in needed) + transit_keys = transit_key_paths([*needed, *other_paths], transit_mount=TRANSIT_MOUNT) capabilities: dict[str, tuple[str, ...]] = {} paths = [*needed, *admin] try: @@ -428,6 +441,8 @@ def why(exc: BaseException) -> str: problems=tuple(problems), unexcused=tuple(unexcused), token_ref=token_ref, + transit_keys=transit_keys, + other_paths=other_paths, ) @@ -462,7 +477,7 @@ def probe_vault( posture=posture, ), lambda: kv_required_capabilities(consumer.refs), - other_keys=functools.partial(_store_transit_keys, settings), + other_required=functools.partial(_store_paths, settings), ) from messagefoundry.store.keyprovider_vault import ( store_vault_address, @@ -489,28 +504,37 @@ def probe_vault( def _store_required(kind: str) -> Mapping[str, frozenset[str]]: """The paths the store consumer of ``kind`` calls, from the provider's own helper. One map for - :func:`probe_vault` and :func:`_store_transit_keys`, so the two cannot disagree.""" + :func:`probe_vault` and :func:`_store_paths`, so the two cannot disagree.""" if kind == "transit": from messagefoundry.store.crypto_transit import transit_cipher_required_capabilities return transit_cipher_required_capabilities() - from messagefoundry.store.keyprovider_vault import kek_required_capabilities + if kind == "kek": + from messagefoundry.store.keyprovider_vault import kek_required_capabilities - return kek_required_capabilities() + return kek_required_capabilities() + # A new store kind must be routed here, not defaulted to the KEK's paths. + raise ValueError(f"no store Vault paths for consumer kind {kind!r}") def _same_vault(a: str, b: str) -> bool: - """Whether two configured Vault addresses name one server, read as written: the case and a - trailing slash are ignored, and nothing is resolved. Two spellings of one server read as two, - and the cost is that the store keys go unasked of the other token, never a false refusal.""" - return a.rstrip("/").casefold() == b.rstrip("/").casefold() + """Whether two configured Vault addresses name one server, read as written: the scheme and + host are compared without case, the port and path as written, a trailing slash ignored, and + nothing is resolved. Two spellings of one server read as two, and the store's paths then go + unasked of the other token: a residual, never a false refusal.""" + sa, sb = urlsplit(a.rstrip("/")), urlsplit(b.rstrip("/")) + return (sa.scheme.casefold(), sa.netloc.casefold(), sa.path) == ( + sb.scheme.casefold(), + sb.netloc.casefold(), + sb.path, + ) -def _store_transit_keys(settings: ServiceSettings) -> tuple[str, ...]: - """The Transit key paths the store hop requires, when the connector-secret token talks to the - same Vault; otherwise none. The connector-secret token is asked about these keys' own, control - and export paths too, so a token that never calls the store key still reads over-granted when - it can export or delete it (vault BACKLOG #4851). The store consumer is the one +def _store_paths(settings: ServiceSettings) -> tuple[str, ...]: + """The paths the store hop calls, when the connector-secret token talks to the same Vault; + otherwise none. The connector-secret token is asked about them, and about their keys' control + and export paths, so a token that never calls the store key still reads over-granted when it + can decrypt with, export or delete it (vault BACKLOG #4851). The store consumer is the one :func:`~messagefoundry.privilege_check.vault_consumers` names, so the dispatch is that function's. Raises as the store's helpers do, for an unset address or key name.""" from messagefoundry.privilege_check import vault_consumers diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index e62067b907..9c65c66d0c 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -44,6 +44,7 @@ from __future__ import annotations import asyncio +import contextvars import json import logging import threading @@ -198,13 +199,26 @@ async def _probe_all( async def bounded(consumer: VaultConsumer) -> VaultTokenReading: done: asyncio.Future[VaultTokenReading] = loop.create_future() + context = contextvars.copy_context() def deliver(reading: VaultTokenReading) -> None: if not done.done(): # cancelled by the bound, so nobody reads it done.set_result(reading) def run() -> None: - reading = _probe_one(consumer, probe) + try: + # Under the caller's context, as asyncio.to_thread would run it. + reading = context.run(_probe_one, consumer, probe) + except BaseException as exc: # noqa: BLE001 - _probe_one catches Exception; this is the rest + # Delivered rather than lost, so it is not read as a timeout, which only warns: a + # BaseException is not one the ruling excuses, so it refuses under enforce. + name = type(exc).__name__ + log.warning( + "vault privilege preflight: %s: the probe raised %s", consumer.hop, name + ) + reading = VaultTokenReading( + problems=(f"the probe raised {name}",), unexcused=(name,) + ) try: loop.call_soon_threadsafe(deliver, reading) except RuntimeError: # the loop closed after the bound gave up on this probe @@ -268,10 +282,11 @@ async def run_vault_privilege_preflight( log.info("vault privilege preflight: %s %s", hop.hop, hop.state.value) else: log.warning( - "vault privilege preflight: %s %s, enforcing=%s: %s%s", + "vault privilege preflight: %s %s, enforcing=%s, partial=%s: %s%s", hop.hop, hop.state.value, enforcing, + hop.partial, scrub_log_argument(hop.detail[:_AUDIT_DETAIL_LIMIT]), "; REFUSING to start" if refusing else "", ) diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index 70759a2303..2ef73fa2b1 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -32,6 +32,7 @@ serve_verdict, vault_admin_paths, vault_hop, + vault_hops, vault_preflight_outcome, ) from messagefoundry.privilege_probes import VaultTokenReading, probe_vault, read_vault_token @@ -122,20 +123,20 @@ def test_a_kv_path_holding_delete_is_not_read_as_a_transit_key() -> None: # --- a connector-secret token holding export on the store key ---------------------------------- -def _kv_reading(vault: _FakeVault, other_keys: Any = None) -> VaultTokenReading: +def _kv_reading(vault: _FakeVault, other_required: Any = None) -> VaultTokenReading: return read_vault_token( lambda: _TOKEN, lambda: _VAULT_ADDR, lambda a, t: vault, lambda: {_KV_PATH: frozenset({"read"})}, - other_keys=other_keys, + other_required=other_required, ) def test_a_secrets_token_that_can_export_the_store_key_refuses() -> None: export = f"transit/export/encryption-key/{_KEK}" vault = _FakeVault(caps={_KV_PATH: ["read"], export: ["read"]}) - hop = vault_hop(_KV, _kv_reading(vault, other_keys=lambda: [f"transit/keys/{_KEK}"])) + hop = vault_hop(_KV, _kv_reading(vault, other_required=lambda: [f"transit/keys/{_KEK}"])) assert any(r.startswith(f"{export} grants read") for r in hop.refusing) # The control: without the store's key named, the same grant is never asked about. alone = vault_hop(_KV, _kv_reading(_FakeVault(caps={_KV_PATH: ["read"], export: ["read"]}))) @@ -146,35 +147,82 @@ def test_a_secrets_token_that_can_export_the_store_key_refuses() -> None: def test_a_secrets_token_that_can_delete_or_rewrite_the_store_key_refuses(cap: str) -> None: key = f"transit/keys/{_KEK}" vault = _FakeVault(caps={_KV_PATH: ["read"], key: [cap]}) - hop = vault_hop(_KV, _kv_reading(vault, other_keys=lambda: [key])) + hop = vault_hop(_KV, _kv_reading(vault, other_required=lambda: [key])) assert any(r.startswith(f"{key} grants {cap}, which creates") for r in hop.refusing) def test_a_secrets_token_reading_the_store_key_only_warns() -> None: key = f"transit/keys/{_KEK}" vault = _FakeVault(caps={_KV_PATH: ["read"], key: ["read"]}) - hop = vault_hop(_KV, _kv_reading(vault, other_keys=lambda: [key])) + hop = vault_hop(_KV, _kv_reading(vault, other_required=lambda: [key])) assert hop.state is HopState.OVER_GRANTED and hop.refusing == () - assert f"{key} grants read; the engine never calls it with this token" in hop.detail + assert f"{key} grants read; the engine calls it only with another hop's token" in hop.detail -def test_a_failure_naming_the_other_hops_keys_is_a_problem_not_a_clean_read() -> None: +def test_a_secrets_token_that_can_decrypt_with_the_store_key_refuses() -> None: + decrypt = f"transit/decrypt/{_KEK}" + vault = _FakeVault(caps={_KV_PATH: ["read"], decrypt: ["update"]}) + paths = [f"transit/keys/{_KEK}", decrypt] + hop = vault_hop(_KV, _kv_reading(vault, other_required=lambda: paths)) + assert any(r.startswith(f"{decrypt} grants update, which uses another") for r in hop.refusing) + + +def test_one_token_on_both_hops_reports_the_store_grants_once_and_only_warns() -> None: + """The owner ruling's shared-token case stays in the warning class with the store's paths + asked of the secrets token too: they are the same token's own grants.""" + caps = _least_caps() | {_KV_PATH: ["read"]} + store = _reading(_FakeVault(caps=caps)) + secrets = _kv_reading(_FakeVault(caps=caps), other_required=lambda: list(_least_caps())) + hops = vault_hops([_STORE, _KV], [store, secrets]) + assert [h.refusing for h in hops] == [(), ()] + assert hops[1].detail.count(f"transit/decrypt/{_KEK}") == 1 + + +def test_a_failure_naming_the_store_paths_is_a_problem_not_a_clean_read() -> None: + from messagefoundry.store.keyprovider import KeyProviderError + def unset() -> list[str]: - raise ValueError("no key name") + raise KeyProviderError("the store key name is not set") - reading = _kv_reading(_FakeVault(caps={_KV_PATH: ["read"]}), other_keys=unset) + reading = _kv_reading(_FakeVault(caps={_KV_PATH: ["read"]}), other_required=unset) assert reading.capabilities - assert any("store hop's Transit keys could not be named" in p for p in reading.problems) + assert any("store hop's Vault paths could not be named" in p for p in reading.problems) assert reading.unexcused == () hop = vault_hop(_KV, reading) assert hop.state is HopState.UNOBSERVABLE and hop.partial +def test_a_code_defect_naming_the_store_paths_is_unexcused() -> None: + def broken() -> list[str]: + raise AttributeError("renamed") + + reading = _kv_reading(_FakeVault(caps={_KV_PATH: ["read"]}), other_required=broken) + assert reading.unexcused == ("AttributeError",) + hop = vault_hop(_KV, reading) + assert vault_preflight_outcome(hop, enforcing=True, over_grant_accepted=False) is ( + PreflightOutcome.REFUSE + ) + + +@pytest.mark.parametrize( + ("a", "b", "same"), + [ + ("https://Vault.Example:8200", "https://vault.example:8200/", True), + ("https://vault.example:8200/Proxy", "https://vault.example:8200/proxy", False), + ("https://vault.example:8200", "https://other.example:8200", False), + ], +) +def test_same_vault_reads_addresses_as_written(a: str, b: str, same: bool) -> None: + from messagefoundry.privilege_probes import _same_vault + + assert _same_vault(a, b) is same + + def _probe_kv_keys(monkeypatch: pytest.MonkeyPatch) -> Any: seen: dict[str, Any] = {} - def fake(*args: Any, other_keys: Any = None) -> VaultTokenReading: - seen["keys"] = other_keys() if other_keys is not None else None + def fake(*args: Any, other_required: Any = None) -> VaultTokenReading: + seen["keys"] = other_required() if other_required is not None else None return VaultTokenReading() monkeypatch.setattr("messagefoundry.privilege_probes.read_vault_token", fake) @@ -190,7 +238,7 @@ def test_probe_vault_hands_the_store_keys_to_the_secrets_probe( monkeypatch.setenv("MEFOR_SECRETS_VAULT_ADDR", _VAULT_ADDR + "/") keys = _probe_kv_keys(monkeypatch) assert f"transit/keys/{_KEK}" in keys - assert set(vault_admin_paths({}, (), transit_mount="transit", other_keys=keys)) >= { + assert set(vault_admin_paths({}, (), transit_mount="transit", other_required=keys)) >= { f"transit/keys/{_KEK}", f"transit/export/encryption-key/{_KEK}", } @@ -267,6 +315,26 @@ async def test_the_audit_row_caps_the_refusing_reasons() -> None: # --- the probes are bounded and run side by side ----------------------------------------------- +async def test_a_probe_raising_a_base_exception_refuses_rather_than_timing_out() -> None: + class Stop(BaseException): + pass + + def stop(consumer: VaultConsumer) -> VaultTokenReading: + raise Stop + + started = time.monotonic() + with pytest.raises(VaultPrivilegeError, match="Stop"): + await run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=stop, + probe_timeout=30, + ) + assert time.monotonic() - started < 10 + + async def test_a_probe_that_hangs_is_cut_off_and_only_warns() -> None: release = threading.Event() From 14792d3f7adf91affb121ecee1475f694261d5e0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:23:59 -0600 Subject: [PATCH 06/31] Vault token preflight docs: review round two repairs SECURITY.md's least-privilege table rows for the three Vault hops point at the refusing class rather than root and administrative grants alone. The administrative path list adds the identity-entity, token-role and plugin paths, says disable_unauthed_rekey_endpoints closes only the rekey endpoint, and says the connector-secret token is asked about every path the store hop calls on the same address, a decrypt grant included. BACKLOG #4851 Proposed PR title: Vault token preflight: close the refusal gaps, bound the probes, report it in GET /security/posture (BACKLOG #4851) Proposed banner #4851: BUILT, PR pending. The Vault preflight asks about sys/audit, sys/seal, sys/raw, sys/generate-root, sys/rekey, identity entity, token-role and plugin paths, and each Transit key's trim, import, import_version, versioned export, BYOK export and restore; a grant that creates, rewrites or deletes a Transit key refuses; the connector-secret token is asked about the store hop's paths on the same Vault. Probes run side by side under a 150 s bound. GET /security/posture carries vault_privilege. A denied lookup-self says the policy-write check did not run. The remaining findings are kept, each with a line in the PR body. Verified-by: tests --- docs/SECURITY.md | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index c6bf15e058..d2abb81f0b 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1147,9 +1147,9 @@ backend hops that present a static credential or none (the *Delegated identity* | Store, SQL Server | the `[store]` login: the service account under `auth = "integrated"`, else `[store].username` | `db_datareader` + `db_datawriter`, plus `db_ddladmin` only under `schema_management = "auto"`; under `key_provider = "host"`, the login that runs `provision-admin` needs more, at least what [DEPLOY-SERVER-DB.md §1.1](DEPLOY-SERVER-DB.md#11-integrated-gmsa-authentication--sql-server-worked-example-99) names; `UPDATE` and `DELETE` denied on `audit_log`; no server role | **Yes**, at every start and by `check-privileges`; an over-grant refuses start under `enforce` | | Store, PostgreSQL | `[store].username` | a `LOGIN` role with no attributes: `CONNECT`, `USAGE` on the store schema and row grants, only `INSERT` and `SELECT` on `audit_log`; it owns that schema only under `auto` | **Yes**, at every start and by `check-privileges`; an over-grant refuses start under `enforce` | | Store, SQLite | the service account | only that account may read and write the `.db` file and its `-wal`/`-shm` sidecars | No: reported **not applicable**; the filesystem ACL governs it | -| Vault, store key provider | the token in `MEFOR_STORE_VAULT_TOKEN` | `read` on `transit/keys/` and `update` on `transit/decrypt/`; plus `read` on `auth/token/lookup-self` and `update` on `sys/capabilities-self` for the privilege probe `serve` and `check-privileges` run | **Yes**, at every start and by `check-privileges` (hop `vault.store`); the root policy or an administrative grant refuses start under `enforce`, anything else warns | -| Vault, Transit cipher | the token in `MEFOR_STORE_VAULT_TOKEN` | `read` on the data and audit keys under `transit/keys/`; `update` on `transit/encrypt/` and `transit/decrypt/` for the data key and `transit/hmac/` and `transit/verify/` for the audit key (the verify grant is for the row seals of ADR 0217); plus `read` on `auth/token/lookup-self` and `update` on `sys/capabilities-self` for the privilege probe `serve` and `check-privileges` run | **Yes**, at every start and by `check-privileges` (hop `vault.store`); the root policy or an administrative grant refuses start under `enforce`, anything else warns | -| Vault, connector secrets | the token in `MEFOR_SECRETS_VAULT_TOKEN` | `read` on the KV v2 data path of each `*_secret` reference, and nothing else; plus `read` on `auth/token/lookup-self` and `update` on `sys/capabilities-self` for the privilege probe `serve` and `check-privileges` run | **Yes**, at every start and by `check-privileges` (hop `vault.secrets`); the root policy or an administrative grant refuses start under `enforce`, anything else warns | +| Vault, store key provider | the token in `MEFOR_STORE_VAULT_TOKEN` | `read` on `transit/keys/` and `update` on `transit/decrypt/`; plus `read` on `auth/token/lookup-self` and `update` on `sys/capabilities-self` for the privilege probe `serve` and `check-privileges` run | **Yes**, at every start and by `check-privileges` (hop `vault.store`); a refusing-class grant (listed below) refuses start under `enforce`, a warning-class one warns | +| Vault, Transit cipher | the token in `MEFOR_STORE_VAULT_TOKEN` | `read` on the data and audit keys under `transit/keys/`; `update` on `transit/encrypt/` and `transit/decrypt/` for the data key and `transit/hmac/` and `transit/verify/` for the audit key (the verify grant is for the row seals of ADR 0217); plus `read` on `auth/token/lookup-self` and `update` on `sys/capabilities-self` for the privilege probe `serve` and `check-privileges` run | **Yes**, at every start and by `check-privileges` (hop `vault.store`); a refusing-class grant (listed below) refuses start under `enforce`, a warning-class one warns | +| Vault, connector secrets | the token in `MEFOR_SECRETS_VAULT_TOKEN` | `read` on the KV v2 data path of each `*_secret` reference, and nothing else; plus `read` on `auth/token/lookup-self` and `update` on `sys/capabilities-self` for the privilege probe `serve` and `check-privileges` run | **Yes**, at every start and by `check-privileges` (hop `vault.secrets`); a refusing-class grant (listed below) refuses start under `enforce`, a warning-class one warns | | LDAP (AD) | `[auth].ad_bind_dn` | read and search on the user and group search bases; no write and no administrative group | **Partly**, by `check-privileges`: identity and administrative groups; delegated ACLs not read; never gates a start | | SMTP (alerts) | `[alerts].email_username`, or no AUTH account | send as `[alerts].email_from` only | No: printed, not probed | | IdP (OIDC) | `[auth].oidc_client_id` at `[auth].oidc_issuer` | a confidential client allowed the configured `oidc_scopes` only; no directory or admin API permission | No: printed, not probed | @@ -1174,18 +1174,23 @@ The administrative paths it is asked about are at least these: - two policy writes under a placeholder name, `sys/policies/acl/` and the older `sys/policy/`; - the same two writes for each policy the token carries, which catches a policy that may rewrite itself; -- two identity-group paths that can attach a policy, `identity/group` and `identity/group/name/`; -- a secrets mount (`sys/mounts/`), an auth method (`sys/auth/`) and `auth/token/create`; +- two identity-group paths that can attach a policy, `identity/group` and `identity/group/name/`, + and three identity-entity paths that can too, `identity/entity`, `identity/entity/name/` and + `identity/entity-alias`; +- a secrets mount (`sys/mounts/`), an auth method (`sys/auth/`), `auth/token/create`, a token role + (`auth/token/roles/`) and a plugin registration (`sys/plugins/catalog/`); - an audit device (`sys/audit/`), `sys/seal`, raw storage (`sys/raw/`), and the root-token generation and rekey endpoints (`sys/generate-root/attempt`, `sys/rekey/init`). Vault serves - those two without a token unless `disable_unauthed_rekey_endpoints` is set, so a token clean - there does not mean nobody can start one; + those two without a token (`disable_unauthed_rekey_endpoints` closes only the rekey one to + unauthenticated callers), so a token clean there does not mean nobody can start one; - for each Transit key the engine uses, its `config` (which can make the key exportable), `rotate`, `trim`, `import`, `import_version`, `export` (every version, and one version), BYOK export, - `backup`, and `restore` with and without the key's name. When the connector-secret token talks - to the same Vault address as the store, it is asked about the store's keys too, their own path - included, so a token that never calls the store key still reads over-granted when it can export - or delete it. + `backup`, and `restore` with and without the key's name; +- when the connector-secret token talks to the same Vault address as the store (read as written, + so two spellings of one server read as two), every path the store hop calls, and its keys' paths + above. A grant there that creates, rewrites or deletes the store key, or uses it (such as + `update` on `transit/decrypt/`), is in the refusing class; any other grant on the key's own + path warns. A token shared by both hops is judged as the shared-token rule above says instead. On a Transit key's own path a `create`, `update`, `patch`, `delete`, `sudo` or `root` grant creates, rewrites or deletes the key, and is in the refusing class. Any other grant there that the engine From 1a8cb03d104c34caca7ac4c5b34b942ef36e0a33 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:52:07 -0600 Subject: [PATCH 07/31] Vault token preflight: repair round three (B1, B2, B4, B5, B6, B8) BACKLOG #4851, bounded repair of the branch's own new code. - A grant on a path another hop calls, other than its key's own path, now warns rather than refuses when either reading carries no token to compare (a probe that failed, timed out or found the token unset), and says why: shared, it would be that hop's grant and warn, so the outcome no longer turns on whether the store probe finished. - On another hop's path only a create, update, patch, delete, sudo or root grant refuses; read and list warn. The reason on a non-key path says the path uses another hop's key, and VAULT_REFUSING_CLASS names the case. - A probe thread that cannot start yields a reading with one problem and nothing unexcused, so it never aborts a start. - The probes' lazy imports run once before any probe thread starts. - A shared token whose other hop failed to read a path it calls now has that grant reported as a warning, from this hop's read or as unjudged. - GET /security/posture caps the refusing list and the detail as the audit row does. Verified-by: tests --- messagefoundry/api/app.py | 13 +- messagefoundry/privilege_check.py | 90 ++++++--- messagefoundry/privilege_probes.py | 33 +++ messagefoundry/vault_preflight.py | 42 +++- tests/test_vault_privilege_preflight_4851.py | 199 ++++++++++++++++++- 5 files changed, 343 insertions(+), 34 deletions(-) diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index d320521ddf..986b9652e4 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -619,7 +619,11 @@ browse_messages, split_uploaded, ) -from messagefoundry.vault_preflight import run_vault_privilege_preflight +from messagefoundry.vault_preflight import ( + capped_detail, + capped_refusing, + run_vault_privilege_preflight, +) __all__ = ["create_app", "create_managed_app"] @@ -6022,7 +6026,8 @@ async def security_posture( # Vault BACKLOG #4851: each Vault token as the startup preflight judged it; None means no # preflight ran in this process, which reads as not_probed, never as clean. # A hop's detail and reasons name KV paths, which can name a connection, so a channel-scoped - # reader (BACKLOG #3189) is shown each hop's state and counts, never its text. + # reader (BACKLOG #3189) is shown each hop's state and counts, never its text. The text is + # capped as the audit row caps it, since a server names the policies and paths in it. vault_privilege = getattr(request.app.state, "vault_privilege", None) vault_privilege_view = ( VaultPrivilegeView(status=STORE_PRIVILEGE_NOT_PROBED) @@ -6034,11 +6039,11 @@ async def security_posture( VaultPrivilegeHopView( hop=h.hop, state=h.state.value, - refusing=list(h.refusing) if visible is None else [], + refusing=capped_refusing(h) if visible is None else [], refusing_count=len(h.refusing), unexcused=list(h.unexcused), partial=h.partial, - detail=h.detail if visible is None else "", + detail=capped_detail(h) if visible is None else "", ) for h in vault_privilege ], diff --git a/messagefoundry/privilege_check.py b/messagefoundry/privilege_check.py index e6737c7c1f..8d16a5da17 100644 --- a/messagefoundry/privilege_check.py +++ b/messagefoundry/privilege_check.py @@ -31,7 +31,7 @@ from __future__ import annotations import unicodedata -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, replace from enum import Enum from typing import TYPE_CHECKING, Literal @@ -277,7 +277,8 @@ def store_hop(report: StorePrivilegeReport, store: StoreSettings) -> HopPrivileg #: The refusing class, in the words every refusal and audit line uses, stated once here (ADR 0216). VAULT_REFUSING_CLASS = ( "the root policy, or a grant on an administrative path, on a Transit key's control, export, " - "backup or restore path, or one that creates, rewrites or deletes a Transit key" + "backup or restore path, or one that creates, rewrites or deletes a Transit key, or a create, " + "update, patch, delete, sudo or root grant on a path that uses another hop's key" ) @@ -449,9 +450,17 @@ def vault_hop( reading: VaultTokenReading, *, shared: Mapping[str, VaultTokenReading] | None = None, + unmatched: Sequence[str] = (), ) -> HopPrivilege: """Judge one token's self-reading against what the engine calls with it. + ``unmatched`` names each other hop whose reading, or this one, carries no token to compare + (its probe failed, timed out or found the token unset), so whether it holds this same token is + unknown. A grant on a path only such a hop calls, other than on a Transit key's own path, then + warns rather than refuses: had the token been compared and found shared, the grant would be + that hop's own and warn, so the outcome would otherwise turn on whether a probe finished (vault + BACKLOG #4851). + Over-granted: a ``root`` policy; any capability beyond the one a configured path needs; any capability but ``deny`` on an administrative path the engine never calls; or, when ``shared`` names other hops that hold the SAME token, any grant on a path only those hops need. One token @@ -462,8 +471,9 @@ def vault_hop( **Two classes (ADR 0216, owner ruling 2026-10-04).** :data:`VAULT_REFUSING_CLASS` is the REFUSING class, kept in :attr:`HopPrivilege.refusing`: the paths :func:`vault_admin_paths` - names, and :data:`_TRANSIT_KEY_CONTROL_CAPS` on a Transit key's own path. Everything else is the - WARNING class, at least: a token shared + names, except a path another hop calls, and :data:`_TRANSIT_KEY_CONTROL_CAPS` on a Transit + key's own path or on a path another hop calls. Everything else is the WARNING class, at least: + read or list on a path another hop calls, a token shared by two hops, an extra capability on a path the engine calls, and a policy name the probe cannot tell from root by reading it, which means it cannot judge rather than that it saw root.""" grave: list[str] = [] @@ -513,33 +523,62 @@ def vault_hop( extra = set(reading.capabilities.get(path, ())) - {"deny"} if path in shared_paths or not extra: continue - if path in reading.other_paths and path in reading.transit_keys: - # Another hop's Transit key: only a grant that creates, rewrites or deletes it is in - # the refusing class, as on the hop's own key path above; any other grant warns. + if path in reading.other_paths: + # A path another hop calls: only a create, update, patch, delete, sudo or root grant + # is in the refusing class, as on the hop's own key path above; read, list or any + # other grant warns. On a path that is not the key's own, such a grant is what uses + # the key, as update on transit/decrypt/ does (vault BACKLOG #4851). + is_key = path in reading.transit_keys control = extra & _TRANSIT_KEY_CONTROL_CAPS - if control: + if control and unmatched and not is_key: + # Shared or not is unknown, and a shared token's grant here would only warn. + over.append( + f"{path} grants {_caps(control)} on a path that uses another hop's key; it " + f"warns rather than refuses because whether {', '.join(unmatched)} holds this " + "same token is unknown, a token not having been read" + ) + elif control and is_key: + grave.append( + f"{path} grants {_caps(control)}, which creates, rewrites or deletes another " + "hop's key; the engine calls it only with that hop's token" + ) + elif control: grave.append( - f"{path} grants {_caps(control)}, which creates, rewrites or deletes the key; " - "the engine calls it only with another hop's token" + f"{path} grants {_caps(control)}; that path uses another hop's key, and the " + "engine calls it only with that hop's token" ) if extra - control: over.append( f"{path} grants {_caps(extra - control)}; the engine calls it only with " "another hop's token" ) - elif path in reading.other_paths: - grave.append( - f"{path} grants {_caps(extra)}, which uses another hop's key; the engine calls it " - "only with that hop's token" - ) else: grave.append(f"{path} grants {_caps(extra)}; the engine never calls it") for other_hop, other in (shared or {}).items(): for path in other.required: - extra = set(other.capabilities.get(path, ())) - {"deny"} - if path not in reading.required and extra: + if path in reading.required: + continue + if path in other.capabilities: + extra = set(other.capabilities[path]) - {"deny"} + if extra: + over.append( + f"the same token serves {other_hop}, so it also holds {_caps(extra)} on " + f"{path}" + ) + continue + # The other hop's read of this path failed, and the loop above skipped it as that + # hop's grant: say what this hop's own read saw there, or that nothing did, so the + # grant is not dropped from both hops (vault BACKLOG #4851). Reported only. + mine = set(reading.capabilities.get(path, ())) - {"deny"} + if mine: over.append( - f"the same token serves {other_hop}, so it also holds {_caps(extra)} on {path}" + f"the same token serves {other_hop}, so it also holds {_caps(mine)} on {path} " + f"(read on this hop; {other_hop}'s own read of it failed)" + ) + elif path not in reading.capabilities: + over.append( + f"the same token serves {other_hop}, whose read of {path} failed, so the " + "grant there was not judged on either hop" ) unread = list(reading.problems) @@ -612,12 +651,17 @@ def vault_hops( reading that could not name its token is judged alone.""" hops: list[HopPrivilege] = [] for consumer, reading in zip(consumers, readings, strict=True): - shared = { - other_consumer.hop: other + others = [ + (other_consumer.hop, other) for other_consumer, other in zip(consumers, readings, strict=True) - if other is not reading and reading.same_token_as(other) - } - hops.append(vault_hop(consumer, reading, shared=shared)) + if other is not reading + ] + shared = {hop: other for hop, other in others if reading.same_token_as(other)} + # A reading with no token to compare, this one or another's, leaves sharing unknown. + unmatched = [ + hop for hop, other in others if reading.token_ref is None or other.token_ref is None + ] + hops.append(vault_hop(consumer, reading, shared=shared, unmatched=unmatched)) return hops diff --git a/messagefoundry/privilege_probes.py b/messagefoundry/privilege_probes.py index 69babd5d60..c39ff151c0 100644 --- a/messagefoundry/privilege_probes.py +++ b/messagefoundry/privilege_probes.py @@ -34,6 +34,7 @@ import functools import hashlib +import importlib import logging import socket from collections.abc import Callable, Iterable, Mapping @@ -63,6 +64,7 @@ __all__ = [ "VaultTokenReading", "excused_failure", + "preload_vault_probe_imports", "probe_vault", "read_ldap_bind", "read_vault_token", @@ -446,6 +448,37 @@ def why(exc: BaseException) -> str: ) +#: Every module :func:`probe_vault` and :func:`read_vault_token` import lazily, and hvac, which the +#: Vault clients they build import. :func:`preload_vault_probe_imports` imports them all. +_VAULT_PROBE_IMPORTS = ( + "messagefoundry.config.secretprovider", + "messagefoundry.config.secretprovider_vault", + "messagefoundry.config.tls_policy", + "messagefoundry.store.crypto_transit", + "messagefoundry.store.keyprovider", + "messagefoundry.store.keyprovider_vault", + "hvac", + "hvac.exceptions", +) + + +def preload_vault_probe_imports() -> None: + """Import, on the calling thread, every module the Vault probe imports lazily, so the startup + preflight can do it before any probe thread starts (vault BACKLOG #4851). One that cannot be + imported, hvac on an install without the Vault extra at least, is left for the probe, which + meets the same failure in its own import and reports it as it always has; so a failure here + never raises, and never aborts a start the probe would only warn on.""" + for name in _VAULT_PROBE_IMPORTS: + try: + importlib.import_module(name) + except Exception as exc: # noqa: BLE001 - the probe's own import reports it + logger.debug( + "privilege probe: importing %s raised %s; the probe reports it", + name, + type(exc).__name__, + ) + + def probe_vault( consumer: VaultConsumer, settings: ServiceSettings, *, posture: HopPosture | None = None ) -> VaultTokenReading: diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index 9c65c66d0c..c4d98d6e71 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -65,7 +65,11 @@ vault_preflight_outcome, vault_refusal_reason, ) -from messagefoundry.privilege_probes import VaultTokenReading, unexcused_cause +from messagefoundry.privilege_probes import ( + VaultTokenReading, + preload_vault_probe_imports, + unexcused_cause, +) from messagefoundry.store.privilege import PreflightOutcome if TYPE_CHECKING: # pragma: no cover - typing only @@ -79,6 +83,8 @@ "VaultAuditStore", "VaultPrivilegeAlertSink", "VaultPrivilegeError", + "capped_detail", + "capped_refusing", "run_vault_privilege_preflight", "vault_privilege_alert_subject", ] @@ -105,6 +111,19 @@ VAULT_PROBE_TIMEOUT_S = 150.0 +def capped_refusing(hop: HopPrivilege) -> list[str]: + """The hop's refusing reasons as the audit row and ``GET /security/posture`` keep them: at most + :data:`_AUDIT_REFUSING_LIMIT`, each cut to :data:`_AUDIT_REASON_LIMIT` characters. Beside it, + ``len(hop.refusing)`` keeps the true count.""" + return [r[:_AUDIT_REASON_LIMIT] for r in hop.refusing[:_AUDIT_REFUSING_LIMIT]] + + +def capped_detail(hop: HopPrivilege) -> str: + """The hop's detail as the audit row and ``GET /security/posture`` keep it, cut to + :data:`_AUDIT_DETAIL_LIMIT` characters.""" + return hop.detail[:_AUDIT_DETAIL_LIMIT] + + class VaultPrivilegeError(RuntimeError): """Raised by the preflight when ``vault_preflight_outcome`` refuses a Vault hop under ``enforce``: a grant in the refusing class with no accepted opt-out, or an unexcused probe @@ -196,6 +215,10 @@ async def _probe_all( dropped. It is a daemon thread of its own, not the loop's default executor, so neither the loop's shutdown nor the interpreter's exit waits on it.""" loop = asyncio.get_running_loop() + # The probes import their providers lazily. Done here, once, before any probe thread starts, + # so the probe threads do not import side by side, and none abandoned at the bound is left + # part way through an import (vault BACKLOG #4851). + preload_vault_probe_imports() async def bounded(consumer: VaultConsumer) -> VaultTokenReading: done: asyncio.Future[VaultTokenReading] = loop.create_future() @@ -226,9 +249,16 @@ def run() -> None: "vault privilege preflight: %s finished after its loop closed", consumer.hop ) - threading.Thread( - target=run, name=f"vault-privilege-probe-{consumer.hop}", daemon=True - ).start() + try: + threading.Thread( + target=run, name=f"vault-privilege-probe-{consumer.hop}", daemon=True + ).start() + except RuntimeError as exc: # no thread to be had, such as at the thread limit + # A reading with a problem and nothing unexcused, so it warns and never aborts the + # start, under warn or enforce (vault BACKLOG #4851). + problem = f"the probe could not start a thread ({type(exc).__name__})" + log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) + return VaultTokenReading(problems=(problem,)) try: return await asyncio.wait_for(done, timeout=timeout) except TimeoutError: @@ -303,11 +333,11 @@ async def run_vault_privilege_preflight( detail = { "hop": hop.hop, "state": hop.state.value, - "refusing": [r[:_AUDIT_REASON_LIMIT] for r in hop.refusing[:_AUDIT_REFUSING_LIMIT]], + "refusing": capped_refusing(hop), "refusing_count": len(hop.refusing), "partial": hop.partial, "unexcused": list(hop.unexcused), - "detail": hop.detail[:_AUDIT_DETAIL_LIMIT], + "detail": capped_detail(hop), "enforcing": enforcing, "refused": refusing, "over_grant_accepted": accepted, diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index 2ef73fa2b1..9a264fa0c0 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -164,7 +164,120 @@ def test_a_secrets_token_that_can_decrypt_with_the_store_key_refuses() -> None: vault = _FakeVault(caps={_KV_PATH: ["read"], decrypt: ["update"]}) paths = [f"transit/keys/{_KEK}", decrypt] hop = vault_hop(_KV, _kv_reading(vault, other_required=lambda: paths)) - assert any(r.startswith(f"{decrypt} grants update, which uses another") for r in hop.refusing) + assert any( + r.startswith(f"{decrypt} grants update; that path uses another hop's key") + for r in hop.refusing + ) + + +@pytest.mark.parametrize("cap", ["read", "list"]) +def test_read_or_list_on_another_hops_non_key_path_only_warns(cap: str) -> None: + """Only a grant that uses or controls the key refuses there; read and list do neither.""" + decrypt = f"transit/decrypt/{_KEK}" + vault = _FakeVault(caps={_KV_PATH: ["read"], decrypt: [cap]}) + paths = [f"transit/keys/{_KEK}", decrypt] + hop = vault_hop(_KV, _kv_reading(vault, other_required=lambda: paths)) + assert hop.state is HopState.OVER_GRANTED and hop.refusing == () + assert f"{decrypt} grants {cap}; the engine calls it only with another hop's token" in ( + hop.detail + ) + assert "uses another hop's key" not in hop.detail + assert vault_preflight_outcome(hop, enforcing=True, over_grant_accepted=False) is ( + PreflightOutcome.WARN + ) + + +def _unread_store_and_secrets(store_token: str | None) -> list[Any]: + """The store's reading with ``store_token`` as its token reference, and a secrets reading on + another token that can decrypt with the store key.""" + decrypt = f"transit/decrypt/{_KEK}" + store = VaultTokenReading(problems=("the probe did not finish",), token_ref=store_token) + vault = _FakeVault(caps={_KV_PATH: ["read"], decrypt: ["update"]}) + secrets = _kv_reading(vault, other_required=lambda: [f"transit/keys/{_KEK}", decrypt]) + return vault_hops([_STORE, _KV], [store, secrets]) + + +def test_a_store_probe_with_no_token_leaves_the_decrypt_grant_warning() -> None: + """Whether the two hops share a token is unknown, and shared it would only warn, so the + outcome must not turn on whether the store's probe finished.""" + _, secrets = _unread_store_and_secrets(None) + assert secrets.refusing == () + assert "whether vault.store holds this same token is unknown" in secrets.detail + assert vault_preflight_outcome(secrets, enforcing=True, over_grant_accepted=False) is ( + PreflightOutcome.WARN + ) + # The control: a store reading that names another token refuses the same grant. + _, apart = _unread_store_and_secrets("another-token-ref") + assert any(f"transit/decrypt/{_KEK} grants update" in r for r in apart.refusing) + + +def test_a_store_probe_with_no_token_still_refuses_a_grant_on_its_key() -> None: + """Control on the key itself refuses either way: shared, the store hop would refuse it.""" + key = f"transit/keys/{_KEK}" + store = VaultTokenReading(problems=("the probe did not finish",)) + vault = _FakeVault(caps={_KV_PATH: ["read"], key: ["delete"]}) + secrets = _kv_reading(vault, other_required=lambda: [key]) + _, hop = vault_hops([_STORE, _KV], [store, secrets]) + assert any(r.startswith(f"{key} grants delete") for r in hop.refusing) + + +async def test_a_timed_out_store_probe_does_not_refuse_the_secrets_decrypt_grant( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(vault_preflight, "vault_consumers", lambda settings: [_STORE, _KV]) + decrypt = f"transit/decrypt/{_KEK}" + release = threading.Event() + + def probe(consumer: VaultConsumer) -> VaultTokenReading: + if consumer.hop == "vault.store": + release.wait(10) + return VaultTokenReading() + vault = _FakeVault(caps={_KV_PATH: ["read"], decrypt: ["update"]}) + return _kv_reading(vault, other_required=lambda: [f"transit/keys/{_KEK}", decrypt]) + + try: + hops = await run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=probe, + probe_timeout=0.2, + ) + finally: + release.set() + store, secrets = hops + assert "did not finish within 0.2s" in store.detail + assert secrets.refusing == () and secrets.state is HopState.OVER_GRANTED + assert "is unknown" in secrets.detail + + +def test_a_shared_token_whose_store_read_failed_reports_the_skipped_grant() -> None: + """Report only: the grant is named as a warning, never a refusal.""" + decrypt = f"transit/decrypt/{_KEK}" + required = {decrypt: frozenset({"update"})} + store = VaultTokenReading( + required=required, problems=("capabilities read failed",), token_ref="same" + ) + secrets = VaultTokenReading( + required={_KV_PATH: frozenset({"read"})}, + admin_paths=(decrypt,), + capabilities={_KV_PATH: ("read",), decrypt: ("update",)}, + other_paths=(decrypt,), + token_ref="same", + ) + _, hop = vault_hops([_STORE, _KV], [store, secrets]) + assert hop.refusing == () + assert f"also holds update on {decrypt} (read on this hop" in hop.detail + # Read on neither hop: said, not dropped. + unread = VaultTokenReading( + required={_KV_PATH: frozenset({"read"})}, + capabilities={_KV_PATH: ("read",)}, + token_ref="same", + ) + _, blind = vault_hops([_STORE, _KV], [store, unread]) + assert blind.refusing == () + assert f"whose read of {decrypt} failed, so the grant there was not judged" in blind.detail def test_one_token_on_both_hops_reports_the_store_grants_once_and_only_warns() -> None: @@ -383,6 +496,63 @@ def meet(consumer: VaultConsumer) -> VaultTokenReading: assert [h.state for h in hops] == [HopState.CLEAN, HopState.CLEAN] +@pytest.mark.parametrize("enforcing", [False, True]) +async def test_a_probe_thread_that_cannot_start_warns_and_never_aborts( + monkeypatch: pytest.MonkeyPatch, enforcing: bool +) -> None: + class NoThread(threading.Thread): + def start(self) -> None: + raise RuntimeError("can't start new thread") + + monkeypatch.setattr(threading, "Thread", NoThread) + store = _AuditStore() + [hop] = await run_vault_privilege_preflight( + _VAULT_SETTINGS, + store, + enforcing=enforcing, + over_grant_accepted=False, + probe=_probe(_FakeVault(caps=_least_caps())), + ) + assert hop.state is HopState.UNOBSERVABLE + assert hop.refusing == () and hop.unexcused == () + assert "could not start a thread (RuntimeError)" in hop.detail + assert store.audits[0][1]["refused"] is False + + +async def test_the_lazy_imports_run_before_any_probe_thread( + monkeypatch: pytest.MonkeyPatch, +) -> None: + events: list[str] = [] + monkeypatch.setattr( + vault_preflight, "preload_vault_probe_imports", lambda: events.append("preload") + ) + + def probe(consumer: VaultConsumer) -> VaultTokenReading: + events.append("probe") + return _reading(_FakeVault(caps=_least_caps())) + + await run_vault_privilege_preflight( + _VAULT_SETTINGS, _AuditStore(), enforcing=True, over_grant_accepted=False, probe=probe + ) + assert events == ["preload", "probe"] + + +def test_the_preload_imports_what_it_can_and_never_raises( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import sys + + from messagefoundry import privilege_probes + + monkeypatch.setattr( + privilege_probes, + "_VAULT_PROBE_IMPORTS", + ("messagefoundry.store.keyprovider_vault", "messagefoundry_no_such_module_4851"), + ) + privilege_probes.preload_vault_probe_imports() + assert "messagefoundry.store.keyprovider_vault" in sys.modules + + def test_the_default_bound_is_finite() -> None: assert 0 < vault_preflight.VAULT_PROBE_TIMEOUT_S < 600 @@ -408,6 +578,33 @@ def test_posture_reports_each_vault_token_the_preflight_read( assert _TOKEN not in resp.text +def test_posture_caps_the_refusing_reasons_and_the_detail_as_the_audit_row_does( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from starlette.testclient import TestClient + + from messagefoundry.config.settings import SecurityEnforcement + + policies = ("default", "x" * 500) + required = {p: frozenset(c) for p, c in _least_caps().items()} + every = vault_admin_paths(required, policies, transit_mount="transit") + caps = _least_caps() | {p: ["update"] for p in every} + _vault_env(monkeypatch, _FakeVault(caps=caps, policies=policies)) + security = SecuritySettings(enforcement=SecurityEnforcement.WARN) + with TestClient(_managed_app(tmp_path, security)) as client: + resp = client.get("/security/posture") + assert resp.status_code == 200, resp.text + [hop] = resp.json()["vault_privilege"]["hops"] + assert hop["refusing_count"] > 20 + assert len(hop["refusing"]) == 20 + assert all(len(r) <= 300 for r in hop["refusing"]) + assert len(hop["detail"]) <= 2000 + # The control: the uncapped text is longer than the caps on both counts. + [judged] = client.app.state.vault_privilege # type: ignore[attr-defined] + assert len(judged.detail) > 2000 + assert any(len(r) > 300 for r in judged.refusing) + + async def test_posture_without_a_preflight_says_not_probed() -> None: from messagefoundry.api.models import SecurityPosture From d061c127d90d20c33c72a0e1356ee7ed56a8fce8 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:53:30 -0600 Subject: [PATCH 08/31] Vault token preflight docs: repair round three BACKLOG #4851. SECURITY.md states the refusing set on a path the store hop calls (only a create, update, patch, delete, sudo or root grant; read and list warn), the warning when a probe that read no token leaves sharing unknown, the posture field's length cap, and a probe thread that cannot start. Verified-by: none --- docs/SECURITY.md | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index d2abb81f0b..a3f1c47edf 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1188,9 +1188,13 @@ The administrative paths it is asked about are at least these: `backup`, and `restore` with and without the key's name; - when the connector-secret token talks to the same Vault address as the store (read as written, so two spellings of one server read as two), every path the store hop calls, and its keys' paths - above. A grant there that creates, rewrites or deletes the store key, or uses it (such as - `update` on `transit/decrypt/`), is in the refusing class; any other grant on the key's own - path warns. A token shared by both hops is judged as the shared-token rule above says instead. + above. On a path the store hop calls, a `create`, `update`, `patch`, `delete`, `sudo` or `root` + grant is in the refusing class: on the key's own path it creates, rewrites or deletes the store + key, and on any other it uses the key (such as `update` on `transit/decrypt/`). Any other + grant there, such as `read` or `list`, warns. A token shared by both hops is judged as the + shared-token rule above says instead. When either hop's probe failed or timed out before it read + its token, whether the two share one is unknown, so such a grant on a path other than the key's + own warns rather than refuses, and the hop says why; shared, it would only warn. On a Transit key's own path a `create`, `update`, `patch`, `delete`, `sudo` or `root` grant creates, rewrites or deletes the key, and is in the refusing class. Any other grant there that the engine @@ -1272,8 +1276,9 @@ at that moment. The over-grants above fall in two classes: - **The refusing class:** the `root` policy, any grant on an administrative path the probe asks about (the list above, which includes a write of the token's own policies and each Transit key's - control, export, backup and restore paths), and a grant that creates, rewrites or deletes a - Transit key. Under the shipped `enforcement = enforce` such a token **refuses to start**. + control, export, backup and restore paths; on a path the store hop calls, only the grants that + list names), a grant that creates, rewrites or deletes a Transit key, and a `create`, `update`, + `patch`, `delete`, `sudo` or `root` grant on a path that uses the store hop's key. Under the shipped `enforcement = enforce` such a token **refuses to start**. The audited opt-out is `[security].allow_over_granted_vault_token = true`: it logs an `AUDIT:` line, marks the `vault_privilege_preflight` audit row `over_grant_accepted`, and is named on `GET /security/posture`. @@ -1293,7 +1298,9 @@ The probes run side by side, and a probe still running after 150 seconds is cut timeout, which only warns. A token whose `auth/token/lookup-self` is denied (a 403, so only a warning) cannot name its own policies, so whether it can rewrite them is not asked; its hop says so. What the preflight read of each token is on `GET /security/posture`, under `vault_privilege`; -a channel-scoped reader is shown each hop's state and counts, not its text. +a channel-scoped reader is shown each hop's state and counts, not its text. There, as in the audit +row, the refusing reasons and the detail are cut to a length cap, and `refusing_count` keeps the +true count. A probe that cannot start its thread reads as not observed and only warns. Under `enforcement = warn` nothing refuses. The probe's limits stay: it asks about exact paths only, so a wildcard grant such as `secret/data/*` would read clean, and a token made with `-no-default-policy` reads From c3252f6754279212a79957fa4423aa669d72060d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 22:08:08 -0600 Subject: [PATCH 09/31] Vault token preflight: repair round three, review repairs BACKLOG #4851. From the code-review round on d061c127d9: - A probe thread that cannot start names RuntimeError unexcused, so it warns under warn and refuses under enforce rather than starting on a token nobody read. - On another hop's path that is not its key's own, every grant but read and list refuses, so a capability string nobody recognises fails closed; VAULT_REFUSING_CLASS says so. - A shared path neither hop read is a part not read (unobservable, partial), not an over-grant. - The preload names more of the probe's lazy imports, and says "at least"; the warning log line uses capped_detail. - Docstrings of vault_hop and vault_hops state the unmatched case, and that a not-shared refusal still turns on the other probe finishing. - The preload test removes its module first, so it can fail. Verified-by: tests --- messagefoundry/privilege_check.py | 66 ++++++++++++-------- messagefoundry/privilege_probes.py | 10 ++- messagefoundry/vault_preflight.py | 14 +++-- tests/test_vault_privilege_preflight_4851.py | 57 +++++++++++++---- 4 files changed, 100 insertions(+), 47 deletions(-) diff --git a/messagefoundry/privilege_check.py b/messagefoundry/privilege_check.py index 8d16a5da17..18f0465dd6 100644 --- a/messagefoundry/privilege_check.py +++ b/messagefoundry/privilege_check.py @@ -274,11 +274,16 @@ def store_hop(report: StorePrivilegeReport, store: StoreSettings) -> HopPrivileg #: (vault BACKLOG #4851); any other extra capability there only warns. _TRANSIT_KEY_CONTROL_CAPS = frozenset({"create", "update", "patch", "delete", "sudo", "root"}) +#: The capabilities on a path another hop calls, other than a Transit key's own path, that only +#: warn: neither calls the path, which Transit serves only to a write. Every other one, a string +#: nobody recognises included, is in the refusing class (vault BACKLOG #4851). +_HARMLESS_ON_ANOTHER_HOPS_PATH = frozenset({"read", "list"}) + #: The refusing class, in the words every refusal and audit line uses, stated once here (ADR 0216). VAULT_REFUSING_CLASS = ( "the root policy, or a grant on an administrative path, on a Transit key's control, export, " - "backup or restore path, or one that creates, rewrites or deletes a Transit key, or a create, " - "update, patch, delete, sudo or root grant on a path that uses another hop's key" + "backup or restore path, or one that creates, rewrites or deletes a Transit key, or any grant " + "but read or list on a path that uses another hop's key" ) @@ -457,9 +462,10 @@ def vault_hop( ``unmatched`` names each other hop whose reading, or this one, carries no token to compare (its probe failed, timed out or found the token unset), so whether it holds this same token is unknown. A grant on a path only such a hop calls, other than on a Transit key's own path, then - warns rather than refuses: had the token been compared and found shared, the grant would be - that hop's own and warn, so the outcome would otherwise turn on whether a probe finished (vault - BACKLOG #4851). + warns rather than refuses, and says why: had the token been compared and found shared, the + grant would be that hop's own and warn, so a refusal would rest on a comparison never made + (vault BACKLOG #4851). Not shared, the same grant refuses once both probes name their tokens, + so whether it refuses still turns on whether the other hop's probe finished. Over-granted: a ``root`` policy; any capability beyond the one a configured path needs; any capability but ``deny`` on an administrative path the engine never calls; or, when ``shared`` @@ -471,11 +477,12 @@ def vault_hop( **Two classes (ADR 0216, owner ruling 2026-10-04).** :data:`VAULT_REFUSING_CLASS` is the REFUSING class, kept in :attr:`HopPrivilege.refusing`: the paths :func:`vault_admin_paths` - names, except a path another hop calls, and :data:`_TRANSIT_KEY_CONTROL_CAPS` on a Transit - key's own path or on a path another hop calls. Everything else is the WARNING class, at least: - read or list on a path another hop calls, a token shared - by two hops, an extra capability on a path the engine calls, and a policy name the probe cannot - tell from root by reading it, which means it cannot judge rather than that it saw root.""" + names, except a path another hop calls; :data:`_TRANSIT_KEY_CONTROL_CAPS` on a Transit key's + own path, this hop's or another's; and any grant but read or list on another path another hop + calls, unless ``unmatched`` leaves sharing unknown. Everything else is the WARNING class, at + least: read or list on a path another hop calls, a token shared by two hops, an extra + capability on a path the engine calls, and a policy name the probe cannot tell from root by + reading it, which means it cannot judge rather than that it saw root.""" grave: list[str] = [] over: list[str] = [] notes: list[str] = [] @@ -524,28 +531,28 @@ def vault_hop( if path in shared_paths or not extra: continue if path in reading.other_paths: - # A path another hop calls: only a create, update, patch, delete, sudo or root grant - # is in the refusing class, as on the hop's own key path above; read, list or any - # other grant warns. On a path that is not the key's own, such a grant is what uses - # the key, as update on transit/decrypt/ does (vault BACKLOG #4851). + # A path another hop calls (vault BACKLOG #4851). On the key's own path, the grants + # that create, rewrite or delete it refuse, as on the hop's own key path above. On any + # other, which uses the key as transit/decrypt/ does, every grant but read and + # list refuses, so a capability string nobody recognises fails closed. is_key = path in reading.transit_keys - control = extra & _TRANSIT_KEY_CONTROL_CAPS + if is_key: + control = extra & _TRANSIT_KEY_CONTROL_CAPS + what = ", which creates, rewrites or deletes another hop's key;" + else: + control = extra - _HARMLESS_ON_ANOTHER_HOPS_PATH + what = "; that path uses another hop's key, and" if control and unmatched and not is_key: - # Shared or not is unknown, and a shared token's grant here would only warn. + # Shared or not is unknown: shared, this grant would be that hop's own and warn. over.append( f"{path} grants {_caps(control)} on a path that uses another hop's key; it " f"warns rather than refuses because whether {', '.join(unmatched)} holds this " "same token is unknown, a token not having been read" ) - elif control and is_key: - grave.append( - f"{path} grants {_caps(control)}, which creates, rewrites or deletes another " - "hop's key; the engine calls it only with that hop's token" - ) elif control: grave.append( - f"{path} grants {_caps(control)}; that path uses another hop's key, and the " - "engine calls it only with that hop's token" + f"{path} grants {_caps(control)}{what} the engine calls it only with that " + "hop's token" ) if extra - control: over.append( @@ -554,6 +561,7 @@ def vault_hop( ) else: grave.append(f"{path} grants {_caps(extra)}; the engine never calls it") + unjudged: list[str] = [] for other_hop, other in (shared or {}).items(): for path in other.required: if path in reading.required: @@ -576,12 +584,13 @@ def vault_hop( f"(read on this hop; {other_hop}'s own read of it failed)" ) elif path not in reading.capabilities: - over.append( + # Nothing was seen there, so it is a part not read, not an over-grant. + unjudged.append( f"the same token serves {other_hop}, whose read of {path} failed, so the " "grant there was not judged on either hop" ) - unread = list(reading.problems) + unread = [*reading.problems, *unjudged] if not reading.looked_up and reading.capabilities: # The policy names come from lookup-self, so without it a write of the token's own # policies was never asked about (vault BACKLOG #4851). Said, so a reading that is @@ -647,8 +656,11 @@ def vault_hops( ) -> list[HopPrivilege]: """Judge every Vault hop, each against the union of grants of every hop that holds its token. - Two hops hold one token when lookup-self named the same token for both (``same_token_as``); a - reading that could not name its token is judged alone.""" + Two hops hold one token when lookup-self named the same token for both (``same_token_as``). A + reading that could not name its token is judged alone, and it also leaves every other hop's + sharing unknown, which turns another hop's refusal for a grant on a path only the unnamed hop + calls, other than a Transit key's own path, into a warning (``unmatched`` in + :func:`vault_hop`).""" hops: list[HopPrivilege] = [] for consumer, reading in zip(consumers, readings, strict=True): others = [ diff --git a/messagefoundry/privilege_probes.py b/messagefoundry/privilege_probes.py index c39ff151c0..f71c52ccd4 100644 --- a/messagefoundry/privilege_probes.py +++ b/messagefoundry/privilege_probes.py @@ -448,15 +448,21 @@ def why(exc: BaseException) -> str: ) -#: Every module :func:`probe_vault` and :func:`read_vault_token` import lazily, and hvac, which the -#: Vault clients they build import. :func:`preload_vault_probe_imports` imports them all. +#: Modules the Vault probe imports lazily, on its own thread: at least those :func:`probe_vault`, +#: :func:`read_vault_token` and their failure classifiers import, and those the Vault clients they +#: build import. :func:`preload_vault_probe_imports` imports them. _VAULT_PROBE_IMPORTS = ( + "messagefoundry.auth.ldap", "messagefoundry.config.secretprovider", "messagefoundry.config.secretprovider_vault", "messagefoundry.config.tls_policy", + "messagefoundry.redaction", "messagefoundry.store.crypto_transit", "messagefoundry.store.keyprovider", "messagefoundry.store.keyprovider_vault", + "messagefoundry.transports.rest", + "messagefoundry.transports.strict_requests", + "requests", "hvac", "hvac.exceptions", ) diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index c4d98d6e71..2d0e3b772c 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -216,8 +216,9 @@ async def _probe_all( loop's shutdown nor the interpreter's exit waits on it.""" loop = asyncio.get_running_loop() # The probes import their providers lazily. Done here, once, before any probe thread starts, - # so the probe threads do not import side by side, and none abandoned at the bound is left - # part way through an import (vault BACKLOG #4851). + # so the probe threads do not import those modules side by side, and one abandoned at the + # bound is not part way through importing one of them (vault BACKLOG #4851). This runs in the + # startup preflight, before any listener binds. preload_vault_probe_imports() async def bounded(consumer: VaultConsumer) -> VaultTokenReading: @@ -254,11 +255,12 @@ def run() -> None: target=run, name=f"vault-privilege-probe-{consumer.hop}", daemon=True ).start() except RuntimeError as exc: # no thread to be had, such as at the thread limit - # A reading with a problem and nothing unexcused, so it warns and never aborts the - # start, under warn or enforce (vault BACKLOG #4851). + # A reading rather than a raise, so warn never aborts the start (vault BACKLOG + # #4851). The token went unread for a reason the ruling does not excuse, so it is + # named unexcused, as any other failure here is, and refuses under enforce. problem = f"the probe could not start a thread ({type(exc).__name__})" log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) - return VaultTokenReading(problems=(problem,)) + return VaultTokenReading(problems=(problem,), unexcused=(type(exc).__name__,)) try: return await asyncio.wait_for(done, timeout=timeout) except TimeoutError: @@ -317,7 +319,7 @@ async def run_vault_privilege_preflight( hop.state.value, enforcing, hop.partial, - scrub_log_argument(hop.detail[:_AUDIT_DETAIL_LIMIT]), + scrub_log_argument(capped_detail(hop)), "; REFUSING to start" if refusing else "", ) if accepted: diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index 9a264fa0c0..fbb6be1980 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -187,6 +187,19 @@ def test_read_or_list_on_another_hops_non_key_path_only_warns(cap: str) -> None: ) +@pytest.mark.parametrize("cap", ["subscribe", "Update", "update​"]) +def test_a_capability_nobody_recognises_on_another_hops_path_refuses(cap: str) -> None: + """Fail closed: a string that is not read or list may call the path that uses the key.""" + decrypt = f"transit/decrypt/{_KEK}" + vault = _FakeVault(caps={_KV_PATH: ["read"], decrypt: [cap]}) + paths = [f"transit/keys/{_KEK}", decrypt] + hop = vault_hop(_KV, _kv_reading(vault, other_required=lambda: paths)) + assert len(hop.refusing) == 1 + assert vault_preflight_outcome(hop, enforcing=True, over_grant_accepted=False) is ( + PreflightOutcome.REFUSE + ) + + def _unread_store_and_secrets(store_token: str | None) -> list[Any]: """The store's reading with ``store_token`` as its token reference, and a secrets reading on another token that can decrypt with the store key.""" @@ -278,6 +291,8 @@ def test_a_shared_token_whose_store_read_failed_reports_the_skipped_grant() -> N _, blind = vault_hops([_STORE, _KV], [store, unread]) assert blind.refusing == () assert f"whose read of {decrypt} failed, so the grant there was not judged" in blind.detail + # Nothing was seen there, so the hop is not observed in part, never over-granted. + assert blind.state is HopState.UNOBSERVABLE and blind.partial def test_one_token_on_both_hops_reports_the_store_grants_once_and_only_warns() -> None: @@ -496,29 +511,44 @@ def meet(consumer: VaultConsumer) -> VaultTokenReading: assert [h.state for h in hops] == [HopState.CLEAN, HopState.CLEAN] -@pytest.mark.parametrize("enforcing", [False, True]) -async def test_a_probe_thread_that_cannot_start_warns_and_never_aborts( - monkeypatch: pytest.MonkeyPatch, enforcing: bool -) -> None: - class NoThread(threading.Thread): - def start(self) -> None: - raise RuntimeError("can't start new thread") +class _NoThread(threading.Thread): + def start(self) -> None: + raise RuntimeError("can't start new thread") + - monkeypatch.setattr(threading, "Thread", NoThread) +async def test_a_probe_thread_that_cannot_start_only_warns_under_warn( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(threading, "Thread", _NoThread) store = _AuditStore() [hop] = await run_vault_privilege_preflight( _VAULT_SETTINGS, store, - enforcing=enforcing, + enforcing=False, over_grant_accepted=False, probe=_probe(_FakeVault(caps=_least_caps())), ) assert hop.state is HopState.UNOBSERVABLE - assert hop.refusing == () and hop.unexcused == () + assert hop.refusing == () and hop.unexcused == ("RuntimeError",) assert "could not start a thread (RuntimeError)" in hop.detail assert store.audits[0][1]["refused"] is False +async def test_a_probe_thread_that_cannot_start_refuses_under_enforce( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A token nobody read is never a pass; the refusal is the preflight's own, not a raise.""" + monkeypatch.setattr(threading, "Thread", _NoThread) + with pytest.raises(VaultPrivilegeError, match="RuntimeError"): + await run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=_probe(_FakeVault(caps=_least_caps())), + ) + + async def test_the_lazy_imports_run_before_any_probe_thread( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -544,13 +574,16 @@ def test_the_preload_imports_what_it_can_and_never_raises( from messagefoundry import privilege_probes + # A module taken out of sys.modules first, so only the preload can put it back. + monkeypatch.delitem(sys.modules, "colorsys", raising=False) monkeypatch.setattr( privilege_probes, "_VAULT_PROBE_IMPORTS", - ("messagefoundry.store.keyprovider_vault", "messagefoundry_no_such_module_4851"), + ("messagefoundry_no_such_module_4851", "colorsys"), ) + assert "colorsys" not in sys.modules privilege_probes.preload_vault_probe_imports() - assert "messagefoundry.store.keyprovider_vault" in sys.modules + assert "colorsys" in sys.modules def test_the_default_bound_is_finite() -> None: From f5ee7438aa6284e1b262482fe2f4d6f9a3035bff Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 22:08:57 -0600 Subject: [PATCH 10/31] Vault token preflight docs: repair round three, review repairs BACKLOG #4851. SECURITY.md: on the store key's own path the control grants refuse; on any other store path every grant but read and list refuses. The refusing-class bullet carries the unknown-token exception, and says an enforcing start is still refused on the store hop's own unexcused failure. The posture paragraph says a cut reason carries no marker, and that a probe thread that cannot start refuses under enforce. Proposed PR title: Vault token preflight: close the refusal gaps, bound the probes, report it in GET /security/posture (BACKLOG #4851) Proposed vault banner: Engine PR closes the open findings of engine PR 2650: the sys and Transit refusal gaps, the connector-secret token asked about the store key, the probes run side by side under a 150 s bound, the result on GET /security/posture, a denied lookup-self said, and the audit and posture text capped. Residuals are named on the PR. Verified-by: none --- docs/SECURITY.md | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index a3f1c47edf..c0b4937fdf 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1188,13 +1188,16 @@ The administrative paths it is asked about are at least these: `backup`, and `restore` with and without the key's name; - when the connector-secret token talks to the same Vault address as the store (read as written, so two spellings of one server read as two), every path the store hop calls, and its keys' paths - above. On a path the store hop calls, a `create`, `update`, `patch`, `delete`, `sudo` or `root` - grant is in the refusing class: on the key's own path it creates, rewrites or deletes the store - key, and on any other it uses the key (such as `update` on `transit/decrypt/`). Any other - grant there, such as `read` or `list`, warns. A token shared by both hops is judged as the - shared-token rule above says instead. When either hop's probe failed or timed out before it read - its token, whether the two share one is unknown, so such a grant on a path other than the key's - own warns rather than refuses, and the hop says why; shared, it would only warn. + above. On the store key's own path, a `create`, `update`, `patch`, `delete`, `sudo` or `root` + grant creates, rewrites or deletes the key and is in the refusing class, and any other grant + warns. On any other path the store hop calls, which uses the key (such as `update` on + `transit/decrypt/`), every grant but `read` and `list` is in the refusing class, and those + two warn. A token shared by both hops is judged as the shared-token rule above says instead. + When either hop's probe failed, timed out or found its token unset before it read the token, + whether the two share one is unknown, so a refusing-class grant on a path the store hop calls, + other than the key's own, only warns, and the hop says why: shared, it would only warn. That + start is still refused under `enforce` when the store hop's own failure is not a network + failure, a timeout or a 403. On a Transit key's own path a `create`, `update`, `patch`, `delete`, `sudo` or `root` grant creates, rewrites or deletes the key, and is in the refusing class. Any other grant there that the engine @@ -1277,8 +1280,10 @@ at that moment. The over-grants above fall in two classes: - **The refusing class:** the `root` policy, any grant on an administrative path the probe asks about (the list above, which includes a write of the token's own policies and each Transit key's control, export, backup and restore paths; on a path the store hop calls, only the grants that - list names), a grant that creates, rewrites or deletes a Transit key, and a `create`, `update`, - `patch`, `delete`, `sudo` or `root` grant on a path that uses the store hop's key. Under the shipped `enforcement = enforce` such a token **refuses to start**. + list names), a grant that creates, rewrites or deletes a Transit key, and any grant but `read` or + `list` on a path that uses the store hop's key. That last grant only warns when either hop's + probe could not read its token, as the list above says. Under the shipped + `enforcement = enforce` such a token **refuses to start**. The audited opt-out is `[security].allow_over_granted_vault_token = true`: it logs an `AUDIT:` line, marks the `vault_privilege_preflight` audit row `over_grant_accepted`, and is named on `GET /security/posture`. @@ -1300,7 +1305,9 @@ warning) cannot name its own policies, so whether it can rewrite them is not ask so. What the preflight read of each token is on `GET /security/posture`, under `vault_privilege`; a channel-scoped reader is shown each hop's state and counts, not its text. There, as in the audit row, the refusing reasons and the detail are cut to a length cap, and `refusing_count` keeps the -true count. A probe that cannot start its thread reads as not observed and only warns. +true count, but nothing marks a reason or detail that was cut. A probe that cannot start its +thread reads as not observed: it warns under `warn` and, being no network failure, timeout or 403, +refuses under `enforce`. Under `enforcement = warn` nothing refuses. The probe's limits stay: it asks about exact paths only, so a wildcard grant such as `secret/data/*` would read clean, and a token made with `-no-default-policy` reads From 81de0ce349bc7c2d373832e25e4a1a19f89f5f0c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 22:22:28 -0600 Subject: [PATCH 11/31] Vault token preflight: repair round three, second review repairs BACKLOG #4851. From the code-review round on f5ee7438aa: - A grant downgraded because sharing is unknown also marks the hop partial, so check-privileges says its verdict covers only what was read rather than a bare "warns only". - The vault_hop docstring names the cases that drop the token reference and that the downgrade is per hop, not per path. - The thread-start tests patch only vault_preflight's threading, and the invisible-character capability case is built with chr(), not a raw character in the source. Verified-by: tests --- messagefoundry/privilege_check.py | 25 +++++++++++++++----- tests/test_vault_privilege_preflight_4851.py | 11 ++++++--- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/messagefoundry/privilege_check.py b/messagefoundry/privilege_check.py index 18f0465dd6..dc22c89c66 100644 --- a/messagefoundry/privilege_check.py +++ b/messagefoundry/privilege_check.py @@ -459,13 +459,17 @@ def vault_hop( ) -> HopPrivilege: """Judge one token's self-reading against what the engine calls with it. - ``unmatched`` names each other hop whose reading, or this one, carries no token to compare - (its probe failed, timed out or found the token unset), so whether it holds this same token is - unknown. A grant on a path only such a hop calls, other than on a Transit key's own path, then - warns rather than refuses, and says why: had the token been compared and found shared, the - grant would be that hop's own and warn, so a refusal would rest on a comparison never made + ``unmatched`` names each other hop whose reading, or this one, carries no token reference (at + least: the token was unset, the client could not be built, the probe hit the bound, raised + past :func:`~messagefoundry.privilege_probes.read_vault_token` or found no thread), so whether + it holds this same token is unknown. Most failures inside the probe keep the reference. A grant + on a path another hop calls, other than on a Transit key's own path, then warns rather than + refuses, says why, and marks the hop ``partial``: had the token been compared and found shared, + the grant would be that hop's own and warn, so a refusal would rest on a comparison never made (vault BACKLOG #4851). Not shared, the same grant refuses once both probes name their tokens, - so whether it refuses still turns on whether the other hop's probe finished. + so whether it refuses still turns on whether the other hop's probe finished. The probe does not + record which hop calls which path, so with more than two hops any unmatched hop downgrades + every such path. Over-granted: a ``root`` policy; any capability beyond the one a configured path needs; any capability but ``deny`` on an administrative path the engine never calls; or, when ``shared`` @@ -526,6 +530,7 @@ def vault_hop( # A path a hop holding this same token calls is that hop's grant: the shared-token loop below # reports it, in the warning class the owner ruling puts a shared token in. shared_paths = {p for other in (shared or {}).values() for p in other.required} + downgraded = False for path in reading.admin_paths: extra = set(reading.capabilities.get(path, ())) - {"deny"} if path in shared_paths or not extra: @@ -544,6 +549,7 @@ def vault_hop( what = "; that path uses another hop's key, and" if control and unmatched and not is_key: # Shared or not is unknown: shared, this grant would be that hop's own and warn. + downgraded = True over.append( f"{path} grants {_caps(control)} on a path that uses another hop's key; it " f"warns rather than refuses because whether {', '.join(unmatched)} holds this " @@ -591,6 +597,13 @@ def vault_hop( ) unread = [*reading.problems, *unjudged] + if downgraded: + # Said as a part not read too, so the hop is partial and a verdict says it covers only + # what was read: the warning above may be a refusal once the other token is named. + unread.append( + f"whether {', '.join(unmatched)} holds this same token is unknown, so a grant on a " + "path another hop calls was judged as a warning only" + ) if not reading.looked_up and reading.capabilities: # The policy names come from lookup-self, so without it a write of the token's own # policies was never asked about (vault BACKLOG #4851). Said, so a reading that is diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index fbb6be1980..8389a14913 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -19,6 +19,7 @@ import threading import time from pathlib import Path +from types import SimpleNamespace from typing import Any import pytest @@ -187,7 +188,7 @@ def test_read_or_list_on_another_hops_non_key_path_only_warns(cap: str) -> None: ) -@pytest.mark.parametrize("cap", ["subscribe", "Update", "update​"]) +@pytest.mark.parametrize("cap", ["subscribe", "Update", "update" + chr(0x200B)]) def test_a_capability_nobody_recognises_on_another_hops_path_refuses(cap: str) -> None: """Fail closed: a string that is not read or list may call the path that uses the key.""" decrypt = f"transit/decrypt/{_KEK}" @@ -216,6 +217,8 @@ def test_a_store_probe_with_no_token_leaves_the_decrypt_grant_warning() -> None: _, secrets = _unread_store_and_secrets(None) assert secrets.refusing == () assert "whether vault.store holds this same token is unknown" in secrets.detail + # Partial, so a verdict on it says it covers only what was read. + assert secrets.partial assert vault_preflight_outcome(secrets, enforcing=True, over_grant_accepted=False) is ( PreflightOutcome.WARN ) @@ -519,7 +522,8 @@ def start(self) -> None: async def test_a_probe_thread_that_cannot_start_only_warns_under_warn( monkeypatch: pytest.MonkeyPatch, ) -> None: - monkeypatch.setattr(threading, "Thread", _NoThread) + # Only the module under test loses its threads; asyncio and the rest keep theirs. + monkeypatch.setattr(vault_preflight, "threading", SimpleNamespace(Thread=_NoThread)) store = _AuditStore() [hop] = await run_vault_privilege_preflight( _VAULT_SETTINGS, @@ -538,7 +542,8 @@ async def test_a_probe_thread_that_cannot_start_refuses_under_enforce( monkeypatch: pytest.MonkeyPatch, ) -> None: """A token nobody read is never a pass; the refusal is the preflight's own, not a raise.""" - monkeypatch.setattr(threading, "Thread", _NoThread) + # Only the module under test loses its threads; asyncio and the rest keep theirs. + monkeypatch.setattr(vault_preflight, "threading", SimpleNamespace(Thread=_NoThread)) with pytest.raises(VaultPrivilegeError, match="RuntimeError"): await run_vault_privilege_preflight( _VAULT_SETTINGS, From fd851129514709ccca272b6848b55df4a961103b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 22:23:16 -0600 Subject: [PATCH 12/31] Vault token preflight docs: repair round three, second review repairs BACKLOG #4851. SECURITY.md names the cases that leave a reading with no token reference, says the downgraded hop is marked partial, and points the store key's own path at the one Transit-key rule rather than restating it. SECURITY-LOOSENING.md lists the new refusing-class clause. Proposed PR title: Vault token preflight: close the refusal gaps, bound the probes, report it in GET /security/posture (BACKLOG #4851) Proposed vault banner: Engine PR closes the open findings of engine PR 2650: the sys and Transit refusal gaps, the connector-secret token asked about the store key, the probes run side by side under a 150 s bound, the result on GET /security/posture, a denied lookup-self said, and the audit and posture text capped. Residuals are named on the PR. Verified-by: none --- docs/SECURITY-LOOSENING.md | 5 +++-- docs/SECURITY.md | 17 +++++++++-------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index 0b8c2d524f..cf2a0307f9 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -2294,8 +2294,9 @@ count is above `0` (vault BACKLOG #2613). - **What you lose:** the refusal under `enforce` that a Vault token the engine uses earns when the startup probe finds it holding a grant in the refusing class, which [SECURITY.md](SECURITY.md#each-backend-hops-least-privilege-the-engine-probes-the-store-vault-and-ldap) lists: at least the root policy, any - grant on an administrative path, a Transit key's control, export, backup or restore path, or a - grant that creates, rewrites or deletes a Transit key. On an administrative, control, export, + grant on an administrative path, a Transit key's control, export, backup or restore path, a + grant that creates, rewrites or deletes a Transit key, or any grant but `read` or `list` on a + path that uses another hop's key. On an administrative, control, export, backup or restore path any grant but `deny` counts, a read included. A write there lets the token widen its own reach, or take the store key out of Vault, and any code path that reaches the token inherits that. - **When acceptable:** on a lab box run with a Vault dev-server root token. Not as a steady state. diff --git a/docs/SECURITY.md b/docs/SECURITY.md index c0b4937fdf..dea4cdd1a4 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1188,16 +1188,17 @@ The administrative paths it is asked about are at least these: `backup`, and `restore` with and without the key's name; - when the connector-secret token talks to the same Vault address as the store (read as written, so two spellings of one server read as two), every path the store hop calls, and its keys' paths - above. On the store key's own path, a `create`, `update`, `patch`, `delete`, `sudo` or `root` - grant creates, rewrites or deletes the key and is in the refusing class, and any other grant - warns. On any other path the store hop calls, which uses the key (such as `update` on + above. The store key's own path is judged by the Transit-key rule in the next paragraph. On any + other path the store hop calls, which uses the key (such as `update` on `transit/decrypt/`), every grant but `read` and `list` is in the refusing class, and those two warn. A token shared by both hops is judged as the shared-token rule above says instead. - When either hop's probe failed, timed out or found its token unset before it read the token, - whether the two share one is unknown, so a refusing-class grant on a path the store hop calls, - other than the key's own, only warns, and the hop says why: shared, it would only warn. That - start is still refused under `enforce` when the store hop's own failure is not a network - failure, a timeout or a 403. + When either hop's reading names no token, whether the two share one is unknown. At least these + leave it unnamed: an unset token, a client that could not be built, a probe cut off at the bound + below, and a probe that raised or could not start its thread; most other probe failures keep + it. Then a refusing-class grant on a path the store hop calls, other than the key's own, only + warns, and the hop says why and is marked partial: shared, it would only warn. Under `enforce` + the start is still refused when the store hop's own failure is not one the excused list below + names (a network failure, a timeout or a 403). On a Transit key's own path a `create`, `update`, `patch`, `delete`, `sudo` or `root` grant creates, rewrites or deletes the key, and is in the refusing class. Any other grant there that the engine From b598d9a1a7ceab896dd49b80772e4dcc7d354295 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 23:51:32 -0600 Subject: [PATCH 13/31] PHI coverage: bind VaultPrivilegeHopView.detail to no store column (BACKLOG #4851) The colliding-field gate failed in test shard 2 because the new VaultPrivilegeHopView.detail field shares its name with the classified detail columns. It projects none of them: app.py builds it from the in-memory HopPrivilege list the serve lifespan stores on app.state.vault_privilege, so the posture route reads no store row. The string names Vault policies, paths and capabilities, is cut by vault_preflight.capped_detail, and is withheld for a channel-scoped reader. Its persisted twin is audit_log.detail (PL-4), as for StorePrivilegeView.detail, so the entry is None with that reason. Verified-by: tests --- tests/test_no_store_phi_coverage.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/test_no_store_phi_coverage.py b/tests/test_no_store_phi_coverage.py index cce4c70b34..6b27d5c0ff 100644 --- a/tests/test_no_store_phi_coverage.py +++ b/tests/test_no_store_phi_coverage.py @@ -168,6 +168,12 @@ def _classified_columns() -> dict[str, str]: # through redact_log_line and cut to 300 characters. Its PERSISTED twin is audit_log.detail # (PL-4), not either of the PL-2 `detail` columns this field NAME collides with. ("StorePrivilegeView", "detail"): None, + # The Vault privilege preflight's per-hop judgment (BACKLOG #4851). app.py copies it from the + # in-memory HopPrivilege list the serve lifespan stashed on app.state.vault_privilege, so the + # route reads no store row. The string names Vault policies, paths and capabilities, cut by + # vault_preflight.capped_detail, and is withheld for a channel-scoped reader. Its PERSISTED twin + # is audit_log.detail (PL-4), not either of the PL-2 `detail` columns this field NAME collides with. + ("VaultPrivilegeHopView", "detail"): None, # The static-credential inventory (BACKLOG #1182). app.py builds it from the loaded graph and # the service settings, so the route reads no store row. None rates that provenance only. The # string is also secret-free by construction, which is a separate claim with its own tests From da8b5e19fe0811017f370bc9501dd208bc889e87 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 23:52:39 -0600 Subject: [PATCH 14/31] ADR 0216 Amendment B: the cross-hop refusal and the probe bound (BACKLOG #4851) States, as a deliberate widening of the owner's 2026-10-04 line "Everything else warns", the two changes this PR makes: a grant on a path another hop calls (reading.other_paths) refuses a start under enforce, any grant but read or list on a non-key path and the key-control grants on a key path; and each Vault probe is bounded at 150 seconds, a probe ended by the bound reading as a timeout, which warns. Cites the Lander's delegated decision d20261202T053010258-eb19bb and names the undo. Verified-by: none --- ...t-under-enforce-with-an-audited-opt-out.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md index b3d3307663..906c5ee66d 100644 --- a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md +++ b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md @@ -178,3 +178,28 @@ it the notifier, or the logging sink when no notifier is configured. audit-row sentence read "records every process's own reading", corrected the same day. - **Best effort.** A sink that raises is logged and never masks the finding, the audit row or the refusal. + +## Amendment B (2026-12-01): a grant on another hop's path refuses, and each probe is bounded + +Vault BACKLOG #4851. Status unchanged: Proposed. Two changes go past the owner's 2026-10-04 line +*"Everything else warns, alerts and audits."* Both are deliberate. The Lander decided them under +the owner's delegation of 2026-12-01 (US Central), record d20261202T053010258-eb19bb, after an +adversarial review; that is a delegated decision, not an owner ruling. + +- **A cross-hop grant refuses.** When a token's reading (`privilege_probes.vault_hop`) finds a + grant on a path in `reading.other_paths`, a path another hop calls with its own token, the + engine judges it as part of `privilege_check.VAULT_REFUSING_CLASS`. On a Transit key's own path, + the grants that create, rewrite or delete the key refuse. On any other such path, any grant but + read or list refuses, so a capability string nobody recognises fails closed. The case the + ruling's words put in the warning class is a connector-secret token that holds, for example, + update on the store hop's Transit decrypt path. It now refuses a start under `enforce`, unless + `[security].allow_over_granted_vault_token` accepts it (audited), as the gravest grants do. It + still warns, never refuses, in at least two cases: read or list on such a path, and a grant on + a non-key path while whether the other hop holds this same token is unknown, because that hop's + token was not read. +- **Each probe is bounded at 150 seconds** (`vault_preflight.VAULT_PROBE_TIMEOUT_S`). Before, the + preflight waited on a probe with no bound of its own. A probe still running at the bound reads + as a timeout, which warns under the 2026-10-04 ruling; it does not refuse. + +Undo for the first: judge the non-key cross-hop case as a warning again. That changes one case and +nothing else in the refusing class. From 965f0e6d101d5a8ccda336660ae06c1aa5db9f83 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 00:11:59 -0600 Subject: [PATCH 15/31] PHI coverage: cite the vault ledger for the Vault posture entry (BACKLOG #4851) Review round 1: the register comment cited a bare BACKLOG #4851, which reads against the engine's stub ledger; the item is vault BACKLOG #4851, as app.py and models.py cite it. Verified-by: tests --- tests/test_no_store_phi_coverage.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_no_store_phi_coverage.py b/tests/test_no_store_phi_coverage.py index 6b27d5c0ff..817ad4d335 100644 --- a/tests/test_no_store_phi_coverage.py +++ b/tests/test_no_store_phi_coverage.py @@ -168,7 +168,7 @@ def _classified_columns() -> dict[str, str]: # through redact_log_line and cut to 300 characters. Its PERSISTED twin is audit_log.detail # (PL-4), not either of the PL-2 `detail` columns this field NAME collides with. ("StorePrivilegeView", "detail"): None, - # The Vault privilege preflight's per-hop judgment (BACKLOG #4851). app.py copies it from the + # The Vault privilege preflight's per-hop judgment (vault BACKLOG #4851). app.py copies it from the # in-memory HopPrivilege list the serve lifespan stashed on app.state.vault_privilege, so the # route reads no store row. The string names Vault policies, paths and capabilities, cut by # vault_preflight.capped_detail, and is withheld for a channel-scoped reader. Its PERSISTED twin From 689a6598d65d4e06cbd21672fbf71805f9030743 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 00:12:47 -0600 Subject: [PATCH 16/31] ADR 0216 Amendment B: state the preconditions and the bound's real loosening (BACKLOG #4851) Review round 1 on the amendment, checked against privilege_check.py, privilege_probes.py and vault_preflight.py: - vault_hop is privilege_check.vault_hop, not privilege_probes; the judgment lands in the hop's refusing list. - The cross-hop check runs only when the two Vault addresses match as written, and only asks the connector-secret token about the store's paths. - Unknown sharing is any reading with no token reference, which includes a store probe ended by the bound, so a slow store probe downgrades the refusal to a warning. - Only serve's wait is bounded; the thread runs on, and check-privileges is unbounded. A probe ended by the bound warns whatever made it hang, which is the second widening of the ruling, now said as such. - The refusing set's other additions in this PR are named. - The undo creates a new warning rather than restoring an earlier state. - docs/adr/README.md's 0216 row records Amendment B. Verified-by: none --- ...t-under-enforce-with-an-audited-opt-out.md | 60 ++++++++++++------- docs/adr/README.md | 2 +- 2 files changed, 41 insertions(+), 21 deletions(-) diff --git a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md index 906c5ee66d..6080334a93 100644 --- a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md +++ b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md @@ -183,23 +183,43 @@ it the notifier, or the logging sink when no notifier is configured. Vault BACKLOG #4851. Status unchanged: Proposed. Two changes go past the owner's 2026-10-04 line *"Everything else warns, alerts and audits."* Both are deliberate. The Lander decided them under -the owner's delegation of 2026-12-01 (US Central), record d20261202T053010258-eb19bb, after an -adversarial review; that is a delegated decision, not an owner ruling. - -- **A cross-hop grant refuses.** When a token's reading (`privilege_probes.vault_hop`) finds a - grant on a path in `reading.other_paths`, a path another hop calls with its own token, the - engine judges it as part of `privilege_check.VAULT_REFUSING_CLASS`. On a Transit key's own path, - the grants that create, rewrite or delete the key refuse. On any other such path, any grant but - read or list refuses, so a capability string nobody recognises fails closed. The case the - ruling's words put in the warning class is a connector-secret token that holds, for example, - update on the store hop's Transit decrypt path. It now refuses a start under `enforce`, unless - `[security].allow_over_granted_vault_token` accepts it (audited), as the gravest grants do. It - still warns, never refuses, in at least two cases: read or list on such a path, and a grant on - a non-key path while whether the other hop holds this same token is unknown, because that hop's - token was not read. -- **Each probe is bounded at 150 seconds** (`vault_preflight.VAULT_PROBE_TIMEOUT_S`). Before, the - preflight waited on a probe with no bound of its own. A probe still running at the bound reads - as a timeout, which warns under the 2026-10-04 ruling; it does not refuse. - -Undo for the first: judge the non-key cross-hop case as a warning again. That changes one case and -nothing else in the refusing class. +the owner's delegation of 2026-12-01 (US Central), after an adversarial review; the question asked +and the owner's answer are in decision record d20261202T053010258-eb19bb. That is a delegated +decision, not an owner ruling. + +- **A cross-hop grant refuses.** The connector-secret token is now also asked about the paths the + store hop calls, and their keys' control and export paths (`privilege_probes._store_paths`), + when the two hops' Vault addresses match as written (`privilege_probes._same_vault`: nothing is + resolved, so two spellings of one server read as two and those paths go unasked). The store + token is not asked about the connector-secret paths. A grant the reading finds on such a path + (`reading.other_paths`) is judged by `privilege_check.vault_hop` into the hop's refusing list. + On a Transit key's own path, the grants that create, rewrite or delete the key refuse. On any + other such path, any grant but read or list refuses, so a capability string nobody recognises + fails closed. The case the ruling's words put in the warning class is a connector-secret token + that holds, for example, update on the store hop's Transit decrypt path. It now refuses a start + under `enforce`, unless `[security].allow_over_granted_vault_token` accepts it (audited), as the + gravest grants do. It still warns, never refuses, in at least two cases: read or list on such a + path, and a grant on a non-key path while whether the other hop holds this same token is + unknown. Unknown means either reading carries no token reference + (`privilege_check.vault_hops`). That includes a store probe ended by the bound below, whose + token may well have been read, so under `enforce` a slow store probe turns this refusal into a + warning and the start goes ahead. +- **Serve's wait on each probe is bounded at 150 seconds** (`vault_preflight.VAULT_PROBE_TIMEOUT_S`). + Before, `serve` waited on a probe with no bound of its own. Only the wait is bounded: the probe's + thread is not stopped and may go on calling Vault with the token after the start, and + `check-privileges` runs the probes with no bound, so the two can disagree on a slow Vault. A + probe still running at the bound reads as a timeout, which warns and does not refuse. That + outcome is the second widening: it holds whatever made the probe hang, not only a network + timeout. A probe stuck for another reason, such as a code defect or a hung read of the token + file, now warns and lets an enforcing start go ahead, where the Decision above refuses any + failure that is not a network failure, a timeout or a 403. + +The same PR also added to the refusing set this ADR's Decision lists, at least the grants that +create, rewrite or delete the hop's own Transit key, more Transit key administration paths and more +administrative paths. Those were judged to fit the ruling's *"Root policy, admin paths and Transit +key control"*; `privilege_check.VAULT_REFUSING_CLASS` states the class once. + +Undo for the first: judge the non-key cross-hop grant as a warning. Before this amendment the +connector-secret token was never asked about the store hop's paths, so the undo makes a new warning +rather than restoring an earlier state, and leaves the unknown-sharing downgrade with nothing to +soften. diff --git a/docs/adr/README.md b/docs/adr/README.md index faa669c8d9..6b3d278def 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -238,7 +238,7 @@ what is withheld and what you can request. | [0213](0213-seal-the-secret-rotation-fingerprint-as-a-store-cipher-cell.md) | **Seal the secret-rotation fingerprint as a store-cipher cell** (vault BACKLOG #3472, #3247 item 1) -- each non-DEK `secret_rotation_meta.fingerprint` becomes a store-cipher cell holding a per-row random HMAC key, the value's MAC and the row's class id, AAD-bound to its row and stored behind the `sealed-hmac-sha256-32` tag. `rotate-key`'s `reencrypt_to_active` re-seals it on all three backends, so a store key rotation no longer moves every fingerprint and no start needs the retired key. A cell the engine cannot read, and every pre-#3472 row, keeps its dates: an old row never resets a clock. `vault_transit` stays off (#3473). Supersedes the #2242 re-key rule and removes the DEK-derived fingerprint key. Rejected: carrying retired fingerprint keys forward (A, the fallback), a random per-store key, recomputing in `rotate-key`, a non-rotating derivation | **Accepted (2026-10-26)** -- owner ruling 2026-10-26, in session (batch 343 Manager), option "S: seal as cipher cell"; built with the change | | [0214](0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md) | **A secrets directory and one accessor for the engine's secret-class settings** (vault BACKLOG #2595, step 3, slice A of four) -- one list of the secret-class setting names in `engine_secrets.py`, which the NSSM reading takes its lists from, and one module every moved reader reads through: the file named for the setting in the directory `MEFOR_SECRETS_DIRECTORY` names, else the environment variable, so the directory wins. Moved: both Vault tokens, the `env()` values, the settings-borne secrets including the database password, and the rotation fingerprint. The reader checks the directory's own access list, then each file's, with the key-file check, and refuses at every enforcement setting a broad one, a link (on every platform since its 2026-11-13 amendment; on Windows only before it), a file named for no setting, an empty, non-UTF-8 or oversized file, and any file named for the store key, which stays in its DPAPI key file. Plain files: DPAPI wrapping waits on a spike. Slice A refused nothing that started before it. Rejected: one DPAPI file for every secret, purging the environment, a settings-file location | **Proposed (2026-10-27)** -- built as slice A; merging records it as Proposed and accepts nothing. Slice C (the installer creates the directory; the location stays operator-named) and slice D (the unbuilt provider names removed) built 2026-11-05, per its Amendments. Half of slice B (the NSSM reading refuses every secret-class name in the service's own lists) built 2026-11-11. Amended 2026-11-13: on POSIX the key-file check also judges the owner of the directory or file and the directory that holds it (`docs/CONFIGURATION.md` states the rule), and on Windows the folder that holds the directory is read too, read where the path resolves to since 2026-11-17; neither is a complete check of the directory's surroundings. Amended 2026-11-22: the host key provider's files may take a custody directory of their own. The rest of slice B (refusing such a secret found in the environment elsewhere, owner ruling 2026-10-01) is built for these names in part, 2026-11-24, per the 2026-11-11 amendment's update, which states what it covers. Open: at least whatever of slice B that update leaves, and whether a Windows file is also DPAPI-wrapped. Step 3 is not closed. Severity conditional per CLAUDE.md section 0 | | [0215](0215-the-web-console-calls-the-json-routes-in-process-through-the-asgi-app-so-one-gate-family-authorizes-both-planes.md) | **The web console calls the JSON routes in-process through the ASGI app, so one gate family authorizes both planes** (vault BACKLOG #2603, research step) -- the console stops calling engine handlers through `CoreHandlers` and `AdminHandlers` and sends each a bearer sub-request through the engine's own app, so every JSON gate runs; `get_engine`, `get_gate` and the console's non-sign-in `AuthService` reads go too. The sub-request's scope copies exactly the browser request's `client`, `server`, `scheme`, `http_version` and `root_path` (never `state`, which carries the mTLS peer certificate, and no browser header but a passed body's `Content-Type`), and one in-process `messagefoundry.console` scope extension carries the `/ui` path and a poll flag: no idle-clock touch for a timer-driven poll, every grant row written as a bearer request writes it (volume cut by composite poll routes, not by deduplication), no PHI-budget exemption (a two-resource page costs two, as a bearer client pays). Every console route outside the public and confinement sets makes at least one sub-request (gate-only `GET /auth/check/` routes, one `require(p)` each, for pages with no data); the JSON writes the console calls that are unpaced today gain admin-write pacing. `require_ui` shrinks to a read-only session check, same-origin on writes, and one refusal-to-browser-answer table. Adds an async client and a response-streaming in-process transport to `apiclient` (stock httpx `ASGITransport` sets a loopback client and buffers response bodies), and a policy class per JSON route. Rejected: the proof-object design (the dual-control executors, convergence and DR re-apply run with no request), a stronger parity guard, stock `ASGITransport`, router-only dispatch, grant-row deduplication. Amends ADR 0065 and ADR 0088 | **Accepted (2026-10-30)** -- owner ruling given in session to the batch 459 Manager through AskUserQuestion, "Accept (Recommended)"; the seven build slices go ahead in the build order, slice 7 at any point. The owner also answered two of its open questions, on grant rows for polls and on the grant row's form; the ADR's *To resolve on acceptance* records both. Open: the extra session reads per sub-request, owned by slice 5. ADR 0065 and ADR 0088 carry an *Amended by ADR 0215* note. Amended 2026-11-24 by an appended section (slice 2a: a check route writes the grant row of an audited permission), on the Lander's ruling d20261124T135809520-03bdbe under the owner's delegation of 2026-11-24. No code yet. Severity conditional per CLAUDE.md section 0. *Superseded cell text, kept as a record: "**Proposed (2026-10-29)** -- doc-only research step; no code. Seven build slices named in the ADR. Acceptance is the owner's; four questions open. Severity conditional per CLAUDE.md section 0".* | -| [0216](0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md) | **The gravest Vault token grants refuse start under enforce, with an audited opt-out** (vault BACKLOG #2903, slice A; ASVS 13.2.2) -- owner ruling 2026-10-04 (17:06:09Z UTC). `serve` probes each Vault token it uses at every start, with the `check-privileges` probe and a client from the provider's own constructor, after the store preflight and before any listener binds. The root policy, any grant on an administrative path (including a write of the token's own policies) and a Transit key's `config`, `rotate`, `export` or `backup` refuse start under `[security].enforcement = enforce`; `[security].allow_over_granted_vault_token` is the audited opt-out (an `AUDIT:` line, `over_grant_accepted` on the `vault_privilege_preflight` audit row, a `security_loosenings()` entry). Every other over-grant, and a probe stopped by a network failure, a timeout or a 403, warn and audit; a probe that failed for any other reason, such as a code defect, refuses under `enforce`. `vault_preflight_outcome` states the decision once for `serve` and `check-privileges`. The third recorded exception to "a new refusal fires only on a new opt-in". Rejected: refusing on any over-grant, reusing the store opt-out | **Proposed (2026-10-30)** -- built as slice A; merging records it as Proposed and accepts nothing. Open: the alert with its auto-resolving inverse (slice B). Severity conditional per CLAUDE.md section 0 | +| [0216](0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md) | **The gravest Vault token grants refuse start under enforce, with an audited opt-out** (vault BACKLOG #2903, slice A; ASVS 13.2.2) -- owner ruling 2026-10-04 (17:06:09Z UTC). `serve` probes each Vault token it uses at every start, with the `check-privileges` probe and a client from the provider's own constructor, after the store preflight and before any listener binds. The root policy, any grant on an administrative path (including a write of the token's own policies) and a Transit key's `config`, `rotate`, `export` or `backup` refuse start under `[security].enforcement = enforce`; `[security].allow_over_granted_vault_token` is the audited opt-out (an `AUDIT:` line, `over_grant_accepted` on the `vault_privilege_preflight` audit row, a `security_loosenings()` entry). Every other over-grant, and a probe stopped by a network failure, a timeout or a 403, warn and audit; a probe that failed for any other reason, such as a code defect, refuses under `enforce`. `vault_preflight_outcome` states the decision once for `serve` and `check-privileges`. The third recorded exception to "a new refusal fires only on a new opt-in". Rejected: refusing on any over-grant, reusing the store opt-out | **Proposed (2026-10-30)** -- built as slice A; merging records it as Proposed and accepts nothing. Open: the alert with its auto-resolving inverse (slice B). Amendment B (2026-12-01, vault BACKLOG #4851): a connector-secret token's grant beyond read or list on a path the store hop calls refuses too, and `serve` waits at most 150 s on each probe, a probe ended there warning whatever made it hang; both widen the ruling's "Everything else warns", by a Lander decision under the owner's delegation. Severity conditional per CLAUDE.md section 0 | | [0217](0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md) | **An unverifiable Transit row seal is denied like a failed one, and the AD reconciler ends sessions rather than holding** (vault BACKLOG #4739, design for #2592's `vault_transit` limb; engine PR 2565 is the parked reference) -- four answers to a seal check: holds, forged (`valid: false` or a malformed seal), unverifiable (a `verify` HTTP 400 while the fixed-input probe works, whatever version it names) and outage. Unverifiable denies the row as forged does (never tombstoning or raw-deleting one on its own), under `integrity.authority_seal_unverifiable` and a capped per-row subject, because a database writer can plant an unheld key version. Transit is sent a fixed-length SHA-256 of the seal input, so no row can force an outage by size. AD sign-in and the certificate leg refuse on an unverifiable map; on a map that does not hold, forged included, the reconciler writes no role row and ends the sessions of accounts whose groups moved since a new sealed `users.directory_groups_digest`, under the unchanged mass-revoke brake, after first trying `main`'s own set; every unverifiable or forged map pages each pass under its own uncapped subject. Write refusals raise `RowSealError` or its sibling `RowSealUnverifiableError` under a catch census, and every catch site audits; a session end never rolls back. Seal-state and outage-refused sign-ins write their own actions and do not count toward the sign-in burst. An owner-rulings list heads the ADR; residuals named: no cross-store binding until #3411, no rollback detection until #2592 step 7, 60 s of cached trust after a version retirement. Rejected: a lagging-node outage case, holding reconcile diffs, ending the sessions outside the brake, re-judging offboarding on a tripped pass, applying demotions from an empty map, re-sealing a map nobody verified | **Accepted (2026-11-06)** by owner ruling on every entry -- design only, no code yet; every answer is a control decision. Severity conditional per CLAUDE.md section 0 | ## Retired allocations — numbers taken but never authored From bee1ebed882e544eafd312129f3a859344c5ff27 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 00:28:47 -0600 Subject: [PATCH 17/31] ADR 0216 Amendment B: one-way check, tighten versus loosen, index row (BACKLOG #4851) Review round 2 on the amendment and the 0216 index row: - The heading and body say the check is one way: only the connector-secret token is asked about the store's paths, and only when _same_vault holds, which casefolds scheme and host and drops a trailing slash rather than comparing as written. - The key control and export paths come from vault_admin_paths, not _store_paths. - The shared-token skip, and warn for any non-control grant on a key's own path, are named among the cases that still warn. - The two changes are named as a tightening and a loosening; the bound loosens the refusal of an unexcused failure. Only serve's wait is bounded, said in the heading too. - The Decision's warning-class example is marked as no longer covering a grant on the hop's own key that creates, rewrites or deletes it. - SECURITY.md is linked as the operator-facing statement. - The README row points readers to Amendment B for the refusing class, stops overclaiming what refuses, and records that Amendment A built slice B. Verified-by: none --- ...t-under-enforce-with-an-audited-opt-out.md | 74 ++++++++++--------- docs/adr/README.md | 2 +- 2 files changed, 42 insertions(+), 34 deletions(-) diff --git a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md index 6080334a93..7a04ff3cf6 100644 --- a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md +++ b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md @@ -179,45 +179,53 @@ it the notifier, or the logging sink when no notifier is configured. - **Best effort.** A sink that raises is logged and never masks the finding, the audit row or the refusal. -## Amendment B (2026-12-01): a grant on another hop's path refuses, and each probe is bounded - -Vault BACKLOG #4851. Status unchanged: Proposed. Two changes go past the owner's 2026-10-04 line -*"Everything else warns, alerts and audits."* Both are deliberate. The Lander decided them under -the owner's delegation of 2026-12-01 (US Central), after an adversarial review; the question asked -and the owner's answer are in decision record d20261202T053010258-eb19bb. That is a delegated -decision, not an owner ruling. - -- **A cross-hop grant refuses.** The connector-secret token is now also asked about the paths the - store hop calls, and their keys' control and export paths (`privilege_probes._store_paths`), - when the two hops' Vault addresses match as written (`privilege_probes._same_vault`: nothing is - resolved, so two spellings of one server read as two and those paths go unasked). The store - token is not asked about the connector-secret paths. A grant the reading finds on such a path - (`reading.other_paths`) is judged by `privilege_check.vault_hop` into the hop's refusing list. - On a Transit key's own path, the grants that create, rewrite or delete the key refuse. On any +## Amendment B (2026-12-01): the connector-secret token's grants on the store's paths can refuse, and serve's wait on a probe is bounded + +Vault BACKLOG #4851. Status unchanged: Proposed. The Lander decided both changes under the owner's +delegation of 2026-12-01 (US Central), after an adversarial review; the question asked and the +owner's answer are in decision record d20261202T053010258-eb19bb. That is a delegated decision, +not an owner ruling. They move in opposite directions. The first tightens: it refuses a grant the +owner's 2026-10-04 line *"Everything else warns, alerts and audits."* puts in the warning class. +The second loosens a control: a probe that hangs for a reason the Decision does not excuse now +warns rather than refuses. The operator-facing statement of both is +[SECURITY.md](../SECURITY.md#each-backend-hops-least-privilege-the-engine-probes-the-store-vault-and-ldap); +this amendment records the decision. + +- **The connector-secret token's grants on the store's paths can refuse.** The check is one way: + the connector-secret token is asked about the paths the store hop calls + (`privilege_probes._store_paths`), and `privilege_check.vault_admin_paths` adds those keys' + control and export paths; the store token is never asked about the connector-secret paths. It + runs only when the two Vault addresses compare equal under `privilege_probes._same_vault`, which + ignores the case of the scheme and host and a trailing slash and resolves nothing, so two names + for one server read as two and the store's paths go unasked. `privilege_check.vault_hop` judges + a grant found on such a path (`reading.other_paths`). On a Transit key's own path, only the + grants that create, rewrite or delete the key refuse, and any other grant there warns. On any other such path, any grant but read or list refuses, so a capability string nobody recognises - fails closed. The case the ruling's words put in the warning class is a connector-secret token - that holds, for example, update on the store hop's Transit decrypt path. It now refuses a start - under `enforce`, unless `[security].allow_over_granted_vault_token` accepts it (audited), as the - gravest grants do. It still warns, never refuses, in at least two cases: read or list on such a - path, and a grant on a non-key path while whether the other hop holds this same token is - unknown. Unknown means either reading carries no token reference - (`privilege_check.vault_hops`). That includes a store probe ended by the bound below, whose - token may well have been read, so under `enforce` a slow store probe turns this refusal into a - warning and the start goes ahead. -- **Serve's wait on each probe is bounded at 150 seconds** (`vault_preflight.VAULT_PROBE_TIMEOUT_S`). - Before, `serve` waited on a probe with no bound of its own. Only the wait is bounded: the probe's + fails closed. The example is a connector-secret token holding update on the store hop's Transit + decrypt path: it now refuses a start under `enforce`, unless + `[security].allow_over_granted_vault_token` accepts it (audited), as the gravest grants do. It + still only warns in at least these cases: read or list on such a path; a path the other hop + calls when both hops hold this same token, which the shared-token check reports; and a non-key + grant while whether the other hop holds this same token is unknown. Unknown means either reading + carries no token reference (`privilege_check.vault_hops`). That includes a store probe ended by + the bound below, whose token may well have been read, so under `enforce` a slow store probe + turns this refusal into a warning and the start goes ahead. +- **Serve's wait on each probe is bounded at 150 seconds** (`vault_preflight.VAULT_PROBE_TIMEOUT_S`), + where before `serve` waited with no bound of its own. Only the wait is bounded: the probe's thread is not stopped and may go on calling Vault with the token after the start, and `check-privileges` runs the probes with no bound, so the two can disagree on a slow Vault. A - probe still running at the bound reads as a timeout, which warns and does not refuse. That - outcome is the second widening: it holds whatever made the probe hang, not only a network - timeout. A probe stuck for another reason, such as a code defect or a hung read of the token - file, now warns and lets an enforcing start go ahead, where the Decision above refuses any - failure that is not a network failure, a timeout or a 403. + probe still running at the bound reads as a timeout, which warns. That holds whatever made the + probe hang, not only a network timeout. A probe stuck for another reason, such as a code defect + or a hung read of the token file, now warns and lets an enforcing start go ahead, where the + Decision above refuses any failure that is not a network failure, a timeout or a 403. This is + the loosening. The same PR also added to the refusing set this ADR's Decision lists, at least the grants that create, rewrite or delete the hop's own Transit key, more Transit key administration paths and more -administrative paths. Those were judged to fit the ruling's *"Root policy, admin paths and Transit -key control"*; `privilege_check.VAULT_REFUSING_CLASS` states the class once. +administrative paths. They were judged to fit the ruling's *"Root policy, admin paths and Transit +key control"*; `privilege_check.VAULT_REFUSING_CLASS` states the class once. The Decision's +warning-class example *"an extra capability on a path the engine calls"* no longer covers a grant +that creates, rewrites or deletes the hop's own Transit key: that grant refuses. Undo for the first: judge the non-key cross-hop grant as a warning. Before this amendment the connector-secret token was never asked about the store hop's paths, so the undo makes a new warning diff --git a/docs/adr/README.md b/docs/adr/README.md index 6b3d278def..09ce69f26e 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -238,7 +238,7 @@ what is withheld and what you can request. | [0213](0213-seal-the-secret-rotation-fingerprint-as-a-store-cipher-cell.md) | **Seal the secret-rotation fingerprint as a store-cipher cell** (vault BACKLOG #3472, #3247 item 1) -- each non-DEK `secret_rotation_meta.fingerprint` becomes a store-cipher cell holding a per-row random HMAC key, the value's MAC and the row's class id, AAD-bound to its row and stored behind the `sealed-hmac-sha256-32` tag. `rotate-key`'s `reencrypt_to_active` re-seals it on all three backends, so a store key rotation no longer moves every fingerprint and no start needs the retired key. A cell the engine cannot read, and every pre-#3472 row, keeps its dates: an old row never resets a clock. `vault_transit` stays off (#3473). Supersedes the #2242 re-key rule and removes the DEK-derived fingerprint key. Rejected: carrying retired fingerprint keys forward (A, the fallback), a random per-store key, recomputing in `rotate-key`, a non-rotating derivation | **Accepted (2026-10-26)** -- owner ruling 2026-10-26, in session (batch 343 Manager), option "S: seal as cipher cell"; built with the change | | [0214](0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md) | **A secrets directory and one accessor for the engine's secret-class settings** (vault BACKLOG #2595, step 3, slice A of four) -- one list of the secret-class setting names in `engine_secrets.py`, which the NSSM reading takes its lists from, and one module every moved reader reads through: the file named for the setting in the directory `MEFOR_SECRETS_DIRECTORY` names, else the environment variable, so the directory wins. Moved: both Vault tokens, the `env()` values, the settings-borne secrets including the database password, and the rotation fingerprint. The reader checks the directory's own access list, then each file's, with the key-file check, and refuses at every enforcement setting a broad one, a link (on every platform since its 2026-11-13 amendment; on Windows only before it), a file named for no setting, an empty, non-UTF-8 or oversized file, and any file named for the store key, which stays in its DPAPI key file. Plain files: DPAPI wrapping waits on a spike. Slice A refused nothing that started before it. Rejected: one DPAPI file for every secret, purging the environment, a settings-file location | **Proposed (2026-10-27)** -- built as slice A; merging records it as Proposed and accepts nothing. Slice C (the installer creates the directory; the location stays operator-named) and slice D (the unbuilt provider names removed) built 2026-11-05, per its Amendments. Half of slice B (the NSSM reading refuses every secret-class name in the service's own lists) built 2026-11-11. Amended 2026-11-13: on POSIX the key-file check also judges the owner of the directory or file and the directory that holds it (`docs/CONFIGURATION.md` states the rule), and on Windows the folder that holds the directory is read too, read where the path resolves to since 2026-11-17; neither is a complete check of the directory's surroundings. Amended 2026-11-22: the host key provider's files may take a custody directory of their own. The rest of slice B (refusing such a secret found in the environment elsewhere, owner ruling 2026-10-01) is built for these names in part, 2026-11-24, per the 2026-11-11 amendment's update, which states what it covers. Open: at least whatever of slice B that update leaves, and whether a Windows file is also DPAPI-wrapped. Step 3 is not closed. Severity conditional per CLAUDE.md section 0 | | [0215](0215-the-web-console-calls-the-json-routes-in-process-through-the-asgi-app-so-one-gate-family-authorizes-both-planes.md) | **The web console calls the JSON routes in-process through the ASGI app, so one gate family authorizes both planes** (vault BACKLOG #2603, research step) -- the console stops calling engine handlers through `CoreHandlers` and `AdminHandlers` and sends each a bearer sub-request through the engine's own app, so every JSON gate runs; `get_engine`, `get_gate` and the console's non-sign-in `AuthService` reads go too. The sub-request's scope copies exactly the browser request's `client`, `server`, `scheme`, `http_version` and `root_path` (never `state`, which carries the mTLS peer certificate, and no browser header but a passed body's `Content-Type`), and one in-process `messagefoundry.console` scope extension carries the `/ui` path and a poll flag: no idle-clock touch for a timer-driven poll, every grant row written as a bearer request writes it (volume cut by composite poll routes, not by deduplication), no PHI-budget exemption (a two-resource page costs two, as a bearer client pays). Every console route outside the public and confinement sets makes at least one sub-request (gate-only `GET /auth/check/` routes, one `require(p)` each, for pages with no data); the JSON writes the console calls that are unpaced today gain admin-write pacing. `require_ui` shrinks to a read-only session check, same-origin on writes, and one refusal-to-browser-answer table. Adds an async client and a response-streaming in-process transport to `apiclient` (stock httpx `ASGITransport` sets a loopback client and buffers response bodies), and a policy class per JSON route. Rejected: the proof-object design (the dual-control executors, convergence and DR re-apply run with no request), a stronger parity guard, stock `ASGITransport`, router-only dispatch, grant-row deduplication. Amends ADR 0065 and ADR 0088 | **Accepted (2026-10-30)** -- owner ruling given in session to the batch 459 Manager through AskUserQuestion, "Accept (Recommended)"; the seven build slices go ahead in the build order, slice 7 at any point. The owner also answered two of its open questions, on grant rows for polls and on the grant row's form; the ADR's *To resolve on acceptance* records both. Open: the extra session reads per sub-request, owned by slice 5. ADR 0065 and ADR 0088 carry an *Amended by ADR 0215* note. Amended 2026-11-24 by an appended section (slice 2a: a check route writes the grant row of an audited permission), on the Lander's ruling d20261124T135809520-03bdbe under the owner's delegation of 2026-11-24. No code yet. Severity conditional per CLAUDE.md section 0. *Superseded cell text, kept as a record: "**Proposed (2026-10-29)** -- doc-only research step; no code. Seven build slices named in the ADR. Acceptance is the owner's; four questions open. Severity conditional per CLAUDE.md section 0".* | -| [0216](0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md) | **The gravest Vault token grants refuse start under enforce, with an audited opt-out** (vault BACKLOG #2903, slice A; ASVS 13.2.2) -- owner ruling 2026-10-04 (17:06:09Z UTC). `serve` probes each Vault token it uses at every start, with the `check-privileges` probe and a client from the provider's own constructor, after the store preflight and before any listener binds. The root policy, any grant on an administrative path (including a write of the token's own policies) and a Transit key's `config`, `rotate`, `export` or `backup` refuse start under `[security].enforcement = enforce`; `[security].allow_over_granted_vault_token` is the audited opt-out (an `AUDIT:` line, `over_grant_accepted` on the `vault_privilege_preflight` audit row, a `security_loosenings()` entry). Every other over-grant, and a probe stopped by a network failure, a timeout or a 403, warn and audit; a probe that failed for any other reason, such as a code defect, refuses under `enforce`. `vault_preflight_outcome` states the decision once for `serve` and `check-privileges`. The third recorded exception to "a new refusal fires only on a new opt-in". Rejected: refusing on any over-grant, reusing the store opt-out | **Proposed (2026-10-30)** -- built as slice A; merging records it as Proposed and accepts nothing. Open: the alert with its auto-resolving inverse (slice B). Amendment B (2026-12-01, vault BACKLOG #4851): a connector-secret token's grant beyond read or list on a path the store hop calls refuses too, and `serve` waits at most 150 s on each probe, a probe ended there warning whatever made it hang; both widen the ruling's "Everything else warns", by a Lander decision under the owner's delegation. Severity conditional per CLAUDE.md section 0 | +| [0216](0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md) | **The gravest Vault token grants refuse start under enforce, with an audited opt-out** (vault BACKLOG #2903, slice A; ASVS 13.2.2) -- owner ruling 2026-10-04 (17:06:09Z UTC). `serve` probes each Vault token it uses at every start, with the `check-privileges` probe and a client from the provider's own constructor, after the store preflight and before any listener binds. The root policy, any grant on an administrative path (including a write of the token's own policies) and a Transit key's `config`, `rotate`, `export` or `backup` refuse start under `[security].enforcement = enforce`; `[security].allow_over_granted_vault_token` is the audited opt-out (an `AUDIT:` line, `over_grant_accepted` on the `vault_privilege_preflight` audit row, a `security_loosenings()` entry). Every other over-grant, and a probe stopped by a network failure, a timeout or a 403, warn and audit; a probe that failed for any other reason, such as a code defect, refuses under `enforce`. `vault_preflight_outcome` states the decision once for `serve` and `check-privileges`. The third recorded exception to "a new refusal fires only on a new opt-in". Rejected: refusing on any over-grant, reusing the store opt-out | **Proposed (2026-10-30)** -- built as slice A; merging records it as Proposed and accepts nothing. Amendment A (2026-11-06) built the alert with its auto-resolving inverse (slice B). Amendment B (2026-12-01, vault BACKLOG #4851) changes the refusing class and the probe wait; read it there rather than the class listed in this row: some connector-secret token grants on the store hop's paths now refuse, more Transit key and administrative paths refuse, and a probe `serve` stops waiting on at 150 s warns whatever made it hang, which loosens the refusal of an unexcused failure. Severity conditional per CLAUDE.md section 0 | | [0217](0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md) | **An unverifiable Transit row seal is denied like a failed one, and the AD reconciler ends sessions rather than holding** (vault BACKLOG #4739, design for #2592's `vault_transit` limb; engine PR 2565 is the parked reference) -- four answers to a seal check: holds, forged (`valid: false` or a malformed seal), unverifiable (a `verify` HTTP 400 while the fixed-input probe works, whatever version it names) and outage. Unverifiable denies the row as forged does (never tombstoning or raw-deleting one on its own), under `integrity.authority_seal_unverifiable` and a capped per-row subject, because a database writer can plant an unheld key version. Transit is sent a fixed-length SHA-256 of the seal input, so no row can force an outage by size. AD sign-in and the certificate leg refuse on an unverifiable map; on a map that does not hold, forged included, the reconciler writes no role row and ends the sessions of accounts whose groups moved since a new sealed `users.directory_groups_digest`, under the unchanged mass-revoke brake, after first trying `main`'s own set; every unverifiable or forged map pages each pass under its own uncapped subject. Write refusals raise `RowSealError` or its sibling `RowSealUnverifiableError` under a catch census, and every catch site audits; a session end never rolls back. Seal-state and outage-refused sign-ins write their own actions and do not count toward the sign-in burst. An owner-rulings list heads the ADR; residuals named: no cross-store binding until #3411, no rollback detection until #2592 step 7, 60 s of cached trust after a version retirement. Rejected: a lagging-node outage case, holding reconcile diffs, ending the sessions outside the brake, re-judging offboarding on a tripped pass, applying demotions from an empty map, re-sealing a map nobody verified | **Accepted (2026-11-06)** by owner ruling on every entry -- design only, no code yet; every answer is a control decision. Severity conditional per CLAUDE.md section 0 | ## Retired allocations — numbers taken but never authored From 548a0879070a9277abc47b90fd4f9427d6800724 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 13:23:17 -0600 Subject: [PATCH 18/31] A Vault probe ended by the bound keeps its token reference read_vault_token names its token before any network call, through a ContextVar sink the startup preflight sets per probe. A store probe the 150 s bound abandons then still names its token, so a secrets token that differs refuses a cross-hop grant under enforce rather than warning on a sharing nobody could tell. Vault BACKLOG #4851, hold fix 1 on PR 3553. Verified-by: tests --- messagefoundry/privilege_check.py | 20 +++++----- messagefoundry/privilege_probes.py | 13 ++++++ messagefoundry/vault_preflight.py | 12 ++++-- tests/test_vault_privilege_preflight_4851.py | 42 ++++++++++++++++++++ 4 files changed, 73 insertions(+), 14 deletions(-) diff --git a/messagefoundry/privilege_check.py b/messagefoundry/privilege_check.py index dc22c89c66..f15f7ca2c2 100644 --- a/messagefoundry/privilege_check.py +++ b/messagefoundry/privilege_check.py @@ -460,16 +460,16 @@ def vault_hop( """Judge one token's self-reading against what the engine calls with it. ``unmatched`` names each other hop whose reading, or this one, carries no token reference (at - least: the token was unset, the client could not be built, the probe hit the bound, raised - past :func:`~messagefoundry.privilege_probes.read_vault_token` or found no thread), so whether - it holds this same token is unknown. Most failures inside the probe keep the reference. A grant - on a path another hop calls, other than on a Transit key's own path, then warns rather than - refuses, says why, and marks the hop ``partial``: had the token been compared and found shared, - the grant would be that hop's own and warn, so a refusal would rest on a comparison never made - (vault BACKLOG #4851). Not shared, the same grant refuses once both probes name their tokens, - so whether it refuses still turns on whether the other hop's probe finished. The probe does not - record which hop calls which path, so with more than two hops any unmatched hop downgrades - every such path. + least: the token was unset, the client could not be built, the probe hit the bound before it + named its token, raised past :func:`~messagefoundry.privilege_probes.read_vault_token` or found + no thread), so whether it holds this same token is unknown. Most failures inside the probe keep + the reference. A grant on a path another hop calls, other than on a Transit key's own path, then + warns rather than refuses, says why, and marks the hop ``partial``: had the token been compared + and found shared, the grant would be that hop's own and warn, so a refusal would rest on a + comparison never made (vault BACKLOG #4851). Not shared, the same grant refuses once both probes + name their tokens, so whether it refuses still turns on whether the other hop's probe named its + token. The probe does not record which hop calls which path, so with more than two hops any + unmatched hop downgrades every such path. Over-granted: a ``root`` policy; any capability beyond the one a configured path needs; any capability but ``deny`` on an administrative path the engine never calls; or, when ``shared`` diff --git a/messagefoundry/privilege_probes.py b/messagefoundry/privilege_probes.py index f71c52ccd4..07cbb70d38 100644 --- a/messagefoundry/privilege_probes.py +++ b/messagefoundry/privilege_probes.py @@ -38,6 +38,7 @@ import logging import socket from collections.abc import Callable, Iterable, Mapping +from contextvars import ContextVar from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any from urllib.parse import urlsplit @@ -62,6 +63,7 @@ from messagefoundry.privilege_check import VaultConsumer __all__ = [ + "VAULT_TOKEN_REF_SINK", "VaultTokenReading", "excused_failure", "preload_vault_probe_imports", @@ -111,6 +113,15 @@ def same_token_as(self, other: VaultTokenReading) -> bool: return self.token_ref is not None and self.token_ref == other.token_ref +#: Where :func:`read_vault_token` hands a token's reference as soon as it has one, before any +#: network call (vault BACKLOG #4851). The startup preflight sets it for each probe it bounds, so a +#: probe the bound ends still names its token, and another hop's grant is judged against it rather +#: than as a sharing nobody could tell. +VAULT_TOKEN_REF_SINK: ContextVar[Callable[[str], None] | None] = ContextVar( + "vault_token_ref_sink", default=None +) + + def _problem(text: str) -> str: """Log one probe problem and return it. The text is already secret-free (:func:`_why`), and is logged with every character in ``CONTROL_CATEGORIES`` escaped visibly, by the log's own @@ -350,6 +361,8 @@ def why(exc: BaseException) -> str: for p in problems: _problem(p) token_ref = hashlib.sha256(named.encode("utf-8")).hexdigest() + if (sink := VAULT_TOKEN_REF_SINK.get()) is not None: + sink(token_ref) from messagefoundry.config.tls_policy import InsecureHopRefused diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index 2d0e3b772c..6cb055a4eb 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -66,6 +66,7 @@ vault_refusal_reason, ) from messagefoundry.privilege_probes import ( + VAULT_TOKEN_REF_SINK, VaultTokenReading, preload_vault_probe_imports, unexcused_cause, @@ -210,9 +211,10 @@ async def _probe_all( ) -> list[VaultTokenReading]: """Every consumer's reading, the probes run side by side, each off the event loop and each bounded by ``timeout`` seconds (vault BACKLOG #4851). A probe still running at the bound reads - as a timeout, which the owner ruling of 2026-10-04 lets only warn. Its thread cannot be - stopped and runs on until the client's own request timeouts end it, and its reading is - dropped. It is a daemon thread of its own, not the loop's default executor, so neither the + as a timeout, which the owner ruling of 2026-10-04 lets only warn; it keeps the token reference + the probe named before the bound, so another hop's grant is still judged against it. Its thread + cannot be stopped and runs on until the client's own request timeouts end it, and its reading + is dropped. It is a daemon thread of its own, not the loop's default executor, so neither the loop's shutdown nor the interpreter's exit waits on it.""" loop = asyncio.get_running_loop() # The probes import their providers lazily. Done here, once, before any probe thread starts, @@ -224,6 +226,8 @@ async def _probe_all( async def bounded(consumer: VaultConsumer) -> VaultTokenReading: done: asyncio.Future[VaultTokenReading] = loop.create_future() context = contextvars.copy_context() + named: list[str] = [] + context.run(VAULT_TOKEN_REF_SINK.set, named.append) def deliver(reading: VaultTokenReading) -> None: if not done.done(): # cancelled by the bound, so nobody reads it @@ -266,7 +270,7 @@ def run() -> None: except TimeoutError: problem = f"the probe did not finish within {timeout:g}s (a timeout)" log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) - return VaultTokenReading(problems=(problem,)) + return VaultTokenReading(problems=(problem,), token_ref=named[0] if named else None) return list(await asyncio.gather(*(bounded(c) for c in consumers))) diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index 8389a14913..56d41959cb 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -268,6 +268,48 @@ def probe(consumer: VaultConsumer) -> VaultTokenReading: assert "is unknown" in secrets.detail +async def test_a_store_probe_ended_by_the_bound_keeps_its_token_and_the_refusal_holds( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``read_vault_token`` names its token before any network call, so a store probe the bound + ends there still names it, and a secrets token that differs refuses the decrypt grant.""" + monkeypatch.setattr(vault_preflight, "vault_consumers", lambda settings: [_STORE, _KV]) + decrypt = f"transit/decrypt/{_KEK}" + release = threading.Event() + hung = SimpleNamespace( + auth=SimpleNamespace(token=SimpleNamespace(lookup_self=lambda: release.wait(10) and {})) + ) + + def probe(consumer: VaultConsumer) -> VaultTokenReading: + if consumer.hop == "vault.store": + return read_vault_token( + lambda: "synthetic-store-token", + lambda: _VAULT_ADDR, + lambda a, t: hung, + lambda: {decrypt: frozenset({"update"})}, + ) + vault = _FakeVault(caps={_KV_PATH: ["read"], decrypt: ["update"]}) + return _kv_reading(vault, other_required=lambda: [f"transit/keys/{_KEK}", decrypt]) + + store = _AuditStore() + try: + with pytest.raises(VaultPrivilegeError, match="vault.secrets"): + await run_vault_privilege_preflight( + _VAULT_SETTINGS, + store, + enforcing=True, + over_grant_accepted=False, + probe=probe, + probe_timeout=0.2, + ) + finally: + release.set() + rows = {detail["hop"]: detail for _, detail in store.audits} + assert "did not finish within 0.2s" in rows["vault.store"]["detail"] + assert rows["vault.store"]["refused"] is False + assert any(r.startswith(f"{decrypt} grants update") for r in rows["vault.secrets"]["refusing"]) + + def test_a_shared_token_whose_store_read_failed_reports_the_skipped_grant() -> None: """Report only: the grant is named as a warning, never a refusal.""" decrypt = f"transit/decrypt/{_KEK}" From 3137278a94907c11b466481b2938781739ba0b94 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 13:24:14 -0600 Subject: [PATCH 19/31] Docs name the 150 s Vault probe bound as the case that only warns CONFIGURATION.md and SECURITY-LOOSENING.md said any other probe failure refuses under enforce; a probe still running at the bound reads as a timeout and only warns. SECURITY.md says the wait is abandoned at 150 s and the probe thread may run on. Vault BACKLOG #4851, hold fix 2 on PR 3553. Verified-by: none --- docs/CONFIGURATION.md | 2 +- docs/SECURITY-LOOSENING.md | 3 ++- docs/SECURITY.md | 6 ++++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 703a1bffbd..45e3f5fb87 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3694,7 +3694,7 @@ and a PHI weakening under **strict enforcement** (`enforcement = enforce`, the d | `allow_single_factor_admin_when_exposed` | bool | `false` | permit **single-factor sign-in on an exposed PHI instance** (ADR 0140). With `require_mfa` explicitly off, and the instance exposed — a **non-loopback bind**, a declared TLS-terminating proxy (`[api].tls_terminated_upstream`), **or** a set `[api].trusted_proxies` (a loopback bind behind a proxy re-encrypting to an operator `tls_cert_file`; vault BACKLOG #2251) — a PHI instance under `enforcement = enforce` **refuses to start** (exit 2). Every account with no second factor enrolled, Administrators included, would then sign in over the network with a single factor. The one exception is an OIDC sign-in that carries an amr/acr claim checked while `[auth].oidc_require_mfa_claim` is on. The refusal, its exposure warnings and its AUDIT line name it only when this config has it. The `security_loosenings()` entry describes the switch, not one config, so it always names it. The gate reads at least exposure, `require_mfa` and `enforcement`, and never a tier or account kind. Setting this permits that start; it is recorded in a WARNING-level AUDIT line and the ordinary exposure warning still prints. A **loosening** — `security_loosenings()` reports it. **The exposure test does not consult the browser console** ([BACKLOG #326](BACKLOG.md); ADR 0140 amendment). It did, and that made the arm miss the topology this document recommends: a loopback bind behind a declared terminator with `serve_web_console` left at its default, where the ADR 0143 auto-degrade clears the console flag in place before the gate reads it. The exposed surface that authenticates with one factor is the **JSON operator API**, which the proxy serves whether or not `/ui` is mounted, so the predicate is the bind-and-proxy posture alone and the refusal fires on at least: an off-loopback bind; a declared proxy with the console left default-on; and a declared proxy with `serve_web_console = false`. **This refusal is one of at least two exceptions to the "a new refusal fires only on a new opt-in" scoping rule (another is the ADR 0199 store-login refusal)**, which the `require_memory_encryption_declaration` row below states — by owner ruling of 2026-08-04, recorded in the [ADR 0140](adr/0140-two-acknowledged-production-phi-no-loosen-carve-outs-single-factor-admin-at-exposure-keyless-phi-in-production.md) amendment, which is the single source for why. Nothing new gates it. **One residual is deliberately left open:** an **undeclared** proxy — `web_console_public_address` set with neither `tls_terminated_upstream` nor `trusted_proxies` — does not count as exposed here, because nothing was declared, so exposure would be an *inference*, and an inference must not refuse. It **warns** instead, on its own dedicated arm: on a PHI instance with `require_mfa` explicitly off, startup prints that if that origin is served by an undeclared proxy every account with no second factor enrolled is single-factor over the network, with the same OIDC exception, and this refusal cannot see it. Do **not** read the ADR 0068 §8 undeclared-proxy warning as that control — it is about the `/ui` session cookie and HSTS, and it is suppressed entirely when the ADR 0143 auto-degrade clears the console flag, which the same `web_console_public_address` triggers. **Prefer `require_mfa = true` — and know its scope.** Under the shipped `require_mfa_scope = "every_local_account"` it requires a second factor from **every** account, *not* only Administrators and (since BACKLOG #1144) *not* only local ones, so a non-interactive bearer-token service account becomes MFA-pending and cannot enrol unattended. **With `require_mfa` kept on, there is one remedy.** Set `require_mfa_scope = "administrators"` (itself reported as a loosening, and it leaves every Administrator in scope) — see that row below. **Making it a directory (AD/Kerberos) principal is no longer the other one:** directory identities used to be out of scope under either value, their factor delegated to the directory, and BACKLOG #1144 retired that. **mTLS is not one either.** A `[api].tls_client_cert_identities` mapping does grant a cert-identity that never meets the MFA gate, but that plane is admitted on exactly **one** route (`GET /service/identity`, `require_service_cert`) and carries no session, so an account "moved to mTLS" can read back its own identity and nothing else — it cannot replay, purge, poll status, or do any work a service account exists for. The `[api].tls_client_cert_identities` row above is the authority on that reach. An AD-only deployment is therefore in scope for **all** of its accounts — its directory principals, any local administrator, and any local service accounts | | `allow_unverified_alert_smtp_tls` | bool | `false` | the **acknowledgment** required to start an enforcing PHI instance whose `[alerts]` SMTP hop does not authenticate the relay — i.e. `[alerts].email_use_tls = false` (cleartext) or `[alerts].email_tls_verify = false` (encrypted but accepts any certificate) ([#323](BACKLOG.md)). Covers BOTH shapes deliberately: cleartext is strictly worse than unauthenticated TLS, so gating only the second would hand an operator a bypass onto the worse posture. Without it `serve` refuses to start (exit 2); with it the start is permitted and named in a WARNING-level `AUDIT:` line. An **acknowledgment switch rather than the clamped `MEFOR_ALLOW_INSECURE_TLS` escape** the connectors use, because this cell is constructed outside the `active_hop_posture` scope, where that clamp reads no posture and so cannot carry an acknowledgment (since vault BACKLOG #2354 it refuses there; it used to be inert). A **loosening** — `security_loosenings()` reports it, so it is never silent. It covers a hop with **no login** only: with `[alerts].email_username` set, either shape is refused at load, so the SMTP AUTH password never crosses (vault BACKLOG #3533) | | `allow_over_granted_store_principal` | bool | `false` | the **audited opt-out** from the refusal an over-granted store login earns under `enforcement = enforce` ([ADR 0199](adr/0199-an-over-granted-store-login-refuses-start-under-enforce-with-an-audited-opt-out.md), ASVS 13.2.2). The startup privilege preflight reads the `[store]` login's effective privileges; when it holds more than [`DEPLOY-SERVER-DB.md` §1.1/§1.2](DEPLOY-SERVER-DB.md) prescribes, `serve` refuses to start unless this is set. With it set the start goes ahead, a WARNING-level `AUDIT:` line names the switch, and the `store_privilege_preflight` audit row carries `over_grant_accepted: true`. It lifts that one refusal only: the warning and the `store_privilege_warning` alert still fire, an unobservable probe needs no opt-out (it only warns), and `[store].require_least_privilege = true` outranks it. SQLite never needs it. A **loosening** — `security_loosenings()` reports it. Env: `MEFOR_SECURITY_ALLOW_OVER_GRANTED_STORE_PRINCIPAL` | -| `allow_over_granted_vault_token` | bool | `false` | the **audited opt-out** from the refusal the gravest Vault grants earn under `enforcement = enforce` ([ADR 0216](adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md), BACKLOG #2903, ASVS 13.2.2). At every start `serve` probes each Vault token it uses, and a token holding a grant in the refusing class refuses the start unless this is set; [`SECURITY.md`](SECURITY.md), *What `serve` does with a Vault finding*, defines the two classes. With it set the start goes ahead, a WARNING-level `AUDIT:` line names the switch, and the `vault_privilege_preflight` audit row carries `over_grant_accepted: true`. It lifts that one refusal only: a warning-class finding and a probe stopped by a network failure, a timeout or a 403 only warn, and a probe that failed for any other reason, such as a code defect, refuses under `enforce` whatever this says. Under `enforcement = warn` nothing refuses. A **loosening** — `security_loosenings()` reports it. Env: `MEFOR_SECURITY_ALLOW_OVER_GRANTED_VAULT_TOKEN` | +| `allow_over_granted_vault_token` | bool | `false` | the **audited opt-out** from the refusal the gravest Vault grants earn under `enforcement = enforce` ([ADR 0216](adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md), BACKLOG #2903, ASVS 13.2.2). At every start `serve` probes each Vault token it uses, and a token holding a grant in the refusing class refuses the start unless this is set; [`SECURITY.md`](SECURITY.md), *What `serve` does with a Vault finding*, defines the two classes. With it set the start goes ahead, a WARNING-level `AUDIT:` line names the switch, and the `vault_privilege_preflight` audit row carries `over_grant_accepted: true`. It lifts that one refusal only: a warning-class finding and a probe stopped by a network failure, a timeout or a 403 only warn, and a probe that failed for any other reason, such as a code defect, refuses under `enforce` whatever this says, except a probe still running at the 150-second bound, which reads as a timeout and only warns, whatever held it up. Under `enforcement = warn` nothing refuses. A **loosening** — `security_loosenings()` reports it. Env: `MEFOR_SECURITY_ALLOW_OVER_GRANTED_VAULT_TOKEN` | | `allow_remote_debugging` | bool | `false` | the **named acceptance** that lifts the refusal `serve` and `supervise` make under `enforcement = enforce` to start with the interpreter's remote debugging (PEP 768) on (vault BACKLOG #2700). For a developer's console-script start, never a deployment: the shipped service launches start with the interface off. A **loosening**, reported; a start it lets through writes a WARNING-level `AUDIT:` line. When the refusal fires is stated once, in [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md#remote_debug_enabled-and-remote_debug_unguarded-the-interpreter-accepts-a-script-from-another-process); what the acceptance leaves open and records is in [its own section](SECURITY-LOOSENING.md#allow_remote_debugging--true----start-under-enforce-with-the-interpreters-remote-debugging-on). Env: `MEFOR_SECURITY_ALLOW_REMOTE_DEBUGGING` | | `require_nonstatic_credentials` | bool | `false` | **opt-in static-credential refusal** (ASVS 13.2.1, [BACKLOG #1182](BACKLOG.md)). Off by default, by owner decision (2026-09-23). When `true`, `serve` refuses to start while any backend hop the engine dials presents an unchanging credential or none and is not named in `static_credential_accepted`. The service-settings hops (`[store]`, `[alerts]`, `[auth]`, `[ai]`, `[secrets]`, `[logging]`) are checked before anything starts, and a refusal there exits 2. The connection graph is checked at the first load, where a refusal fails the server's startup, and at every `/config/reload`, where a refused reload leaves the running graph in place. Read once at start: a `/config/reload` judges the new graph against the value the engine started with, so an edit takes effect on restart. The refuse/warn split is `enforcement`, as for `[store].require_managed_identity`. Several hops have **no** compliant credential kind in the product, so with this on they can only run under an opt-out; the full list is in [`CONNECTIONS.md`](CONNECTIONS.md) §*Static credentials on every backend hop*. Not a loosening: it tightens. Env: `MEFOR_SECURITY_REQUIRE_NONSTATIC_CREDENTIALS` | | `static_credential_accepted` | table | `{}` | the audited per-hop opt-outs for `require_nonstatic_credentials`: hop name to reason, e.g. `{ "OB_ACME_REST" = "partner offers HTTP Basic only" }`. Hop names are the ones `messagefoundry check`'s `static-credentials` line and `GET /security/posture` print: an outbound connection's own name, or a name with a prefix (`settings:` for a service-settings hop; `inbound:`, `fhir_lookup:`, `db_lookup:`, `reference:` or `proxy:` for the others). A blank reason is refused at load. Read only while the refusal is on. Then each honoured entry is logged at start by name and reason, never by secret; an entry that matches no hop is logged as doing nothing; and `security_loosenings()` names the set. Read once at start, like the rest of `[security]`: a `/config/reload` does not re-read it, so an added, changed or removed opt-out takes effect on restart | diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index cf2a0307f9..cec5a0a312 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -2311,7 +2311,8 @@ count is above `0` (vault BACKLOG #2613). token shared by two hops or an extra capability on a path the engine calls, and a probe that could not read the token because of a network failure, a timeout or a 403, only warn, so there is nothing for it to lift there. A probe that failed for any other reason, such as a code defect, - refuses under `enforce`, and this switch does not lift that refusal. + refuses under `enforce`, and this switch does not lift that refusal. The exception is a probe + still running at the 150-second bound: it reads as a timeout and only warns, whatever held it up. - **How to turn it off:** remove it, after the token's policy matches the grant [`SECURITY.md`](SECURITY.md) prescribes for that hop. `messagefoundry check-privileges` shows the grant and what `serve` would do with it. diff --git a/docs/SECURITY.md b/docs/SECURITY.md index a8dca5926d..5b360a860a 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1300,8 +1300,10 @@ token variable, another Vault error status, and an answer that names no capabili Under `enforce` such a failure **refuses to start**, the audit row names it under `unexcused`, and the opt-out does not lift it. -The probes run side by side, and a probe still running after 150 seconds is cut off and reads as a -timeout, which only warns. A token whose `auth/token/lookup-self` is denied (a 403, so only a +The probes run side by side. The preflight abandons its wait on a probe still running after 150 +seconds, and that probe reads as a timeout, which only warns, whatever held it up. Its thread is +not stopped: it may run on until the Vault client's own request timeouts end it, and what it reads +then is dropped. A token whose `auth/token/lookup-self` is denied (a 403, so only a warning) cannot name its own policies, so whether it can rewrite them is not asked; its hop says so. What the preflight read of each token is on `GET /security/posture`, under `vault_privilege`; a channel-scoped reader is shown each hop's state and counts, not its text. There, as in the audit From d1b003003af341e20bfdc9720eca2961714ea551 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 13:38:53 -0600 Subject: [PATCH 20/31] Review round 1: docs and comments match the kept token reference SECURITY.md and ADR 0216 no longer say a probe ended by the bound leaves its token unnamed; they say it does only before the client is built, and that the ended reading refuses a grant on a shared token too. The sink comment and the vault_hops docstring say when the reference is taken. The new test bounds at 2 s so the fast probe cannot time out. Vault BACKLOG #4851, PR 3553 hold. Verified-by: tests --- docs/SECURITY.md | 12 +++++++----- ...se-start-under-enforce-with-an-audited-opt-out.md | 8 +++++--- messagefoundry/privilege_check.py | 10 +++++----- messagefoundry/privilege_probes.py | 4 ++-- tests/test_vault_privilege_preflight_4851.py | 9 +++++---- 5 files changed, 24 insertions(+), 19 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 5b360a860a..b4e248a5d9 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1191,11 +1191,13 @@ The administrative paths it is asked about are at least these: above. The store key's own path is judged by the Transit-key rule in the next paragraph. On any other path the store hop calls, which uses the key (such as `update` on `transit/decrypt/`), every grant but `read` and `list` is in the refusing class, and those - two warn. A token shared by both hops is judged as the shared-token rule above says instead. + two warn. A token shared by both hops is judged as the shared-token rule above says instead, + except where the store hop's probe was cut off at the bound below: that reading names none of + the store hop's paths, so such a grant refuses even on a shared token. When either hop's reading names no token, whether the two share one is unknown. At least these leave it unnamed: an unset token, a client that could not be built, a probe cut off at the bound - below, and a probe that raised or could not start its thread; most other probe failures keep - it. Then a refusing-class grant on a path the store hop calls, other than the key's own, only + below before it built its Vault client, and a probe that raised or could not start its thread; + most other probe failures keep it, a probe cut off later included. Then a refusing-class grant on a path the store hop calls, other than the key's own, only warns, and the hop says why and is marked partial: shared, it would only warn. Under `enforce` the start is still refused when the store hop's own failure is not one the excused list below names (a network failure, a timeout or a 403). @@ -1302,8 +1304,8 @@ the opt-out does not lift it. The probes run side by side. The preflight abandons its wait on a probe still running after 150 seconds, and that probe reads as a timeout, which only warns, whatever held it up. Its thread is -not stopped: it may run on until the Vault client's own request timeouts end it, and what it reads -then is dropped. A token whose `auth/token/lookup-self` is denied (a 403, so only a +not stopped: it may run on, and go on calling Vault with the token after the start, for as long as +whatever held it up lasts, and what it reads then is dropped. A token whose `auth/token/lookup-self` is denied (a 403, so only a warning) cannot name its own policies, so whether it can rewrite them is not asked; its hop says so. What the preflight read of each token is on `GET /security/posture`, under `vault_privilege`; a channel-scoped reader is shown each hop's state and counts, not its text. There, as in the audit diff --git a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md index 7a04ff3cf6..4c05e5a3fc 100644 --- a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md +++ b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md @@ -205,11 +205,13 @@ this amendment records the decision. decrypt path: it now refuses a start under `enforce`, unless `[security].allow_over_granted_vault_token` accepts it (audited), as the gravest grants do. It still only warns in at least these cases: read or list on such a path; a path the other hop - calls when both hops hold this same token, which the shared-token check reports; and a non-key + calls when both hops hold this same token and the other hop's probe finished, which the + shared-token check reports; and a non-key grant while whether the other hop holds this same token is unknown. Unknown means either reading carries no token reference (`privilege_check.vault_hops`). That includes a store probe ended by - the bound below, whose token may well have been read, so under `enforce` a slow store probe - turns this refusal into a warning and the start goes ahead. + the bound below before it built its Vault client. A store probe ended after that keeps its token + reference (`privilege_probes.VAULT_TOKEN_REF_SINK`), so the grant still refuses, and refuses on + a token both hops hold too, because the ended reading names none of the store hop's paths. - **Serve's wait on each probe is bounded at 150 seconds** (`vault_preflight.VAULT_PROBE_TIMEOUT_S`), where before `serve` waited with no bound of its own. Only the wait is bounded: the probe's thread is not stopped and may go on calling Vault with the token after the start, and diff --git a/messagefoundry/privilege_check.py b/messagefoundry/privilege_check.py index f15f7ca2c2..319f588c0d 100644 --- a/messagefoundry/privilege_check.py +++ b/messagefoundry/privilege_check.py @@ -669,11 +669,11 @@ def vault_hops( ) -> list[HopPrivilege]: """Judge every Vault hop, each against the union of grants of every hop that holds its token. - Two hops hold one token when lookup-self named the same token for both (``same_token_as``). A - reading that could not name its token is judged alone, and it also leaves every other hop's - sharing unknown, which turns another hop's refusal for a grant on a path only the unnamed hop - calls, other than a Transit key's own path, into a warning (``unmatched`` in - :func:`vault_hop`).""" + Two hops hold one token when both readings carry the same token reference (``same_token_as``), + taken before lookup-self, so a probe ended by the bound can match too. A reading that could not + name its token is judged alone, and it also leaves every other hop's sharing unknown, which + turns another hop's refusal for a grant on a path only the unnamed hop calls, other than a + Transit key's own path, into a warning (``unmatched`` in :func:`vault_hop`).""" hops: list[HopPrivilege] = [] for consumer, reading in zip(consumers, readings, strict=True): others = [ diff --git a/messagefoundry/privilege_probes.py b/messagefoundry/privilege_probes.py index 07cbb70d38..955233d064 100644 --- a/messagefoundry/privilege_probes.py +++ b/messagefoundry/privilege_probes.py @@ -113,8 +113,8 @@ def same_token_as(self, other: VaultTokenReading) -> bool: return self.token_ref is not None and self.token_ref == other.token_ref -#: Where :func:`read_vault_token` hands a token's reference as soon as it has one, before any -#: network call (vault BACKLOG #4851). The startup preflight sets it for each probe it bounds, so a +#: Where :func:`read_vault_token` hands a token's reference once it has built the hop's client, +#: before any network call (vault BACKLOG #4851). The startup preflight sets it for each probe it bounds, so a #: probe the bound ends still names its token, and another hop's grant is judged against it rather #: than as a sharing nobody could tell. VAULT_TOKEN_REF_SINK: ContextVar[Callable[[str], None] | None] = ContextVar( diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index 56d41959cb..dc05363bb1 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -271,8 +271,9 @@ def probe(consumer: VaultConsumer) -> VaultTokenReading: async def test_a_store_probe_ended_by_the_bound_keeps_its_token_and_the_refusal_holds( monkeypatch: pytest.MonkeyPatch, ) -> None: - """``read_vault_token`` names its token before any network call, so a store probe the bound - ends there still names it, and a secrets token that differs refuses the decrypt grant.""" + """``read_vault_token`` names its token once it has built the client, before any network + call, so a store probe the bound ends there still names it, and a secrets token that differs + refuses the decrypt grant.""" monkeypatch.setattr(vault_preflight, "vault_consumers", lambda settings: [_STORE, _KV]) decrypt = f"transit/decrypt/{_KEK}" release = threading.Event() @@ -300,12 +301,12 @@ def probe(consumer: VaultConsumer) -> VaultTokenReading: enforcing=True, over_grant_accepted=False, probe=probe, - probe_timeout=0.2, + probe_timeout=2.0, ) finally: release.set() rows = {detail["hop"]: detail for _, detail in store.audits} - assert "did not finish within 0.2s" in rows["vault.store"]["detail"] + assert "did not finish within 2s" in rows["vault.store"]["detail"] assert rows["vault.store"]["refused"] is False assert any(r.startswith(f"{decrypt} grants update") for r in rows["vault.secrets"]["refusing"]) From b656bdb777efddf54374c02463f12fb951565a0e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 14:44:15 -0600 Subject: [PATCH 21/31] Vault preflight waits for each probe again: remove the 150 s probe bound The startup preflight no longer stops waiting on a Vault probe after 150 seconds. A probe still running at the bound read as a timeout, which only warns, so a slow probe on a root token passed under enforce, and a slow store probe left the other hop judged against a reading with no paths. serve now waits for each probe as origin/main does; the probes still run side by side on daemon threads off the event loop, a failed thread start and a BaseException still refuse under enforce, and a cancelled start does not wait on a probe thread. The cross-hop refusal stays. Removed: VAULT_PROBE_TIMEOUT_S, the probe_timeout parameter and timeout branch, and VAULT_TOKEN_REF_SINK, which only the bound used. ADR 0216 Amendment B and its index row, docs/SECURITY.md, docs/CONFIGURATION.md, docs/SECURITY-LOOSENING.md and the changelog fragment now say the start waits, and that a total bound was considered and declined. Lander hold 7357681986 on PR 3553, decision d20261202T202356290-48e563. Vault BACKLOG #4851. Verified-by: tests --- ...1-vault-preflight-refusal-gaps.security.md | 2 +- docs/CONFIGURATION.md | 2 +- docs/SECURITY-LOOSENING.md | 3 +- docs/SECURITY.md | 26 +- ...t-under-enforce-with-an-audited-opt-out.md | 40 ++- docs/adr/README.md | 2 +- messagefoundry/privilege_check.py | 11 +- messagefoundry/privilege_probes.py | 13 - messagefoundry/vault_preflight.py | 62 ++-- tests/test_vault_privilege_preflight_4851.py | 287 ++++++++++++------ 10 files changed, 260 insertions(+), 188 deletions(-) diff --git a/changelog.d/4851-vault-preflight-refusal-gaps.security.md b/changelog.d/4851-vault-preflight-refusal-gaps.security.md index 6a1f75db4a..e3a9b83f51 100644 --- a/changelog.d/4851-vault-preflight-refusal-gaps.security.md +++ b/changelog.d/4851-vault-preflight-refusal-gaps.security.md @@ -1 +1 @@ -- The Vault token preflight now also refuses an enforcing start on a token holding a grant on an audit device, `sys/seal`, raw storage, or the root-token generation or rekey endpoints, or one that can create, rewrite or delete a Transit key the engine uses, or trim, import over, BYOK-export, restore or export one version of it; and on a connector-secret token, on the same Vault address as the store, that can do so to the store key. The probes run side by side, each cut off after 150 seconds as a timeout, which only warns. A token whose lookup-self is denied says its own policies went unasked. `GET /security/posture` reports what the preflight read of each token, under `vault_privilege`. (BACKLOG #4851) +- The Vault token preflight now also refuses an enforcing start on a token holding a grant on an audit device, `sys/seal`, raw storage, or the root-token generation or rekey endpoints, or one that can create, rewrite or delete a Transit key the engine uses, or trim, import over, BYOK-export, restore or export one version of it; and on a connector-secret token, on the same Vault address as the store, that can do so to the store key. The probes run side by side, and the start still waits for each one to finish. A token whose lookup-self is denied says its own policies went unasked. `GET /security/posture` reports what the preflight read of each token, under `vault_privilege`. (BACKLOG #4851) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 45e3f5fb87..703a1bffbd 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3694,7 +3694,7 @@ and a PHI weakening under **strict enforcement** (`enforcement = enforce`, the d | `allow_single_factor_admin_when_exposed` | bool | `false` | permit **single-factor sign-in on an exposed PHI instance** (ADR 0140). With `require_mfa` explicitly off, and the instance exposed — a **non-loopback bind**, a declared TLS-terminating proxy (`[api].tls_terminated_upstream`), **or** a set `[api].trusted_proxies` (a loopback bind behind a proxy re-encrypting to an operator `tls_cert_file`; vault BACKLOG #2251) — a PHI instance under `enforcement = enforce` **refuses to start** (exit 2). Every account with no second factor enrolled, Administrators included, would then sign in over the network with a single factor. The one exception is an OIDC sign-in that carries an amr/acr claim checked while `[auth].oidc_require_mfa_claim` is on. The refusal, its exposure warnings and its AUDIT line name it only when this config has it. The `security_loosenings()` entry describes the switch, not one config, so it always names it. The gate reads at least exposure, `require_mfa` and `enforcement`, and never a tier or account kind. Setting this permits that start; it is recorded in a WARNING-level AUDIT line and the ordinary exposure warning still prints. A **loosening** — `security_loosenings()` reports it. **The exposure test does not consult the browser console** ([BACKLOG #326](BACKLOG.md); ADR 0140 amendment). It did, and that made the arm miss the topology this document recommends: a loopback bind behind a declared terminator with `serve_web_console` left at its default, where the ADR 0143 auto-degrade clears the console flag in place before the gate reads it. The exposed surface that authenticates with one factor is the **JSON operator API**, which the proxy serves whether or not `/ui` is mounted, so the predicate is the bind-and-proxy posture alone and the refusal fires on at least: an off-loopback bind; a declared proxy with the console left default-on; and a declared proxy with `serve_web_console = false`. **This refusal is one of at least two exceptions to the "a new refusal fires only on a new opt-in" scoping rule (another is the ADR 0199 store-login refusal)**, which the `require_memory_encryption_declaration` row below states — by owner ruling of 2026-08-04, recorded in the [ADR 0140](adr/0140-two-acknowledged-production-phi-no-loosen-carve-outs-single-factor-admin-at-exposure-keyless-phi-in-production.md) amendment, which is the single source for why. Nothing new gates it. **One residual is deliberately left open:** an **undeclared** proxy — `web_console_public_address` set with neither `tls_terminated_upstream` nor `trusted_proxies` — does not count as exposed here, because nothing was declared, so exposure would be an *inference*, and an inference must not refuse. It **warns** instead, on its own dedicated arm: on a PHI instance with `require_mfa` explicitly off, startup prints that if that origin is served by an undeclared proxy every account with no second factor enrolled is single-factor over the network, with the same OIDC exception, and this refusal cannot see it. Do **not** read the ADR 0068 §8 undeclared-proxy warning as that control — it is about the `/ui` session cookie and HSTS, and it is suppressed entirely when the ADR 0143 auto-degrade clears the console flag, which the same `web_console_public_address` triggers. **Prefer `require_mfa = true` — and know its scope.** Under the shipped `require_mfa_scope = "every_local_account"` it requires a second factor from **every** account, *not* only Administrators and (since BACKLOG #1144) *not* only local ones, so a non-interactive bearer-token service account becomes MFA-pending and cannot enrol unattended. **With `require_mfa` kept on, there is one remedy.** Set `require_mfa_scope = "administrators"` (itself reported as a loosening, and it leaves every Administrator in scope) — see that row below. **Making it a directory (AD/Kerberos) principal is no longer the other one:** directory identities used to be out of scope under either value, their factor delegated to the directory, and BACKLOG #1144 retired that. **mTLS is not one either.** A `[api].tls_client_cert_identities` mapping does grant a cert-identity that never meets the MFA gate, but that plane is admitted on exactly **one** route (`GET /service/identity`, `require_service_cert`) and carries no session, so an account "moved to mTLS" can read back its own identity and nothing else — it cannot replay, purge, poll status, or do any work a service account exists for. The `[api].tls_client_cert_identities` row above is the authority on that reach. An AD-only deployment is therefore in scope for **all** of its accounts — its directory principals, any local administrator, and any local service accounts | | `allow_unverified_alert_smtp_tls` | bool | `false` | the **acknowledgment** required to start an enforcing PHI instance whose `[alerts]` SMTP hop does not authenticate the relay — i.e. `[alerts].email_use_tls = false` (cleartext) or `[alerts].email_tls_verify = false` (encrypted but accepts any certificate) ([#323](BACKLOG.md)). Covers BOTH shapes deliberately: cleartext is strictly worse than unauthenticated TLS, so gating only the second would hand an operator a bypass onto the worse posture. Without it `serve` refuses to start (exit 2); with it the start is permitted and named in a WARNING-level `AUDIT:` line. An **acknowledgment switch rather than the clamped `MEFOR_ALLOW_INSECURE_TLS` escape** the connectors use, because this cell is constructed outside the `active_hop_posture` scope, where that clamp reads no posture and so cannot carry an acknowledgment (since vault BACKLOG #2354 it refuses there; it used to be inert). A **loosening** — `security_loosenings()` reports it, so it is never silent. It covers a hop with **no login** only: with `[alerts].email_username` set, either shape is refused at load, so the SMTP AUTH password never crosses (vault BACKLOG #3533) | | `allow_over_granted_store_principal` | bool | `false` | the **audited opt-out** from the refusal an over-granted store login earns under `enforcement = enforce` ([ADR 0199](adr/0199-an-over-granted-store-login-refuses-start-under-enforce-with-an-audited-opt-out.md), ASVS 13.2.2). The startup privilege preflight reads the `[store]` login's effective privileges; when it holds more than [`DEPLOY-SERVER-DB.md` §1.1/§1.2](DEPLOY-SERVER-DB.md) prescribes, `serve` refuses to start unless this is set. With it set the start goes ahead, a WARNING-level `AUDIT:` line names the switch, and the `store_privilege_preflight` audit row carries `over_grant_accepted: true`. It lifts that one refusal only: the warning and the `store_privilege_warning` alert still fire, an unobservable probe needs no opt-out (it only warns), and `[store].require_least_privilege = true` outranks it. SQLite never needs it. A **loosening** — `security_loosenings()` reports it. Env: `MEFOR_SECURITY_ALLOW_OVER_GRANTED_STORE_PRINCIPAL` | -| `allow_over_granted_vault_token` | bool | `false` | the **audited opt-out** from the refusal the gravest Vault grants earn under `enforcement = enforce` ([ADR 0216](adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md), BACKLOG #2903, ASVS 13.2.2). At every start `serve` probes each Vault token it uses, and a token holding a grant in the refusing class refuses the start unless this is set; [`SECURITY.md`](SECURITY.md), *What `serve` does with a Vault finding*, defines the two classes. With it set the start goes ahead, a WARNING-level `AUDIT:` line names the switch, and the `vault_privilege_preflight` audit row carries `over_grant_accepted: true`. It lifts that one refusal only: a warning-class finding and a probe stopped by a network failure, a timeout or a 403 only warn, and a probe that failed for any other reason, such as a code defect, refuses under `enforce` whatever this says, except a probe still running at the 150-second bound, which reads as a timeout and only warns, whatever held it up. Under `enforcement = warn` nothing refuses. A **loosening** — `security_loosenings()` reports it. Env: `MEFOR_SECURITY_ALLOW_OVER_GRANTED_VAULT_TOKEN` | +| `allow_over_granted_vault_token` | bool | `false` | the **audited opt-out** from the refusal the gravest Vault grants earn under `enforcement = enforce` ([ADR 0216](adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md), BACKLOG #2903, ASVS 13.2.2). At every start `serve` probes each Vault token it uses, and a token holding a grant in the refusing class refuses the start unless this is set; [`SECURITY.md`](SECURITY.md), *What `serve` does with a Vault finding*, defines the two classes. With it set the start goes ahead, a WARNING-level `AUDIT:` line names the switch, and the `vault_privilege_preflight` audit row carries `over_grant_accepted: true`. It lifts that one refusal only: a warning-class finding and a probe stopped by a network failure, a timeout or a 403 only warn, and a probe that failed for any other reason, such as a code defect, refuses under `enforce` whatever this says. Under `enforcement = warn` nothing refuses. A **loosening** — `security_loosenings()` reports it. Env: `MEFOR_SECURITY_ALLOW_OVER_GRANTED_VAULT_TOKEN` | | `allow_remote_debugging` | bool | `false` | the **named acceptance** that lifts the refusal `serve` and `supervise` make under `enforcement = enforce` to start with the interpreter's remote debugging (PEP 768) on (vault BACKLOG #2700). For a developer's console-script start, never a deployment: the shipped service launches start with the interface off. A **loosening**, reported; a start it lets through writes a WARNING-level `AUDIT:` line. When the refusal fires is stated once, in [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md#remote_debug_enabled-and-remote_debug_unguarded-the-interpreter-accepts-a-script-from-another-process); what the acceptance leaves open and records is in [its own section](SECURITY-LOOSENING.md#allow_remote_debugging--true----start-under-enforce-with-the-interpreters-remote-debugging-on). Env: `MEFOR_SECURITY_ALLOW_REMOTE_DEBUGGING` | | `require_nonstatic_credentials` | bool | `false` | **opt-in static-credential refusal** (ASVS 13.2.1, [BACKLOG #1182](BACKLOG.md)). Off by default, by owner decision (2026-09-23). When `true`, `serve` refuses to start while any backend hop the engine dials presents an unchanging credential or none and is not named in `static_credential_accepted`. The service-settings hops (`[store]`, `[alerts]`, `[auth]`, `[ai]`, `[secrets]`, `[logging]`) are checked before anything starts, and a refusal there exits 2. The connection graph is checked at the first load, where a refusal fails the server's startup, and at every `/config/reload`, where a refused reload leaves the running graph in place. Read once at start: a `/config/reload` judges the new graph against the value the engine started with, so an edit takes effect on restart. The refuse/warn split is `enforcement`, as for `[store].require_managed_identity`. Several hops have **no** compliant credential kind in the product, so with this on they can only run under an opt-out; the full list is in [`CONNECTIONS.md`](CONNECTIONS.md) §*Static credentials on every backend hop*. Not a loosening: it tightens. Env: `MEFOR_SECURITY_REQUIRE_NONSTATIC_CREDENTIALS` | | `static_credential_accepted` | table | `{}` | the audited per-hop opt-outs for `require_nonstatic_credentials`: hop name to reason, e.g. `{ "OB_ACME_REST" = "partner offers HTTP Basic only" }`. Hop names are the ones `messagefoundry check`'s `static-credentials` line and `GET /security/posture` print: an outbound connection's own name, or a name with a prefix (`settings:` for a service-settings hop; `inbound:`, `fhir_lookup:`, `db_lookup:`, `reference:` or `proxy:` for the others). A blank reason is refused at load. Read only while the refusal is on. Then each honoured entry is logged at start by name and reason, never by secret; an entry that matches no hop is logged as doing nothing; and `security_loosenings()` names the set. Read once at start, like the rest of `[security]`: a `/config/reload` does not re-read it, so an added, changed or removed opt-out takes effect on restart | diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index cec5a0a312..cf2a0307f9 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -2311,8 +2311,7 @@ count is above `0` (vault BACKLOG #2613). token shared by two hops or an extra capability on a path the engine calls, and a probe that could not read the token because of a network failure, a timeout or a 403, only warn, so there is nothing for it to lift there. A probe that failed for any other reason, such as a code defect, - refuses under `enforce`, and this switch does not lift that refusal. The exception is a probe - still running at the 150-second bound: it reads as a timeout and only warns, whatever held it up. + refuses under `enforce`, and this switch does not lift that refusal. - **How to turn it off:** remove it, after the token's policy matches the grant [`SECURITY.md`](SECURITY.md) prescribes for that hop. `messagefoundry check-privileges` shows the grant and what `serve` would do with it. diff --git a/docs/SECURITY.md b/docs/SECURITY.md index b4e248a5d9..e276403519 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1191,15 +1191,12 @@ The administrative paths it is asked about are at least these: above. The store key's own path is judged by the Transit-key rule in the next paragraph. On any other path the store hop calls, which uses the key (such as `update` on `transit/decrypt/`), every grant but `read` and `list` is in the refusing class, and those - two warn. A token shared by both hops is judged as the shared-token rule above says instead, - except where the store hop's probe was cut off at the bound below: that reading names none of - the store hop's paths, so such a grant refuses even on a shared token. + two warn. A token shared by both hops is judged as the shared-token rule above says instead. When either hop's reading names no token, whether the two share one is unknown. At least these - leave it unnamed: an unset token, a client that could not be built, a probe cut off at the bound - below before it built its Vault client, and a probe that raised or could not start its thread; - most other probe failures keep it, a probe cut off later included. Then a refusing-class grant on a path the store hop calls, other than the key's own, only - warns, and the hop says why and is marked partial: shared, it would only warn. Under `enforce` - the start is still refused when the store hop's own failure is not one the excused list below + leave it unnamed: an unset token, a client that could not be built, and a probe that raised or + could not start its thread; most other probe failures keep it. Then a refusing-class grant on a + path the store hop calls, other than the key's own, only warns, and the hop says why and is + marked partial: shared, it would only warn. Under `enforce` the start is still refused when the store hop's own failure is not one the excused list below names (a network failure, a timeout or a 403). On a Transit key's own path a `create`, `update`, `patch`, `delete`, `sudo` or `root` grant creates, @@ -1285,7 +1282,7 @@ at that moment. The over-grants above fall in two classes: control, export, backup and restore paths; on a path the store hop calls, only the grants that list names), a grant that creates, rewrites or deletes a Transit key, and any grant but `read` or `list` on a path that uses the store hop's key. That last grant only warns when either hop's - probe could not read its token, as the list above says. Under the shipped + reading names no token, as the list above says. Under the shipped `enforcement = enforce` such a token **refuses to start**. The audited opt-out is `[security].allow_over_granted_vault_token = true`: it logs an `AUDIT:` line, marks the `vault_privilege_preflight` audit row `over_grant_accepted`, and is named on @@ -1302,12 +1299,11 @@ token variable, another Vault error status, and an answer that names no capabili Under `enforce` such a failure **refuses to start**, the audit row names it under `unexcused`, and the opt-out does not lift it. -The probes run side by side. The preflight abandons its wait on a probe still running after 150 -seconds, and that probe reads as a timeout, which only warns, whatever held it up. Its thread is -not stopped: it may run on, and go on calling Vault with the token after the start, for as long as -whatever held it up lasts, and what it reads then is dropped. A token whose `auth/token/lookup-self` is denied (a 403, so only a -warning) cannot name its own policies, so whether it can rewrite them is not asked; its hop says -so. What the preflight read of each token is on `GET /security/posture`, under `vault_privilege`; +The probes run side by side, and `serve` waits for each one to finish: how long a probe takes never +decides its outcome. Only the Vault client's own per-request timeouts limit a probe, as they limit +the store open; a limit on the whole wait was considered and declined (ADR 0216, Amendment B). A +token whose `auth/token/lookup-self` is denied (a 403, so only a warning) cannot name its own +policies, so whether it can rewrite them is not asked; its hop says so. What the preflight read of each token is on `GET /security/posture`, under `vault_privilege`; a channel-scoped reader is shown each hop's state and counts, not its text. There, as in the audit row, the refusing reasons and the detail are cut to a length cap, and `refusing_count` keeps the true count, but nothing marks a reason or detail that was cut. A probe that cannot start its diff --git a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md index 4c05e5a3fc..007a97e8d3 100644 --- a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md +++ b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md @@ -179,15 +179,13 @@ it the notifier, or the logging sink when no notifier is configured. - **Best effort.** A sink that raises is logged and never masks the finding, the audit row or the refusal. -## Amendment B (2026-12-01): the connector-secret token's grants on the store's paths can refuse, and serve's wait on a probe is bounded +## Amendment B (2026-12-01): the connector-secret token's grants on the store's paths can refuse -Vault BACKLOG #4851. Status unchanged: Proposed. The Lander decided both changes under the owner's +Vault BACKLOG #4851. Status unchanged: Proposed. The Lander decided the change under the owner's delegation of 2026-12-01 (US Central), after an adversarial review; the question asked and the owner's answer are in decision record d20261202T053010258-eb19bb. That is a delegated decision, -not an owner ruling. They move in opposite directions. The first tightens: it refuses a grant the -owner's 2026-10-04 line *"Everything else warns, alerts and audits."* puts in the warning class. -The second loosens a control: a probe that hangs for a reason the Decision does not excuse now -warns rather than refuses. The operator-facing statement of both is +not an owner ruling. It tightens: it refuses a grant the owner's 2026-10-04 line *"Everything else +warns, alerts and audits."* puts in the warning class. The operator-facing statement is [SECURITY.md](../SECURITY.md#each-backend-hops-least-privilege-the-engine-probes-the-store-vault-and-ldap); this amendment records the decision. @@ -205,22 +203,20 @@ this amendment records the decision. decrypt path: it now refuses a start under `enforce`, unless `[security].allow_over_granted_vault_token` accepts it (audited), as the gravest grants do. It still only warns in at least these cases: read or list on such a path; a path the other hop - calls when both hops hold this same token and the other hop's probe finished, which the - shared-token check reports; and a non-key + calls when both hops hold this same token, which the shared-token check reports; and a non-key grant while whether the other hop holds this same token is unknown. Unknown means either reading - carries no token reference (`privilege_check.vault_hops`). That includes a store probe ended by - the bound below before it built its Vault client. A store probe ended after that keeps its token - reference (`privilege_probes.VAULT_TOKEN_REF_SINK`), so the grant still refuses, and refuses on - a token both hops hold too, because the ended reading names none of the store hop's paths. -- **Serve's wait on each probe is bounded at 150 seconds** (`vault_preflight.VAULT_PROBE_TIMEOUT_S`), - where before `serve` waited with no bound of its own. Only the wait is bounded: the probe's - thread is not stopped and may go on calling Vault with the token after the start, and - `check-privileges` runs the probes with no bound, so the two can disagree on a slow Vault. A - probe still running at the bound reads as a timeout, which warns. That holds whatever made the - probe hang, not only a network timeout. A probe stuck for another reason, such as a code defect - or a hung read of the token file, now warns and lets an enforcing start go ahead, where the - Decision above refuses any failure that is not a network failure, a timeout or a 403. This is - the loosening. + carries no token reference (`privilege_check.vault_hops`), at least when a token is unset, a + client could not be built, or a probe raised or could not start its thread. +- **Serve still waits for each probe to finish.** The probes now run side by side, each on a + thread of its own off the event loop, and a start cancelled while one runs does not wait on its + thread. A limit on the whole wait, after which a probe still running would read as a timeout and + only warn, was considered and declined: decided by the Lander under the owner's delegation of + 2026-11-29, decision record d20261202T202356290-48e563, which supersedes the probe-wait half of + d20261202T053010258-eb19bb. Such a limit would have turned a probe slow for a reason the Decision + does not excuse, a code defect or a hung read of the token file among them, into a warning, and + a slow probe on a token holding root into a pass under `enforce`. So, as before this amendment, + only the Vault client's own per-request timeouts limit a probe, as they limit the store open, + and elapsed time alone never turns a probe into a reading. The same PR also added to the refusing set this ADR's Decision lists, at least the grants that create, rewrite or delete the hop's own Transit key, more Transit key administration paths and more @@ -229,7 +225,7 @@ key control"*; `privilege_check.VAULT_REFUSING_CLASS` states the class once. The warning-class example *"an extra capability on a path the engine calls"* no longer covers a grant that creates, rewrites or deletes the hop's own Transit key: that grant refuses. -Undo for the first: judge the non-key cross-hop grant as a warning. Before this amendment the +Undo for the cross-hop refusal: judge the non-key cross-hop grant as a warning. Before this amendment the connector-secret token was never asked about the store hop's paths, so the undo makes a new warning rather than restoring an earlier state, and leaves the unknown-sharing downgrade with nothing to soften. diff --git a/docs/adr/README.md b/docs/adr/README.md index b6ef8bba44..dfbd606261 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -238,7 +238,7 @@ what is withheld and what you can request. | [0213](0213-seal-the-secret-rotation-fingerprint-as-a-store-cipher-cell.md) | **Seal the secret-rotation fingerprint as a store-cipher cell** (vault BACKLOG #3472, #3247 item 1) -- each non-DEK `secret_rotation_meta.fingerprint` becomes a store-cipher cell holding a per-row random HMAC key, the value's MAC and the row's class id, AAD-bound to its row and stored behind the `sealed-hmac-sha256-32` tag. `rotate-key`'s `reencrypt_to_active` re-seals it on all three backends, so a store key rotation no longer moves every fingerprint and no start needs the retired key. A cell the engine cannot read, and every pre-#3472 row, keeps its dates: an old row never resets a clock. `vault_transit` stays off (#3473). Supersedes the #2242 re-key rule and removes the DEK-derived fingerprint key. Rejected: carrying retired fingerprint keys forward (A, the fallback), a random per-store key, recomputing in `rotate-key`, a non-rotating derivation | **Accepted (2026-10-26)** -- owner ruling 2026-10-26, in session (batch 343 Manager), option "S: seal as cipher cell"; built with the change | | [0214](0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md) | **A secrets directory and one accessor for the engine's secret-class settings** (vault BACKLOG #2595, step 3, slice A of four) -- one list of the secret-class setting names in `engine_secrets.py`, which the NSSM reading takes its lists from, and one module every moved reader reads through: the file named for the setting in the directory `MEFOR_SECRETS_DIRECTORY` names, else the environment variable, so the directory wins. Moved: both Vault tokens, the `env()` values, the settings-borne secrets including the database password, and the rotation fingerprint. The reader checks the directory's own access list, then each file's, with the key-file check, and refuses at every enforcement setting a broad one, a link (on every platform since its 2026-11-13 amendment; on Windows only before it), a file named for no setting, an empty, non-UTF-8 or oversized file, and any file named for the store key, which stays in its DPAPI key file. Plain files: DPAPI wrapping waits on a spike. Slice A refused nothing that started before it. Rejected: one DPAPI file for every secret, purging the environment, a settings-file location | **Proposed (2026-10-27)** -- built as slice A; merging records it as Proposed and accepts nothing. Slice C (the installer creates the directory; the location stays operator-named) and slice D (the unbuilt provider names removed) built 2026-11-05, per its Amendments. Half of slice B (the NSSM reading refuses every secret-class name in the service's own lists) built 2026-11-11. Amended 2026-11-13: on POSIX the key-file check also judges the owner of the directory or file and the directory that holds it (`docs/CONFIGURATION.md` states the rule), and on Windows the folder that holds the directory is read too, read where the path resolves to since 2026-11-17; neither is a complete check of the directory's surroundings. Amended 2026-11-22: the host key provider's files may take a custody directory of their own. The rest of slice B (refusing such a secret found in the environment elsewhere, owner ruling 2026-10-01) is built for these names in part, 2026-11-24, per the 2026-11-11 amendment's update, which states what it covers. Open: at least whatever of slice B that update leaves, and whether a Windows file is also DPAPI-wrapped. Step 3 is not closed. Severity conditional per CLAUDE.md section 0 | | [0215](0215-the-web-console-calls-the-json-routes-in-process-through-the-asgi-app-so-one-gate-family-authorizes-both-planes.md) | **The web console calls the JSON routes in-process through the ASGI app, so one gate family authorizes both planes** (vault BACKLOG #2603, research step) -- the console stops calling engine handlers through `CoreHandlers` and `AdminHandlers` and sends each a bearer sub-request through the engine's own app, so every JSON gate runs; `get_engine`, `get_gate` and the console's non-sign-in `AuthService` reads go too. The sub-request's scope copies exactly the browser request's `client`, `server`, `scheme`, `http_version` and `root_path` (never `state`, which carries the mTLS peer certificate, and no browser header but a passed body's `Content-Type`), and one in-process `messagefoundry.console` scope extension carries the `/ui` path and a poll flag: no idle-clock touch for a timer-driven poll, every grant row written as a bearer request writes it (volume cut by composite poll routes, not by deduplication), no PHI-budget exemption (a two-resource page costs two, as a bearer client pays). Every console route outside the public and confinement sets makes at least one sub-request (gate-only `GET /auth/check/` routes, one `require(p)` each, for pages with no data); the JSON writes the console calls that are unpaced today gain admin-write pacing. `require_ui` shrinks to a read-only session check, same-origin on writes, and one refusal-to-browser-answer table. Adds an async client and a response-streaming in-process transport to `apiclient` (stock httpx `ASGITransport` sets a loopback client and buffers response bodies), and a policy class per JSON route. Rejected: the proof-object design (the dual-control executors, convergence and DR re-apply run with no request), a stronger parity guard, stock `ASGITransport`, router-only dispatch, grant-row deduplication. Amends ADR 0065 and ADR 0088 | **Accepted (2026-10-30)** -- owner ruling given in session to the batch 459 Manager through AskUserQuestion, "Accept (Recommended)"; the seven build slices go ahead in the build order, slice 7 at any point. The owner also answered two of its open questions, on grant rows for polls and on the grant row's form; the ADR's *To resolve on acceptance* records both. Open: the extra session reads per sub-request, owned by slice 5. ADR 0065 and ADR 0088 carry an *Amended by ADR 0215* note. Amended 2026-11-24 by an appended section (slice 2a: a check route writes the grant row of an audited permission), on the Lander's ruling d20261124T135809520-03bdbe under the owner's delegation of 2026-11-24. No code yet. Severity conditional per CLAUDE.md section 0. *Superseded cell text, kept as a record: "**Proposed (2026-10-29)** -- doc-only research step; no code. Seven build slices named in the ADR. Acceptance is the owner's; four questions open. Severity conditional per CLAUDE.md section 0".* | -| [0216](0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md) | **The gravest Vault token grants refuse start under enforce, with an audited opt-out** (vault BACKLOG #2903, slice A; ASVS 13.2.2) -- owner ruling 2026-10-04 (17:06:09Z UTC). `serve` probes each Vault token it uses at every start, with the `check-privileges` probe and a client from the provider's own constructor, after the store preflight and before any listener binds. The root policy, any grant on an administrative path (including a write of the token's own policies) and a Transit key's `config`, `rotate`, `export` or `backup` refuse start under `[security].enforcement = enforce`; `[security].allow_over_granted_vault_token` is the audited opt-out (an `AUDIT:` line, `over_grant_accepted` on the `vault_privilege_preflight` audit row, a `security_loosenings()` entry). Every other over-grant, and a probe stopped by a network failure, a timeout or a 403, warn and audit; a probe that failed for any other reason, such as a code defect, refuses under `enforce`. `vault_preflight_outcome` states the decision once for `serve` and `check-privileges`. The third recorded exception to "a new refusal fires only on a new opt-in". Rejected: refusing on any over-grant, reusing the store opt-out | **Proposed (2026-10-30)** -- built as slice A; merging records it as Proposed and accepts nothing. Amendment A (2026-11-06) built the alert with its auto-resolving inverse (slice B). Amendment B (2026-12-01, vault BACKLOG #4851) changes the refusing class and the probe wait; read it there rather than the class listed in this row: some connector-secret token grants on the store hop's paths now refuse, more Transit key and administrative paths refuse, and a probe `serve` stops waiting on at 150 s warns whatever made it hang, which loosens the refusal of an unexcused failure. Severity conditional per CLAUDE.md section 0 | +| [0216](0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md) | **The gravest Vault token grants refuse start under enforce, with an audited opt-out** (vault BACKLOG #2903, slice A; ASVS 13.2.2) -- owner ruling 2026-10-04 (17:06:09Z UTC). `serve` probes each Vault token it uses at every start, with the `check-privileges` probe and a client from the provider's own constructor, after the store preflight and before any listener binds. The root policy, any grant on an administrative path (including a write of the token's own policies) and a Transit key's `config`, `rotate`, `export` or `backup` refuse start under `[security].enforcement = enforce`; `[security].allow_over_granted_vault_token` is the audited opt-out (an `AUDIT:` line, `over_grant_accepted` on the `vault_privilege_preflight` audit row, a `security_loosenings()` entry). Every other over-grant, and a probe stopped by a network failure, a timeout or a 403, warn and audit; a probe that failed for any other reason, such as a code defect, refuses under `enforce`. `vault_preflight_outcome` states the decision once for `serve` and `check-privileges`. The third recorded exception to "a new refusal fires only on a new opt-in". Rejected: refusing on any over-grant, reusing the store opt-out | **Proposed (2026-10-30)** -- built as slice A; merging records it as Proposed and accepts nothing. Amendment A (2026-11-06) built the alert with its auto-resolving inverse (slice B). Amendment B (2026-12-01, vault BACKLOG #4851) changes the refusing class; read it there rather than the class listed in this row: some connector-secret token grants on the store hop's paths now refuse, and more Transit key and administrative paths refuse. `serve` still waits for each probe to finish; a limit on that wait was considered and declined (decision record d20261202T202356290-48e563). Severity conditional per CLAUDE.md section 0 | | [0217](0217-an-unverifiable-transit-row-seal-is-denied-like-a-failed-one-and-the-ad-reconciler-ends-sessions-rather-than-holding.md) | **An unverifiable Transit row seal is denied like a failed one, and the AD reconciler ends sessions rather than holding** (vault BACKLOG #4739, design for #2592's `vault_transit` limb; engine PR 2565 is the parked reference) -- four answers to a seal check: holds, forged (`valid: false` or a malformed seal), unverifiable (a `verify` HTTP 400 while the fixed-input probe works, whatever version it names) and outage. Unverifiable denies the row as forged does (never tombstoning or raw-deleting one on its own), under `integrity.authority_seal_unverifiable` and a capped per-row subject, because a database writer can plant an unheld key version. Transit is sent a fixed-length SHA-256 of the seal input, so no row can force an outage by size. AD sign-in and the certificate leg refuse on an unverifiable map; on a map that does not hold, forged included, the reconciler writes no role row and ends the sessions of accounts whose groups moved since a new sealed `users.directory_groups_digest`, under the unchanged mass-revoke brake, after first trying `main`'s own set; every unverifiable or forged map pages each pass under its own uncapped subject. Write refusals raise `RowSealError` or its sibling `RowSealUnverifiableError` under a catch census, and every catch site audits; a session end never rolls back. Seal-state and outage-refused sign-ins write their own actions and do not count toward the sign-in burst. An owner-rulings list heads the ADR; residuals named: no cross-store binding until #3411, no rollback detection until #2592 step 7, 60 s of cached trust after a version retirement. Rejected: a lagging-node outage case, holding reconcile diffs, ending the sessions outside the brake, re-judging offboarding on a tripped pass, applying demotions from an empty map, re-sealing a map nobody verified | **Accepted (2026-11-06)** by owner ruling on every entry -- design only, no code yet; every answer is a control decision. Severity conditional per CLAUDE.md section 0 | ## Retired allocations — numbers taken but never authored diff --git a/messagefoundry/privilege_check.py b/messagefoundry/privilege_check.py index 319f588c0d..b8a273e4e4 100644 --- a/messagefoundry/privilege_check.py +++ b/messagefoundry/privilege_check.py @@ -460,10 +460,9 @@ def vault_hop( """Judge one token's self-reading against what the engine calls with it. ``unmatched`` names each other hop whose reading, or this one, carries no token reference (at - least: the token was unset, the client could not be built, the probe hit the bound before it - named its token, raised past :func:`~messagefoundry.privilege_probes.read_vault_token` or found - no thread), so whether it holds this same token is unknown. Most failures inside the probe keep - the reference. A grant on a path another hop calls, other than on a Transit key's own path, then + least: the token was unset, the client could not be built, or the probe raised past + :func:`~messagefoundry.privilege_probes.read_vault_token` or found no thread), so whether it + holds this same token is unknown. Most failures inside the probe keep the reference. A grant on a path another hop calls, other than on a Transit key's own path, then warns rather than refuses, says why, and marks the hop ``partial``: had the token been compared and found shared, the grant would be that hop's own and warn, so a refusal would rest on a comparison never made (vault BACKLOG #4851). Not shared, the same grant refuses once both probes @@ -670,8 +669,8 @@ def vault_hops( """Judge every Vault hop, each against the union of grants of every hop that holds its token. Two hops hold one token when both readings carry the same token reference (``same_token_as``), - taken before lookup-self, so a probe ended by the bound can match too. A reading that could not - name its token is judged alone, and it also leaves every other hop's sharing unknown, which + taken before lookup-self, so a probe whose lookup-self failed can match too. A reading that + could not name its token is judged alone, and it also leaves every other hop's sharing unknown, which turns another hop's refusal for a grant on a path only the unnamed hop calls, other than a Transit key's own path, into a warning (``unmatched`` in :func:`vault_hop`).""" hops: list[HopPrivilege] = [] diff --git a/messagefoundry/privilege_probes.py b/messagefoundry/privilege_probes.py index 955233d064..f71c52ccd4 100644 --- a/messagefoundry/privilege_probes.py +++ b/messagefoundry/privilege_probes.py @@ -38,7 +38,6 @@ import logging import socket from collections.abc import Callable, Iterable, Mapping -from contextvars import ContextVar from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any from urllib.parse import urlsplit @@ -63,7 +62,6 @@ from messagefoundry.privilege_check import VaultConsumer __all__ = [ - "VAULT_TOKEN_REF_SINK", "VaultTokenReading", "excused_failure", "preload_vault_probe_imports", @@ -113,15 +111,6 @@ def same_token_as(self, other: VaultTokenReading) -> bool: return self.token_ref is not None and self.token_ref == other.token_ref -#: Where :func:`read_vault_token` hands a token's reference once it has built the hop's client, -#: before any network call (vault BACKLOG #4851). The startup preflight sets it for each probe it bounds, so a -#: probe the bound ends still names its token, and another hop's grant is judged against it rather -#: than as a sharing nobody could tell. -VAULT_TOKEN_REF_SINK: ContextVar[Callable[[str], None] | None] = ContextVar( - "vault_token_ref_sink", default=None -) - - def _problem(text: str) -> str: """Log one probe problem and return it. The text is already secret-free (:func:`_why`), and is logged with every character in ``CONTROL_CATEGORIES`` escaped visibly, by the log's own @@ -361,8 +350,6 @@ def why(exc: BaseException) -> str: for p in problems: _problem(p) token_ref = hashlib.sha256(named.encode("utf-8")).hexdigest() - if (sink := VAULT_TOKEN_REF_SINK.get()) is not None: - sink(token_ref) from messagefoundry.config.tls_policy import InsecureHopRefused diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index 6cb055a4eb..7678019263 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -13,8 +13,8 @@ such as the Transit cipher, goes on using the token it read; a token replaced after this read is judged only at the next start. It judges the readings with :func:`messagefoundry.privilege_check.vault_hops`. The -probes run side by side, each bounded by :data:`VAULT_PROBE_TIMEOUT_S`, and the judged hops are -kept for ``GET /security/posture``. +probes run side by side, the start waits for each to finish, and the judged hops are kept for +``GET /security/posture``. **What it refuses is** :func:`~messagefoundry.privilege_check.vault_preflight_outcome` **and nothing else**, which ADR 0216 and ``docs/SECURITY.md`` (*What serve does with a Vault finding*) describe: @@ -66,7 +66,6 @@ vault_refusal_reason, ) from messagefoundry.privilege_probes import ( - VAULT_TOKEN_REF_SINK, VaultTokenReading, preload_vault_probe_imports, unexcused_cause, @@ -103,14 +102,6 @@ _AUDIT_REFUSING_LIMIT = 20 _AUDIT_REASON_LIMIT = 300 -#: How long, in seconds, the preflight waits for each Vault probe (vault BACKLOG #4851). The probes -#: run side by side, so this is about the longest a start waits on them all. Each probe sends two -#: requests on a client with hvac's 30-second default, which requests applies to the connect and -#: to each read apart, so a Vault that answers within those limits finishes inside 2 x (30 + 30) -#: seconds; the rest is margin. The bound ends what those limits do not, at least a name that does -#: not resolve and a reply that trickles in. A probe it ends reads as a timeout, which only warns. -VAULT_PROBE_TIMEOUT_S = 150.0 - def capped_refusing(hop: HopPrivilege) -> list[str]: """The hop's refusing reasons as the audit row and ``GET /security/posture`` keep them: at most @@ -205,41 +196,36 @@ def _probe_one( async def _probe_all( - consumers: list[VaultConsumer], - probe: Callable[[VaultConsumer], VaultTokenReading], - timeout: float, + consumers: list[VaultConsumer], probe: Callable[[VaultConsumer], VaultTokenReading] ) -> list[VaultTokenReading]: - """Every consumer's reading, the probes run side by side, each off the event loop and each - bounded by ``timeout`` seconds (vault BACKLOG #4851). A probe still running at the bound reads - as a timeout, which the owner ruling of 2026-10-04 lets only warn; it keeps the token reference - the probe named before the bound, so another hop's grant is still judged against it. Its thread - cannot be stopped and runs on until the client's own request timeouts end it, and its reading - is dropped. It is a daemon thread of its own, not the loop's default executor, so neither the - loop's shutdown nor the interpreter's exit waits on it.""" + """Every consumer's reading, the probes run side by side, each off the event loop (vault + BACKLOG #4851). The start waits for every probe to finish, as it did when they ran one after + the other: no elapsed time alone turns a probe into a reading (decision + d20261202T202356290-48e563). Nothing here ends a probe early: only the client's own + per-request timeouts limit it, as they limit the store open. Each probe runs on a daemon + thread of its own, not the loop's default executor, so a start cancelled while a probe runs + does not wait on it, nor does the interpreter's exit.""" loop = asyncio.get_running_loop() # The probes import their providers lazily. Done here, once, before any probe thread starts, - # so the probe threads do not import those modules side by side, and one abandoned at the - # bound is not part way through importing one of them (vault BACKLOG #4851). This runs in the - # startup preflight, before any listener binds. + # so the probe threads do not import those modules side by side (vault BACKLOG #4851). This + # runs in the startup preflight, before any listener binds. preload_vault_probe_imports() - async def bounded(consumer: VaultConsumer) -> VaultTokenReading: + async def one(consumer: VaultConsumer) -> VaultTokenReading: done: asyncio.Future[VaultTokenReading] = loop.create_future() + # Under the caller's context, as asyncio.to_thread would run it. context = contextvars.copy_context() - named: list[str] = [] - context.run(VAULT_TOKEN_REF_SINK.set, named.append) def deliver(reading: VaultTokenReading) -> None: - if not done.done(): # cancelled by the bound, so nobody reads it + if not done.done(): # the start was cancelled, so nobody reads it done.set_result(reading) def run() -> None: try: - # Under the caller's context, as asyncio.to_thread would run it. reading = context.run(_probe_one, consumer, probe) except BaseException as exc: # noqa: BLE001 - _probe_one catches Exception; this is the rest - # Delivered rather than lost, so it is not read as a timeout, which only warns: a - # BaseException is not one the ruling excuses, so it refuses under enforce. + # Delivered rather than lost, so the start is not left waiting: a BaseException is + # not one the ruling excuses, so it refuses under enforce. name = type(exc).__name__ log.warning( "vault privilege preflight: %s: the probe raised %s", consumer.hop, name @@ -249,7 +235,7 @@ def run() -> None: ) try: loop.call_soon_threadsafe(deliver, reading) - except RuntimeError: # the loop closed after the bound gave up on this probe + except RuntimeError: # the loop closed after a cancelled start stopped waiting log.debug( "vault privilege preflight: %s finished after its loop closed", consumer.hop ) @@ -265,14 +251,9 @@ def run() -> None: problem = f"the probe could not start a thread ({type(exc).__name__})" log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) return VaultTokenReading(problems=(problem,), unexcused=(type(exc).__name__,)) - try: - return await asyncio.wait_for(done, timeout=timeout) - except TimeoutError: - problem = f"the probe did not finish within {timeout:g}s (a timeout)" - log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) - return VaultTokenReading(problems=(problem,), token_ref=named[0] if named else None) + return await done - return list(await asyncio.gather(*(bounded(c) for c in consumers))) + return list(await asyncio.gather(*(one(c) for c in consumers))) async def run_vault_privilege_preflight( @@ -283,7 +264,6 @@ async def run_vault_privilege_preflight( over_grant_accepted: bool, probe: Callable[[VaultConsumer], VaultTokenReading], alert_sink: VaultPrivilegeAlertSink | None = None, - probe_timeout: float = VAULT_PROBE_TIMEOUT_S, ) -> list[HopPrivilege]: """Probe every Vault token ``settings`` puts to use, report each, and refuse where :func:`~messagefoundry.privilege_check.vault_preflight_outcome` says so. @@ -302,7 +282,7 @@ async def run_vault_privilege_preflight( consumers = vault_consumers(settings) if not consumers: return [] - readings = await _probe_all(consumers, probe, probe_timeout) + readings = await _probe_all(consumers, probe) hops = vault_hops(consumers, readings) outcomes = [ vault_preflight_outcome(hop, enforcing=enforcing, over_grant_accepted=over_grant_accepted) diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index dc05363bb1..2a0da9469d 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -6,8 +6,8 @@ have started on a Vault token able to turn off an audit device, seal Vault, read its storage raw, start a root-token generation or a rekey, delete or restore the store key, trim it or export one version of it, and on a connector-secret token able to export the store key. ``GET -/security/posture`` would not have said what the preflight read, and a probe that hung would have -held the start for as long as hvac let it. +/security/posture`` would not have said what the preflight read. The preflight still waits for each +probe, as it did before (decision d20261202T202356290-48e563), and runs them side by side. Every Vault answer is MOCKED by the fake client the ``check-privileges`` tests use, and every token is a synthetic string. No test opens a socket. @@ -15,9 +15,9 @@ from __future__ import annotations +import asyncio import json import threading -import time from pathlib import Path from types import SimpleNamespace from typing import Any @@ -237,77 +237,193 @@ def test_a_store_probe_with_no_token_still_refuses_a_grant_on_its_key() -> None: assert any(r.startswith(f"{key} grants delete") for r in hop.refusing) -async def test_a_timed_out_store_probe_does_not_refuse_the_secrets_decrypt_grant( +# --- a slow probe is waited for: elapsed time alone never makes a reading ---------------------- +# +# The preflight waits for each probe as it did before vault BACKLOG #4851, so a slow probe is +# judged on what it read (decision d20261202T202356290-48e563). "Slow" here is a lookup-self held +# on an event a timer sets: the probe has named its token and waits on Vault's first answer. + + +def _released_soon() -> threading.Event: + """An event a timer sets half a second on, so a probe waiting on it is slow, never stuck.""" + release = threading.Event() + timer = threading.Timer(0.5, release.set) + timer.daemon = True + timer.start() + return release + + +def _slow(vault: _FakeVault, release: threading.Event) -> Any: + """``vault`` with its lookup-self held until ``release`` is set.""" + + def lookup_self() -> dict[str, Any]: + assert release.wait(10) + return vault.auth.token.lookup_self() + + token = SimpleNamespace(lookup_self=lookup_self) + return SimpleNamespace(auth=SimpleNamespace(token=token), sys=vault.sys) + + +def _shared_caps() -> dict[str, list[str]]: + """One token's grants, enough for both hops.""" + return _least_caps() | {_KV_PATH: ["read"]} + + +def _two_hops( monkeypatch: pytest.MonkeyPatch, -) -> None: + *, + slow_hop: str, + store_vault: _FakeVault, + secrets_vault: _FakeVault, + store_token: str = _TOKEN, +) -> Any: + """A probe for the store and secrets hops, the one named ``slow_hop`` slow. The secrets token is + asked about the store's paths, as :func:`~messagefoundry.privilege_probes.probe_vault` asks it + when both hops name one Vault.""" monkeypatch.setattr(vault_preflight, "vault_consumers", lambda settings: [_STORE, _KV]) - decrypt = f"transit/decrypt/{_KEK}" - release = threading.Event() + release = _released_soon() def probe(consumer: VaultConsumer) -> VaultTokenReading: - if consumer.hop == "vault.store": - release.wait(10) - return VaultTokenReading() - vault = _FakeVault(caps={_KV_PATH: ["read"], decrypt: ["update"]}) - return _kv_reading(vault, other_required=lambda: [f"transit/keys/{_KEK}", decrypt]) + store = consumer.hop == "vault.store" + vault: Any = store_vault if store else secrets_vault + if consumer.hop == slow_hop: + vault = _slow(vault, release) + if store: + return _reading(vault, token=store_token) + return _kv_reading(vault, other_required=lambda: list(_least_caps())) - try: - hops = await run_vault_privilege_preflight( + return probe + + +async def test_a_slow_store_probe_holding_root_refuses_under_enforce() -> None: + vault = _slow(_FakeVault(caps=_least_caps(), policies=("root",)), _released_soon()) + store = _AuditStore() + with pytest.raises(VaultPrivilegeError, match="vault.store"): + await run_vault_privilege_preflight( _VAULT_SETTINGS, - _AuditStore(), + store, enforcing=True, over_grant_accepted=False, - probe=probe, - probe_timeout=0.2, + probe=_probe(vault), ) - finally: - release.set() - store, secrets = hops - assert "did not finish within 0.2s" in store.detail - assert secrets.refusing == () and secrets.state is HopState.OVER_GRANTED - assert "is unknown" in secrets.detail + [(_, row)] = store.audits + assert row["state"] == "over_granted" and row["refused"] is True -async def test_a_store_probe_ended_by_the_bound_keeps_its_token_and_the_refusal_holds( +async def test_one_token_with_a_slow_store_probe_starts_with_a_warning( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The shared-token case the owner ruling lets only warn, the store's paths being that same + token's own: no refusal on either hop, and no text says the store calls them with another.""" + probe = _two_hops( + monkeypatch, + slow_hop="vault.store", + store_vault=_FakeVault(caps=_shared_caps()), + secrets_vault=_FakeVault(caps=_shared_caps()), + ) + store = _AuditStore() + hops = await run_vault_privilege_preflight( + _VAULT_SETTINGS, store, enforcing=True, over_grant_accepted=False, probe=probe + ) + assert [h.refusing for h in hops] == [(), ()] + assert [h.state for h in hops] == [HopState.OVER_GRANTED, HopState.OVER_GRANTED] + assert [row["refused"] for _, row in store.audits] == [False, False] + for hop in hops: + assert "only with another hop's token" not in hop.detail + assert "only with that hop's token" not in hop.detail + assert "the same token serves vault.store" in hops[1].detail + + +async def test_one_token_with_a_slow_secrets_probe_never_reads_the_store_clean( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The secrets hop's grants are the same token's, so the store hop carries them as a warning + and never fires ``vault_privilege_clean``, which could resolve an open warning.""" + from tests.test_vault_privilege_preflight import _RecordingSink + + probe = _two_hops( + monkeypatch, + slow_hop="vault.secrets", + store_vault=_FakeVault(caps=_shared_caps()), + secrets_vault=_FakeVault(caps=_shared_caps()), + ) + sink = _RecordingSink() + hops = await run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=probe, + alert_sink=sink, + ) + assert hops[0].hop == "vault.store" and hops[0].state is HopState.OVER_GRANTED + assert "vault:store" not in sink.cleared + assert "vault:store" in [e["name"] for e in sink.events] + + +async def test_distinct_tokens_refuse_the_decrypt_grant_after_a_slow_store_probe( monkeypatch: pytest.MonkeyPatch, ) -> None: - """``read_vault_token`` names its token once it has built the client, before any network - call, so a store probe the bound ends there still names it, and a secrets token that differs - refuses the decrypt grant.""" - monkeypatch.setattr(vault_preflight, "vault_consumers", lambda settings: [_STORE, _KV]) decrypt = f"transit/decrypt/{_KEK}" - release = threading.Event() - hung = SimpleNamespace( - auth=SimpleNamespace(token=SimpleNamespace(lookup_self=lambda: release.wait(10) and {})) + probe = _two_hops( + monkeypatch, + slow_hop="vault.store", + store_vault=_FakeVault(caps=_least_caps()), + secrets_vault=_FakeVault(caps={_KV_PATH: ["read"], decrypt: ["update"]}), + store_token="synthetic-store-token", ) + store = _AuditStore() + with pytest.raises(VaultPrivilegeError, match="vault.secrets"): + await run_vault_privilege_preflight( + _VAULT_SETTINGS, store, enforcing=True, over_grant_accepted=False, probe=probe + ) + rows = {detail["hop"]: detail for _, detail in store.audits} + assert rows["vault.store"]["state"] == "clean" and rows["vault.store"]["refused"] is False + assert any(r.startswith(f"{decrypt} grants update") for r in rows["vault.secrets"]["refusing"]) - def probe(consumer: VaultConsumer) -> VaultTokenReading: - if consumer.hop == "vault.store": - return read_vault_token( - lambda: "synthetic-store-token", - lambda: _VAULT_ADDR, - lambda a, t: hung, - lambda: {decrypt: frozenset({"update"})}, - ) - vault = _FakeVault(caps={_KV_PATH: ["read"], decrypt: ["update"]}) - return _kv_reading(vault, other_required=lambda: [f"transit/keys/{_KEK}", decrypt]) +async def test_one_token_with_delete_on_the_kek_refuses_after_a_slow_store_probe( + monkeypatch: pytest.MonkeyPatch, +) -> None: + key = f"transit/keys/{_KEK}" + caps = _shared_caps() | {key: ["delete", "read"]} + probe = _two_hops( + monkeypatch, + slow_hop="vault.store", + store_vault=_FakeVault(caps=caps), + secrets_vault=_FakeVault(caps=caps), + ) store = _AuditStore() - try: - with pytest.raises(VaultPrivilegeError, match="vault.secrets"): - await run_vault_privilege_preflight( - _VAULT_SETTINGS, - store, - enforcing=True, - over_grant_accepted=False, - probe=probe, - probe_timeout=2.0, - ) - finally: - release.set() + with pytest.raises(VaultPrivilegeError, match="vault.store"): + await run_vault_privilege_preflight( + _VAULT_SETTINGS, store, enforcing=True, over_grant_accepted=False, probe=probe + ) + rows = {detail["hop"]: detail for _, detail in store.audits} + assert any(r.startswith(f"{key} grants delete") for r in rows["vault.store"]["refusing"]) + + +async def test_distinct_tokens_refuse_when_the_slow_store_probe_ends_in_a_network_failure( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The store probe named its token before the network failed, so the secrets token is still + compared with it, and the decrypt grant refuses; the network failure itself only warns.""" + decrypt = f"transit/decrypt/{_KEK}" + down = ConnectionError("vault.invalid") + probe = _two_hops( + monkeypatch, + slow_hop="vault.store", + store_vault=_FakeVault(lookup_error=down, caps_error=down), + secrets_vault=_FakeVault(caps={_KV_PATH: ["read"], decrypt: ["update"]}), + store_token="synthetic-store-token", + ) + store = _AuditStore() + with pytest.raises(VaultPrivilegeError, match="vault.secrets"): + await run_vault_privilege_preflight( + _VAULT_SETTINGS, store, enforcing=True, over_grant_accepted=False, probe=probe + ) rows = {detail["hop"]: detail for _, detail in store.audits} - assert "did not finish within 2s" in rows["vault.store"]["detail"] - assert rows["vault.store"]["refused"] is False + assert rows["vault.store"]["state"] == "unobservable" + assert rows["vault.store"]["unexcused"] == [] and rows["vault.store"]["refused"] is False assert any(r.startswith(f"{decrypt} grants update") for r in rows["vault.secrets"]["refusing"]) @@ -486,54 +602,57 @@ async def test_the_audit_row_caps_the_refusing_reasons() -> None: assert all(len(r) <= 300 for r in detail["refusing"]) -# --- the probes are bounded and run side by side ----------------------------------------------- +# --- the probes run side by side, off the event loop ------------------------------------------- -async def test_a_probe_raising_a_base_exception_refuses_rather_than_timing_out() -> None: +async def test_a_probe_raising_a_base_exception_refuses() -> None: + """Delivered rather than lost: a lost reading would leave the start waiting, which the + ``wait_for`` here turns into a failure instead of a hung test.""" + class Stop(BaseException): pass def stop(consumer: VaultConsumer) -> VaultTokenReading: raise Stop - started = time.monotonic() with pytest.raises(VaultPrivilegeError, match="Stop"): - await run_vault_privilege_preflight( - _VAULT_SETTINGS, - _AuditStore(), - enforcing=True, - over_grant_accepted=False, - probe=stop, - probe_timeout=30, + await asyncio.wait_for( + run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=stop, + ), + 10, ) - assert time.monotonic() - started < 10 -async def test_a_probe_that_hangs_is_cut_off_and_only_warns() -> None: +async def test_a_cancelled_start_does_not_wait_on_a_probe_thread() -> None: + """The probe thread cannot be stopped, so a cancelled start returns while it runs on; it is a + daemon thread, so neither the loop's shutdown nor the interpreter's exit waits on it.""" + started = threading.Event() release = threading.Event() def hang(consumer: VaultConsumer) -> VaultTokenReading: + started.set() release.wait(10) return VaultTokenReading() - store = _AuditStore() - started = time.monotonic() - try: - hops = await run_vault_privilege_preflight( - _VAULT_SETTINGS, - store, - enforcing=True, - over_grant_accepted=False, - probe=hang, - probe_timeout=0.2, + task = asyncio.create_task( + run_vault_privilege_preflight( + _VAULT_SETTINGS, _AuditStore(), enforcing=True, over_grant_accepted=False, probe=hang ) + ) + try: + assert await asyncio.to_thread(started.wait, 5) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(task, 5) + probes = [t for t in threading.enumerate() if t.name == "vault-privilege-probe-vault.store"] + assert any(t.is_alive() and t.daemon for t in probes) finally: release.set() - assert time.monotonic() - started < 5 - [hop] = hops - assert hop.state is HopState.UNOBSERVABLE and hop.unexcused == () - assert "did not finish within 0.2s" in hop.detail - assert store.audits[0][1]["refused"] is False async def test_the_probes_run_side_by_side(monkeypatch: pytest.MonkeyPatch) -> None: @@ -634,10 +753,6 @@ def test_the_preload_imports_what_it_can_and_never_raises( assert "colorsys" in sys.modules -def test_the_default_bound_is_finite() -> None: - assert 0 < vault_preflight.VAULT_PROBE_TIMEOUT_S < 600 - - # --- the result reaches GET /security/posture -------------------------------------------------- From 71d8d9f410df04490a5975f73b517777a2818a2d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 15:00:44 -0600 Subject: [PATCH 22/31] Vault preflight: a clock-jump control for the no-bound test, and docs on what still holds a start The root-token test now moves the event loop's clock far ahead while the probe is held, so a limit on the wait of any length would fire and the test fails; it fails on the held head with its 150 s bound. Docs and the _probe_all docstring now say the per-request timeouts do not end every hang, and that a cancelled start's probe thread may go on calling Vault until the probe ends. Stale "did not finish" fixture text and docstring wrapping fixed. Review round 1 on PR 3553, Lander hold 7357681986. Vault BACKLOG #4851. Verified-by: tests --- docs/SECURITY.md | 19 +++++--- ...t-under-enforce-with-an-audited-opt-out.md | 10 +++-- messagefoundry/privilege_check.py | 11 ++--- messagefoundry/vault_preflight.py | 8 ++-- tests/test_vault_privilege_preflight_4851.py | 45 +++++++++++++------ 5 files changed, 61 insertions(+), 32 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index e276403519..af2a34208d 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1196,8 +1196,9 @@ The administrative paths it is asked about are at least these: leave it unnamed: an unset token, a client that could not be built, and a probe that raised or could not start its thread; most other probe failures keep it. Then a refusing-class grant on a path the store hop calls, other than the key's own, only warns, and the hop says why and is - marked partial: shared, it would only warn. Under `enforce` the start is still refused when the store hop's own failure is not one the excused list below - names (a network failure, a timeout or a 403). + marked partial: shared, it would only warn. Under `enforce` the start is still refused when the + store hop's own failure is not one the excused list below names (a network failure, a timeout + or a 403). On a Transit key's own path a `create`, `update`, `patch`, `delete`, `sudo` or `root` grant creates, rewrites or deletes the key, and is in the refusing class. Any other grant there that the engine @@ -1299,12 +1300,16 @@ token variable, another Vault error status, and an answer that names no capabili Under `enforce` such a failure **refuses to start**, the audit row names it under `unexcused`, and the opt-out does not lift it. -The probes run side by side, and `serve` waits for each one to finish: how long a probe takes never -decides its outcome. Only the Vault client's own per-request timeouts limit a probe, as they limit -the store open; a limit on the whole wait was considered and declined (ADR 0216, Amendment B). A +The probes run side by side, and `serve` waits for each one to finish; the preflight never turns a +probe into a timeout by itself. A limit on the whole wait was considered and declined (ADR 0216, +Amendment B). Only the Vault client's own per-request timeouts end a request, as they do for the +store open, and they do not end everything: at least a name that does not resolve, a reply that +trickles in, or a hung read of the token file holds the start, before any listener binds, for as +long as it lasts. If a start is cancelled while a probe runs, the start does not wait for it, but +the probe's thread runs on and may go on calling Vault with the token until the probe ends. A token whose `auth/token/lookup-self` is denied (a 403, so only a warning) cannot name its own -policies, so whether it can rewrite them is not asked; its hop says so. What the preflight read of each token is on `GET /security/posture`, under `vault_privilege`; -a channel-scoped reader is shown each hop's state and counts, not its text. There, as in the audit +policies, so whether it can rewrite them is not asked; its hop says so. What the preflight read of +each token is on `GET /security/posture`, under `vault_privilege`; a channel-scoped reader is shown each hop's state and counts, not its text. There, as in the audit row, the refusing reasons and the detail are cut to a length cap, and `refusing_count` keeps the true count, but nothing marks a reason or detail that was cut. A probe that cannot start its thread reads as not observed: it warns under `warn` and, being no network failure, timeout or 403, diff --git a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md index 007a97e8d3..1a979757ef 100644 --- a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md +++ b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md @@ -208,15 +208,17 @@ this amendment records the decision. carries no token reference (`privilege_check.vault_hops`), at least when a token is unset, a client could not be built, or a probe raised or could not start its thread. - **Serve still waits for each probe to finish.** The probes now run side by side, each on a - thread of its own off the event loop, and a start cancelled while one runs does not wait on its - thread. A limit on the whole wait, after which a probe still running would read as a timeout and + thread of its own off the event loop. A start cancelled while one runs does not wait on its + thread, which runs on and may go on calling Vault with the token until the probe ends. A limit on the whole wait, after which a probe still running would read as a timeout and only warn, was considered and declined: decided by the Lander under the owner's delegation of 2026-11-29, decision record d20261202T202356290-48e563, which supersedes the probe-wait half of d20261202T053010258-eb19bb. Such a limit would have turned a probe slow for a reason the Decision does not excuse, a code defect or a hung read of the token file among them, into a warning, and a slow probe on a token holding root into a pass under `enforce`. So, as before this amendment, - only the Vault client's own per-request timeouts limit a probe, as they limit the store open, - and elapsed time alone never turns a probe into a reading. + elapsed time alone never turns a probe into a reading. Only the Vault client's own per-request + timeouts end a request, as they do for the store open, and they do not end everything: at least + a name that does not resolve, a reply that trickles in, or a hung read of the token file holds + the start for as long as it lasts. The same PR also added to the refusing set this ADR's Decision lists, at least the grants that create, rewrite or delete the hop's own Transit key, more Transit key administration paths and more diff --git a/messagefoundry/privilege_check.py b/messagefoundry/privilege_check.py index b8a273e4e4..e1667c62fb 100644 --- a/messagefoundry/privilege_check.py +++ b/messagefoundry/privilege_check.py @@ -462,8 +462,9 @@ def vault_hop( ``unmatched`` names each other hop whose reading, or this one, carries no token reference (at least: the token was unset, the client could not be built, or the probe raised past :func:`~messagefoundry.privilege_probes.read_vault_token` or found no thread), so whether it - holds this same token is unknown. Most failures inside the probe keep the reference. A grant on a path another hop calls, other than on a Transit key's own path, then - warns rather than refuses, says why, and marks the hop ``partial``: had the token been compared + holds this same token is unknown. Most failures inside the probe keep the reference. A grant + on a path another hop calls, other than on a Transit key's own path, then warns rather than + refuses, says why, and marks the hop ``partial``: had the token been compared and found shared, the grant would be that hop's own and warn, so a refusal would rest on a comparison never made (vault BACKLOG #4851). Not shared, the same grant refuses once both probes name their tokens, so whether it refuses still turns on whether the other hop's probe named its @@ -670,9 +671,9 @@ def vault_hops( Two hops hold one token when both readings carry the same token reference (``same_token_as``), taken before lookup-self, so a probe whose lookup-self failed can match too. A reading that - could not name its token is judged alone, and it also leaves every other hop's sharing unknown, which - turns another hop's refusal for a grant on a path only the unnamed hop calls, other than a - Transit key's own path, into a warning (``unmatched`` in :func:`vault_hop`).""" + could not name its token is judged alone, and it also leaves every other hop's sharing + unknown, which turns another hop's refusal for a grant on a path only the unnamed hop calls, + other than a Transit key's own path, into a warning (``unmatched`` in :func:`vault_hop`).""" hops: list[HopPrivilege] = [] for consumer, reading in zip(consumers, readings, strict=True): others = [ diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index 7678019263..e99cdb62dc 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -202,9 +202,11 @@ async def _probe_all( BACKLOG #4851). The start waits for every probe to finish, as it did when they ran one after the other: no elapsed time alone turns a probe into a reading (decision d20261202T202356290-48e563). Nothing here ends a probe early: only the client's own - per-request timeouts limit it, as they limit the store open. Each probe runs on a daemon - thread of its own, not the loop's default executor, so a start cancelled while a probe runs - does not wait on it, nor does the interpreter's exit.""" + per-request timeouts end a request, as they do for the store open, and a hang they do not end, + such as a name that does not resolve or a reply that trickles in, holds the start. Each probe + runs on a daemon thread of its own, not the loop's default executor, so a start cancelled + while a probe runs does not wait on it, nor does the interpreter's exit; the thread runs on, + and may go on calling Vault with the token, until the probe ends.""" loop = asyncio.get_running_loop() # The probes import their providers lazily. Done here, once, before any probe thread starts, # so the probe threads do not import those modules side by side (vault BACKLOG #4851). This diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index 2a0da9469d..ebd6e9e1ab 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -205,7 +205,7 @@ def _unread_store_and_secrets(store_token: str | None) -> list[Any]: """The store's reading with ``store_token`` as its token reference, and a secrets reading on another token that can decrypt with the store key.""" decrypt = f"transit/decrypt/{_KEK}" - store = VaultTokenReading(problems=("the probe did not finish",), token_ref=store_token) + store = VaultTokenReading(problems=("the token could not be read",), token_ref=store_token) vault = _FakeVault(caps={_KV_PATH: ["read"], decrypt: ["update"]}) secrets = _kv_reading(vault, other_required=lambda: [f"transit/keys/{_KEK}", decrypt]) return vault_hops([_STORE, _KV], [store, secrets]) @@ -213,7 +213,7 @@ def _unread_store_and_secrets(store_token: str | None) -> list[Any]: def test_a_store_probe_with_no_token_leaves_the_decrypt_grant_warning() -> None: """Whether the two hops share a token is unknown, and shared it would only warn, so the - outcome must not turn on whether the store's probe finished.""" + outcome must not turn on whether the store's probe named its token.""" _, secrets = _unread_store_and_secrets(None) assert secrets.refusing == () assert "whether vault.store holds this same token is unknown" in secrets.detail @@ -230,7 +230,7 @@ def test_a_store_probe_with_no_token_leaves_the_decrypt_grant_warning() -> None: def test_a_store_probe_with_no_token_still_refuses_a_grant_on_its_key() -> None: """Control on the key itself refuses either way: shared, the store hop would refuse it.""" key = f"transit/keys/{_KEK}" - store = VaultTokenReading(problems=("the probe did not finish",)) + store = VaultTokenReading(problems=("the token could not be read",)) vault = _FakeVault(caps={_KV_PATH: ["read"], key: ["delete"]}) secrets = _kv_reading(vault, other_required=lambda: [key]) _, hop = vault_hops([_STORE, _KV], [store, secrets]) @@ -296,16 +296,35 @@ def probe(consumer: VaultConsumer) -> VaultTokenReading: async def test_a_slow_store_probe_holding_root_refuses_under_enforce() -> None: - vault = _slow(_FakeVault(caps=_least_caps(), policies=("root",)), _released_soon()) + """While the probe is held, the loop's clock is moved far ahead, so every timer is due: a + limit on the wait, of any length, would end it there and read it as a timeout, which warns.""" + started, release = threading.Event(), threading.Event() + vault = _FakeVault(caps=_least_caps(), policies=("root",)) + + def probe(consumer: VaultConsumer) -> VaultTokenReading: + started.set() + assert release.wait(10) + return _reading(vault) + store = _AuditStore() - with pytest.raises(VaultPrivilegeError, match="vault.store"): - await run_vault_privilege_preflight( - _VAULT_SETTINGS, - store, - enforcing=True, - over_grant_accepted=False, - probe=_probe(vault), + task = asyncio.create_task( + run_vault_privilege_preflight( + _VAULT_SETTINGS, store, enforcing=True, over_grant_accepted=False, probe=probe ) + ) + loop = asyncio.get_running_loop() + real_time = loop.time + try: + assert await asyncio.to_thread(started.wait, 5) + loop.time = lambda: real_time() + 10**9 # type: ignore[method-assign] + for _ in range(10): + await asyncio.sleep(0) + assert not task.done() + finally: + del loop.time + release.set() + with pytest.raises(VaultPrivilegeError, match="vault.store"): + await asyncio.wait_for(task, 10) [(_, row)] = store.audits assert row["state"] == "over_granted" and row["refused"] is True @@ -629,8 +648,8 @@ def stop(consumer: VaultConsumer) -> VaultTokenReading: async def test_a_cancelled_start_does_not_wait_on_a_probe_thread() -> None: - """The probe thread cannot be stopped, so a cancelled start returns while it runs on; it is a - daemon thread, so neither the loop's shutdown nor the interpreter's exit waits on it.""" + """The probe thread cannot be stopped, so a cancelled start returns while it runs on, and the + thread is a daemon of its own, so the interpreter's exit does not wait on it.""" started = threading.Event() release = threading.Event() From 89fb66ab6441d3507d1bac5eede1338e1edee0f7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 15:14:10 -0600 Subject: [PATCH 23/31] Vault preflight tests: clock jump on a private loop, cancelled probe thread checked by identity The root-token control now moves the clock of its own asyncio.run loop, so no other test's timers see the jump, and restores it on every path. The cancellation test checks the thread the probe ran on rather than any thread with that name. Docs name a DNS server that never answers, not a name that does not resolve, which fails fast and only warns. Review round 2 on PR 3553, Lander hold 7357681986. Vault BACKLOG #4851. Verified-by: tests --- docs/SECURITY.md | 2 +- ...t-under-enforce-with-an-audited-opt-out.md | 2 +- messagefoundry/vault_preflight.py | 2 +- tests/test_vault_privilege_preflight_4851.py | 50 +++++++++++-------- 4 files changed, 32 insertions(+), 24 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index af2a34208d..c8a50e0619 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1303,7 +1303,7 @@ the opt-out does not lift it. The probes run side by side, and `serve` waits for each one to finish; the preflight never turns a probe into a timeout by itself. A limit on the whole wait was considered and declined (ADR 0216, Amendment B). Only the Vault client's own per-request timeouts end a request, as they do for the -store open, and they do not end everything: at least a name that does not resolve, a reply that +store open, and they do not end everything: at least a DNS server that never answers, a reply that trickles in, or a hung read of the token file holds the start, before any listener binds, for as long as it lasts. If a start is cancelled while a probe runs, the start does not wait for it, but the probe's thread runs on and may go on calling Vault with the token until the probe ends. A diff --git a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md index 1a979757ef..ae2d4aad87 100644 --- a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md +++ b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md @@ -217,7 +217,7 @@ this amendment records the decision. a slow probe on a token holding root into a pass under `enforce`. So, as before this amendment, elapsed time alone never turns a probe into a reading. Only the Vault client's own per-request timeouts end a request, as they do for the store open, and they do not end everything: at least - a name that does not resolve, a reply that trickles in, or a hung read of the token file holds + a DNS server that never answers, a reply that trickles in, or a hung read of the token file holds the start for as long as it lasts. The same PR also added to the refusing set this ADR's Decision lists, at least the grants that diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index e99cdb62dc..dd8e3b2db1 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -203,7 +203,7 @@ async def _probe_all( the other: no elapsed time alone turns a probe into a reading (decision d20261202T202356290-48e563). Nothing here ends a probe early: only the client's own per-request timeouts end a request, as they do for the store open, and a hang they do not end, - such as a name that does not resolve or a reply that trickles in, holds the start. Each probe + such as a DNS server that never answers or a reply that trickles in, holds the start. Each probe runs on a daemon thread of its own, not the loop's default executor, so a start cancelled while a probe runs does not wait on it, nor does the interpreter's exit; the thread runs on, and may go on calling Vault with the token, until the probe ends.""" diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index ebd6e9e1ab..b48a78aa35 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -295,9 +295,10 @@ def probe(consumer: VaultConsumer) -> VaultTokenReading: return probe -async def test_a_slow_store_probe_holding_root_refuses_under_enforce() -> None: - """While the probe is held, the loop's clock is moved far ahead, so every timer is due: a - limit on the wait, of any length, would end it there and read it as a timeout, which warns.""" +def test_a_slow_store_probe_holding_root_refuses_under_enforce() -> None: + """While the probe is held, the loop's clock is moved far ahead, so every timer on the loop is + due: a limit on the wait timed by the event loop's clock, of any length, would end it there and + read it as a timeout, which warns. A private loop, so no other test's timers see the jump.""" started, release = threading.Event(), threading.Event() vault = _FakeVault(caps=_least_caps(), policies=("root",)) @@ -307,24 +308,28 @@ def probe(consumer: VaultConsumer) -> VaultTokenReading: return _reading(vault) store = _AuditStore() - task = asyncio.create_task( - run_vault_privilege_preflight( - _VAULT_SETTINGS, store, enforcing=True, over_grant_accepted=False, probe=probe + + async def start() -> None: + loop = asyncio.get_running_loop() + real_time = loop.time + task = asyncio.create_task( + run_vault_privilege_preflight( + _VAULT_SETTINGS, store, enforcing=True, over_grant_accepted=False, probe=probe + ) ) - ) - loop = asyncio.get_running_loop() - real_time = loop.time - try: - assert await asyncio.to_thread(started.wait, 5) - loop.time = lambda: real_time() + 10**9 # type: ignore[method-assign] - for _ in range(10): - await asyncio.sleep(0) - assert not task.done() - finally: - del loop.time - release.set() - with pytest.raises(VaultPrivilegeError, match="vault.store"): + try: + assert await asyncio.to_thread(started.wait, 5) + loop.time = lambda: real_time() + 10**9 # type: ignore[method-assign] + for _ in range(10): + await asyncio.sleep(0) + assert not task.done() + finally: + loop.time = real_time # type: ignore[method-assign] + release.set() await asyncio.wait_for(task, 10) + + with pytest.raises(VaultPrivilegeError, match="vault.store"): + asyncio.run(start()) [(_, row)] = store.audits assert row["state"] == "over_granted" and row["refused"] is True @@ -652,8 +657,10 @@ async def test_a_cancelled_start_does_not_wait_on_a_probe_thread() -> None: thread is a daemon of its own, so the interpreter's exit does not wait on it.""" started = threading.Event() release = threading.Event() + ran_on: list[threading.Thread] = [] def hang(consumer: VaultConsumer) -> VaultTokenReading: + ran_on.append(threading.current_thread()) started.set() release.wait(10) return VaultTokenReading() @@ -668,9 +675,10 @@ def hang(consumer: VaultConsumer) -> VaultTokenReading: task.cancel() with pytest.raises(asyncio.CancelledError): await asyncio.wait_for(task, 5) - probes = [t for t in threading.enumerate() if t.name == "vault-privilege-probe-vault.store"] - assert any(t.is_alive() and t.daemon for t in probes) + [thread] = ran_on + assert thread.is_alive() and thread.daemon finally: + task.cancel() release.set() From 0075eb77ed76161573ca45ae8c431b818ae54b90 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 15:45:08 -0600 Subject: [PATCH 24/31] Vault preflight: a probe thread always delivers a reading, and two claims read true A probe thread now delivers from a finally, starting from an unexcused failure reading, so a log call that raises on the thread can no longer kill it before delivery and leave the start waiting before any listener binds. The delivered failure refuses under enforce; a new test with a log filter that raises on probe threads, under asyncio.wait_for, timed out on the previous head. ADR 0216 Amendment B and the _probe_all docstring now say the preflight's own clock never turns a probe into a reading, while a request the Vault client's timeout ends still reads as a timeout, which only warns. The changelog fragment now also names the refusal of a connector-secret token holding any grant but read or list on a path the store calls with its key, such as update on its decrypt path, when the store hop holds another token, and when it only warns. Answers hold 7359590589 on PR 3553. BACKLOG #4851. Verified-by: tests --- ...1-vault-preflight-refusal-gaps.security.md | 2 +- ...t-under-enforce-with-an-audited-opt-out.md | 3 +- messagefoundry/vault_preflight.py | 34 ++++++++++++------- tests/test_vault_privilege_preflight_4851.py | 33 ++++++++++++++++++ 4 files changed, 58 insertions(+), 14 deletions(-) diff --git a/changelog.d/4851-vault-preflight-refusal-gaps.security.md b/changelog.d/4851-vault-preflight-refusal-gaps.security.md index e3a9b83f51..d6dd0f44fb 100644 --- a/changelog.d/4851-vault-preflight-refusal-gaps.security.md +++ b/changelog.d/4851-vault-preflight-refusal-gaps.security.md @@ -1 +1 @@ -- The Vault token preflight now also refuses an enforcing start on a token holding a grant on an audit device, `sys/seal`, raw storage, or the root-token generation or rekey endpoints, or one that can create, rewrite or delete a Transit key the engine uses, or trim, import over, BYOK-export, restore or export one version of it; and on a connector-secret token, on the same Vault address as the store, that can do so to the store key. The probes run side by side, and the start still waits for each one to finish. A token whose lookup-self is denied says its own policies went unasked. `GET /security/posture` reports what the preflight read of each token, under `vault_privilege`. (BACKLOG #4851) +- The Vault token preflight now also refuses an enforcing start on a token holding a grant on an audit device, `sys/seal`, raw storage, or the root-token generation or rekey endpoints, or one that can create, rewrite or delete a Transit key the engine uses, or trim, import over, BYOK-export, restore or export one version of it; and on a connector-secret token, on the same Vault address as the store, that can do so to the store key, or that holds any grant but read or list on a path the store calls with that key, such as `update` on its decrypt path, when the store hop holds another token; held by the store hop's own token, or with that unknown because a token went unread, such a grant only warns. The probes run side by side, and the start still waits for each one to finish. A token whose lookup-self is denied says its own policies went unasked. `GET /security/posture` reports what the preflight read of each token, under `vault_privilege`. (BACKLOG #4851) diff --git a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md index ae2d4aad87..9885df8392 100644 --- a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md +++ b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md @@ -215,7 +215,8 @@ this amendment records the decision. d20261202T053010258-eb19bb. Such a limit would have turned a probe slow for a reason the Decision does not excuse, a code defect or a hung read of the token file among them, into a warning, and a slow probe on a token holding root into a pass under `enforce`. So, as before this amendment, - elapsed time alone never turns a probe into a reading. Only the Vault client's own per-request + the preflight's own clock never turns a probe into a reading; a request the Vault client's + timeout ends still reads as a timeout, which only warns. Only the Vault client's own per-request timeouts end a request, as they do for the store open, and they do not end everything: at least a DNS server that never answers, a reply that trickles in, or a hung read of the token file holds the start for as long as it lasts. diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index dd8e3b2db1..d8157f788f 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -44,6 +44,7 @@ from __future__ import annotations import asyncio +import contextlib import contextvars import json import logging @@ -77,6 +78,12 @@ log = logging.getLogger(__name__) +#: A probe thread's reading until its probe returns one: what it delivers if something raises +#: before a reading of its own is built. Unexcused, so it refuses under enforce. +_UNDELIVERED = VaultTokenReading( + problems=("the probe failed before it built a reading",), unexcused=("BaseException",) +) + __all__ = [ "VAULT_PRIVILEGE_ALERT_SUBJECT", "VAULT_PRIVILEGE_AUDIT_ACTION", @@ -200,7 +207,8 @@ async def _probe_all( ) -> list[VaultTokenReading]: """Every consumer's reading, the probes run side by side, each off the event loop (vault BACKLOG #4851). The start waits for every probe to finish, as it did when they ran one after - the other: no elapsed time alone turns a probe into a reading (decision + the other: the preflight's own clock never turns a probe into a reading; a request the Vault + client's timeout ends still reads as a timeout, which only warns (decision d20261202T202356290-48e563). Nothing here ends a probe early: only the client's own per-request timeouts end a request, as they do for the store open, and a hang they do not end, such as a DNS server that never answers or a reply that trickles in, holds the start. Each probe @@ -223,24 +231,26 @@ def deliver(reading: VaultTokenReading) -> None: done.set_result(reading) def run() -> None: + # A failure until the probe returns a reading, and delivered from the ``finally``, so + # whatever raises here, a log call included, the start still gets a reading and is not + # left waiting on this thread. Every failure is one the ruling does not excuse, so it + # refuses under enforce. The delivery path itself logs nothing. + reading = _UNDELIVERED try: reading = context.run(_probe_one, consumer, probe) - except BaseException as exc: # noqa: BLE001 - _probe_one catches Exception; this is the rest - # Delivered rather than lost, so the start is not left waiting: a BaseException is - # not one the ruling excuses, so it refuses under enforce. + except BaseException as exc: # noqa: BLE001 - _probe_one catches Exception; this is the rest, a raising log call in it included name = type(exc).__name__ - log.warning( - "vault privilege preflight: %s: the probe raised %s", consumer.hop, name - ) reading = VaultTokenReading( problems=(f"the probe raised {name}",), unexcused=(name,) ) - try: - loop.call_soon_threadsafe(deliver, reading) - except RuntimeError: # the loop closed after a cancelled start stopped waiting - log.debug( - "vault privilege preflight: %s finished after its loop closed", consumer.hop + log.warning( + "vault privilege preflight: %s: the probe raised %s", consumer.hop, name ) + finally: + # A RuntimeError here is a loop closed after a cancelled start stopped waiting: + # nobody reads the reading then. + with contextlib.suppress(RuntimeError): + loop.call_soon_threadsafe(deliver, reading) try: threading.Thread( diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index b48a78aa35..532cb76554 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -17,6 +17,7 @@ import asyncio import json +import logging import threading from pathlib import Path from types import SimpleNamespace @@ -652,6 +653,38 @@ def stop(consumer: VaultConsumer) -> VaultTokenReading: ) +async def test_a_probe_thread_whose_logging_raises_still_refuses() -> None: + """Delivered whatever raises, logging included: with every log call on a probe thread raising, + the probe's own failure and the thread's fallback warning both raise, and the start must still + get a reading, which refuses under enforce rather than leaving the start waiting.""" + + class RaiseOnProbeThreads(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + if threading.current_thread().name.startswith("vault-privilege-probe-"): + raise RuntimeError("synthetic logging failure") + return True + + def fail(consumer: VaultConsumer) -> VaultTokenReading: + raise ValueError("synthetic probe failure") + + raising = RaiseOnProbeThreads() + vault_preflight.log.addFilter(raising) + try: + with pytest.raises(VaultPrivilegeError, match="vault.store"): + await asyncio.wait_for( + run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=fail, + ), + 5, + ) + finally: + vault_preflight.log.removeFilter(raising) + + async def test_a_cancelled_start_does_not_wait_on_a_probe_thread() -> None: """The probe thread cannot be stopped, so a cancelled start returns while it runs on, and the thread is a daemon of its own, so the interpreter's exit does not wait on it.""" From 88e3596e13933908cefe109a06b6eb27f529dc19 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 15:59:35 -0600 Subject: [PATCH 25/31] Vault preflight: the probe thread only probes and delivers; the loop classifies Review round 1 on the previous commit. The probe thread now runs only the probe and hands back its reading or whatever it raised; the loop classifies and logs a raise (_probe_failed). So nothing between the probe and the delivery can raise, no sentinel reading is shared between hops, and the refusal names the exception the probe raised rather than a later logging failure. The closed-loop debug line is kept, since nobody waits on the thread by then. The new test now has a positive control (the raising filter must fire), matches the cause in the refusal, and allows 10 s as its sibling does; it still times out on the expected head's module. The changelog clause excludes the key's own path, where only create, rewrite or delete grants refuse, and gives the warning cases as "at least". BACKLOG #4851. Verified-by: tests --- ...1-vault-preflight-refusal-gaps.security.md | 2 +- messagefoundry/vault_preflight.py | 80 ++++++++----------- tests/test_vault_privilege_preflight_4851.py | 20 +++-- 3 files changed, 50 insertions(+), 52 deletions(-) diff --git a/changelog.d/4851-vault-preflight-refusal-gaps.security.md b/changelog.d/4851-vault-preflight-refusal-gaps.security.md index d6dd0f44fb..e178e864ae 100644 --- a/changelog.d/4851-vault-preflight-refusal-gaps.security.md +++ b/changelog.d/4851-vault-preflight-refusal-gaps.security.md @@ -1 +1 @@ -- The Vault token preflight now also refuses an enforcing start on a token holding a grant on an audit device, `sys/seal`, raw storage, or the root-token generation or rekey endpoints, or one that can create, rewrite or delete a Transit key the engine uses, or trim, import over, BYOK-export, restore or export one version of it; and on a connector-secret token, on the same Vault address as the store, that can do so to the store key, or that holds any grant but read or list on a path the store calls with that key, such as `update` on its decrypt path, when the store hop holds another token; held by the store hop's own token, or with that unknown because a token went unread, such a grant only warns. The probes run side by side, and the start still waits for each one to finish. A token whose lookup-self is denied says its own policies went unasked. `GET /security/posture` reports what the preflight read of each token, under `vault_privilege`. (BACKLOG #4851) +- The Vault token preflight now also refuses an enforcing start on a token holding a grant on an audit device, `sys/seal`, raw storage, or the root-token generation or rekey endpoints, or one that can create, rewrite or delete a Transit key the engine uses, or trim, import over, BYOK-export, restore or export one version of it; and on a connector-secret token, on the same Vault address as the store, that can do so to the store key, or that holds any grant but read or list on a path other than the key's own that the store calls with that key, such as `update` on its decrypt path, when the store hop holds another token. Such a grant still only warns in at least these cases: the store hop holds this same token, or whether it does is unknown because a token went unread. The probes run side by side, and the start still waits for each one to finish. A token whose lookup-self is denied says its own policies went unasked. `GET /security/posture` reports what the preflight read of each token, under `vault_privilege`. (BACKLOG #4851) diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index d8157f788f..c5e3678a1c 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -44,7 +44,6 @@ from __future__ import annotations import asyncio -import contextlib import contextvars import json import logging @@ -78,12 +77,6 @@ log = logging.getLogger(__name__) -#: A probe thread's reading until its probe returns one: what it delivers if something raises -#: before a reading of its own is built. Unexcused, so it refuses under enforce. -_UNDELIVERED = VaultTokenReading( - problems=("the probe failed before it built a reading",), unexcused=("BaseException",) -) - __all__ = [ "VAULT_PRIVILEGE_ALERT_SUBJECT", "VAULT_PRIVILEGE_AUDIT_ACTION", @@ -183,23 +176,20 @@ def _alert(sink: VaultPrivilegeAlertSink, hop: HopPrivilege, outcome: PreflightO log.exception("vault privilege preflight: the alert sink raised") -def _probe_one( - consumer: VaultConsumer, probe: Callable[[VaultConsumer], VaultTokenReading] -) -> VaultTokenReading: - """One consumer's reading. A probe that raises never aborts the start here: the probe reports - its own failures, but a token re-read or an unrouted consumer kind can still raise, and under - ``enforcement = warn`` nothing here may refuse. The raise becomes a reading with one problem. - Unless :func:`~messagefoundry.privilege_probes.excused_failure` excuses it, the reading also - names it in ``unexcused``, which refuses under ``enforce``: a code defect is never a pass. Only +def _probe_failed(consumer: VaultConsumer, exc: BaseException) -> VaultTokenReading: + """The reading for a probe that raised ``exc``. A probe that raises never aborts the start + here: the probe reports its own failures, but a token re-read or an unrouted consumer kind can + still raise, and under ``enforcement = warn`` nothing here may refuse. The raise becomes a + reading with one problem. Unless :func:`~messagefoundry.privilege_probes.excused_failure` + excuses it, the reading also names it in ``unexcused``, which refuses under ``enforce``: a code + defect is never a pass. A ``BaseException`` that is not an ``Exception`` is never excused. Only the exception's type is kept, so no library or server text reaches the log or the audit row.""" - try: - return probe(consumer) - except Exception as exc: # noqa: BLE001 - classified below, never a pass - problem = f"the probe raised {type(exc).__name__}" - log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) - cause = unexcused_cause(exc) - unexcused = () if cause is None else (cause,) - return VaultTokenReading(problems=(problem,), unexcused=unexcused) + name = type(exc).__name__ + problem = f"the probe raised {name}" + cause = unexcused_cause(exc) if isinstance(exc, Exception) else name + unexcused = () if cause is None else (cause,) + log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) + return VaultTokenReading(problems=(problem,), unexcused=unexcused) async def _probe_all( @@ -222,35 +212,32 @@ async def _probe_all( preload_vault_probe_imports() async def one(consumer: VaultConsumer) -> VaultTokenReading: - done: asyncio.Future[VaultTokenReading] = loop.create_future() + done: asyncio.Future[VaultTokenReading | BaseException] = loop.create_future() # Under the caller's context, as asyncio.to_thread would run it. context = contextvars.copy_context() - def deliver(reading: VaultTokenReading) -> None: + def deliver(outcome: VaultTokenReading | BaseException) -> None: if not done.done(): # the start was cancelled, so nobody reads it - done.set_result(reading) + done.set_result(outcome) def run() -> None: - # A failure until the probe returns a reading, and delivered from the ``finally``, so - # whatever raises here, a log call included, the start still gets a reading and is not - # left waiting on this thread. Every failure is one the ruling does not excuse, so it - # refuses under enforce. The delivery path itself logs nothing. - reading = _UNDELIVERED + # The thread only runs the probe and hands back its reading or whatever it raised, a + # raising log call inside the probe included. Nothing between the probe and the + # delivery logs or classifies, so nothing there can raise and leave the start waiting + # on this thread; the loop classifies and logs a raise (:func:`_probe_failed`). + outcome: VaultTokenReading | BaseException try: - reading = context.run(_probe_one, consumer, probe) - except BaseException as exc: # noqa: BLE001 - _probe_one catches Exception; this is the rest, a raising log call in it included - name = type(exc).__name__ - reading = VaultTokenReading( - problems=(f"the probe raised {name}",), unexcused=(name,) - ) - log.warning( - "vault privilege preflight: %s: the probe raised %s", consumer.hop, name + outcome = context.run(probe, consumer) + except BaseException as exc: # noqa: BLE001 - every raise is delivered, never a pass + outcome = exc + try: + loop.call_soon_threadsafe(deliver, outcome) + except RuntimeError: # the loop closed after a cancelled start stopped waiting + # Nobody waits on this thread any more, so a log call that raises here holds + # nothing up. + log.debug( + "vault privilege preflight: %s finished after its loop closed", consumer.hop ) - finally: - # A RuntimeError here is a loop closed after a cancelled start stopped waiting: - # nobody reads the reading then. - with contextlib.suppress(RuntimeError): - loop.call_soon_threadsafe(deliver, reading) try: threading.Thread( @@ -263,7 +250,10 @@ def run() -> None: problem = f"the probe could not start a thread ({type(exc).__name__})" log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) return VaultTokenReading(problems=(problem,), unexcused=(type(exc).__name__,)) - return await done + outcome = await done + if isinstance(outcome, BaseException): + return _probe_failed(consumer, outcome) + return outcome return list(await asyncio.gather(*(one(c) for c in consumers))) diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index 532cb76554..1ddbb551ed 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -654,23 +654,29 @@ def stop(consumer: VaultConsumer) -> VaultTokenReading: async def test_a_probe_thread_whose_logging_raises_still_refuses() -> None: - """Delivered whatever raises, logging included: with every log call on a probe thread raising, - the probe's own failure and the thread's fallback warning both raise, and the start must still - get a reading, which refuses under enforce rather than leaving the start waiting.""" + """Delivered whatever raises, logging included: every log call on a probe thread raises, the + probe's own included, and the start must still get a reading, which refuses under enforce + naming the logging failure, rather than being left waiting. Before the fix the thread's own + warnings raised too and the thread died undelivered, which the ``wait_for`` turns into a + failure instead of a hung test.""" + fired: list[str] = [] class RaiseOnProbeThreads(logging.Filter): def filter(self, record: logging.LogRecord) -> bool: - if threading.current_thread().name.startswith("vault-privilege-probe-"): + name = threading.current_thread().name + if name.startswith("vault-privilege-probe-"): + fired.append(name) raise RuntimeError("synthetic logging failure") return True def fail(consumer: VaultConsumer) -> VaultTokenReading: + vault_preflight.log.warning("synthetic probe log line") raise ValueError("synthetic probe failure") raising = RaiseOnProbeThreads() vault_preflight.log.addFilter(raising) try: - with pytest.raises(VaultPrivilegeError, match="vault.store"): + with pytest.raises(VaultPrivilegeError, match=r"vault\.store: RuntimeError"): await asyncio.wait_for( run_vault_privilege_preflight( _VAULT_SETTINGS, @@ -679,10 +685,12 @@ def fail(consumer: VaultConsumer) -> VaultTokenReading: over_grant_accepted=False, probe=fail, ), - 5, + 10, ) finally: vault_preflight.log.removeFilter(raising) + # The positive control: the raising filter fired, so a logger left disabled cannot pass this. + assert fired async def test_a_cancelled_start_does_not_wait_on_a_probe_thread() -> None: From 33ea6711fea9d5c03bfd6d0589738527f1ed891c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 16:09:08 -0600 Subject: [PATCH 26/31] Vault preflight: fail closed on a raising classifier, log a late raise, free its frames Review round 2. A classifier that raises while a probe's raise is judged now names the raise unexcused instead of aborting the start. A probe that raises after its start stopped waiting is logged at WARNING again, as the expected head did. The probe thread drops its own reference to a delivered exception, so no reference cycle keeps the probe's frames, the token among them, alive until a GC pass. The ADR now says outright that declining the limit does not stop a token holding root from starting under enforce when the client's timeout ends its probe. The changelog clause covers every key the store calls, not one. The new test's docstring says which log calls it makes raise. BACKLOG #4851. Verified-by: tests --- ...1-vault-preflight-refusal-gaps.security.md | 2 +- ...t-under-enforce-with-an-audited-opt-out.md | 3 ++- messagefoundry/vault_preflight.py | 20 +++++++++++++++++-- tests/test_vault_privilege_preflight_4851.py | 7 ++++--- 4 files changed, 25 insertions(+), 7 deletions(-) diff --git a/changelog.d/4851-vault-preflight-refusal-gaps.security.md b/changelog.d/4851-vault-preflight-refusal-gaps.security.md index e178e864ae..2f3352d59c 100644 --- a/changelog.d/4851-vault-preflight-refusal-gaps.security.md +++ b/changelog.d/4851-vault-preflight-refusal-gaps.security.md @@ -1 +1 @@ -- The Vault token preflight now also refuses an enforcing start on a token holding a grant on an audit device, `sys/seal`, raw storage, or the root-token generation or rekey endpoints, or one that can create, rewrite or delete a Transit key the engine uses, or trim, import over, BYOK-export, restore or export one version of it; and on a connector-secret token, on the same Vault address as the store, that can do so to the store key, or that holds any grant but read or list on a path other than the key's own that the store calls with that key, such as `update` on its decrypt path, when the store hop holds another token. Such a grant still only warns in at least these cases: the store hop holds this same token, or whether it does is unknown because a token went unread. The probes run side by side, and the start still waits for each one to finish. A token whose lookup-self is denied says its own policies went unasked. `GET /security/posture` reports what the preflight read of each token, under `vault_privilege`. (BACKLOG #4851) +- The Vault token preflight now also refuses an enforcing start on a token holding a grant on an audit device, `sys/seal`, raw storage, or the root-token generation or rekey endpoints, or one that can create, rewrite or delete a Transit key the engine uses, or trim, import over, BYOK-export, restore or export one version of it; and on a connector-secret token, on the same Vault address as the store, that can do so to the store key, or that holds any grant but read or list on a path, other than a key's own path, that the store calls with one of its keys, such as `update` on the decrypt path, when the store hop holds another token. Such a grant still only warns in at least these cases: the store hop holds this same token, or whether it does is unknown because a token went unread. The probes run side by side, and the start still waits for each one to finish. A token whose lookup-self is denied says its own policies went unasked. `GET /security/posture` reports what the preflight read of each token, under `vault_privilege`. (BACKLOG #4851) diff --git a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md index 9885df8392..04958ef32e 100644 --- a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md +++ b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md @@ -216,7 +216,8 @@ this amendment records the decision. does not excuse, a code defect or a hung read of the token file among them, into a warning, and a slow probe on a token holding root into a pass under `enforce`. So, as before this amendment, the preflight's own clock never turns a probe into a reading; a request the Vault client's - timeout ends still reads as a timeout, which only warns. Only the Vault client's own per-request + timeout ends still reads as a timeout, which only warns. So declining the limit does not stop a + token holding root from starting under `enforce` when the client's timeout ends its probe. Only the Vault client's own per-request timeouts end a request, as they do for the store open, and they do not end everything: at least a DNS server that never answers, a reply that trickles in, or a hung read of the token file holds the start for as long as it lasts. diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index c5e3678a1c..e667b8d12b 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -186,7 +186,10 @@ def _probe_failed(consumer: VaultConsumer, exc: BaseException) -> VaultTokenRead the exception's type is kept, so no library or server text reaches the log or the audit row.""" name = type(exc).__name__ problem = f"the probe raised {name}" - cause = unexcused_cause(exc) if isinstance(exc, Exception) else name + try: + cause = unexcused_cause(exc) if isinstance(exc, Exception) else name + except Exception: # noqa: BLE001 - a classifier that raises excuses nothing: fail closed + cause = name unexcused = () if cause is None else (cause,) log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) return VaultTokenReading(problems=(problem,), unexcused=unexcused) @@ -217,8 +220,16 @@ async def one(consumer: VaultConsumer) -> VaultTokenReading: context = contextvars.copy_context() def deliver(outcome: VaultTokenReading | BaseException) -> None: - if not done.done(): # the start was cancelled, so nobody reads it + if not done.done(): done.set_result(outcome) + elif isinstance(outcome, BaseException): + # The start was cancelled, so nobody reads it; the raise is still logged. + log.warning( + "vault privilege preflight: %s: the probe raised %s after its start stopped " + "waiting", + consumer.hop, + type(outcome).__name__, + ) def run() -> None: # The thread only runs the probe and hands back its reading or whatever it raised, a @@ -238,6 +249,11 @@ def run() -> None: log.debug( "vault privilege preflight: %s finished after its loop closed", consumer.hop ) + finally: + # A delivered raise's traceback holds this frame: dropping the frame's own + # reference to it leaves no cycle, so the probe's frames, the token and its client + # among them, are freed once the reading is built rather than at a GC pass. + del outcome try: threading.Thread( diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index 1ddbb551ed..39ccce3639 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -654,9 +654,10 @@ def stop(consumer: VaultConsumer) -> VaultTokenReading: async def test_a_probe_thread_whose_logging_raises_still_refuses() -> None: - """Delivered whatever raises, logging included: every log call on a probe thread raises, the - probe's own included, and the start must still get a reading, which refuses under enforce - naming the logging failure, rather than being left waiting. Before the fix the thread's own + """Delivered whatever raises, logging included: every call on the preflight's logger from a + probe thread raises, one inside the probe included, and the start must still get a reading, + which refuses under enforce naming the logging failure, rather than being left waiting. Other + loggers, and log calls on the loop, are not made to raise here. Before the fix the thread's own warnings raised too and the thread died undelivered, which the ``wait_for`` turns into a failure instead of a hung test.""" fired: list[str] = [] From 4b8549079832c499a96aa4bf1b1e802d38c0f56b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 16:38:00 -0600 Subject: [PATCH 27/31] Vault preflight frees a failed probe's frames and keeps its text out of every log Answers Lander hold 7360803139 on PR 3553 (vault BACKLOG #4851): 1. The loop clears a delivered raise's traceback once _probe_failed has read it, so the probe's frames, the token among them, are freed by reference count, not at a collector pass. Test: a weakref with gc off. 2. A raise that lands after the loop closed is a WARNING naming its type and no text. Test. 3. The reading goes to the loop bound as a default, not as a callback argument, so asyncio debug mode's slow-callback log never shows a raise's text. Test with a zero slow-callback bound. 4. The run comment says nothing between the probe and the delivery logs or classifies. 5. SECURITY.md, ADR 0216 Amendment B and the _probe_all docstring drop the DNS server that never answers: excused_failure excuses socket.gaierror, so a lookup the resolver gives up on only warns. Verified-by: tests --- docs/SECURITY.md | 6 +- ...t-under-enforce-with-an-audited-opt-out.md | 4 +- messagefoundry/vault_preflight.py | 48 +++++--- tests/test_vault_privilege_preflight_4851.py | 111 ++++++++++++++++++ 4 files changed, 150 insertions(+), 19 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index c8a50e0619..f6781db615 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1303,9 +1303,9 @@ the opt-out does not lift it. The probes run side by side, and `serve` waits for each one to finish; the preflight never turns a probe into a timeout by itself. A limit on the whole wait was considered and declined (ADR 0216, Amendment B). Only the Vault client's own per-request timeouts end a request, as they do for the -store open, and they do not end everything: at least a DNS server that never answers, a reply that -trickles in, or a hung read of the token file holds the start, before any listener binds, for as -long as it lasts. If a start is cancelled while a probe runs, the start does not wait for it, but +store open, and they do not end everything: at least a reply that trickles in, or a hung read of +the token file holds the start, before any listener binds, for as long as it lasts. A name lookup +the resolver gives up on is a network failure, which only warns. If a start is cancelled while a probe runs, the start does not wait for it, but the probe's thread runs on and may go on calling Vault with the token until the probe ends. A token whose `auth/token/lookup-self` is denied (a 403, so only a warning) cannot name its own policies, so whether it can rewrite them is not asked; its hop says so. What the preflight read of diff --git a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md index 04958ef32e..378d5d9e62 100644 --- a/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md +++ b/docs/adr/0216-the-gravest-vault-token-grants-refuse-start-under-enforce-with-an-audited-opt-out.md @@ -219,8 +219,8 @@ this amendment records the decision. timeout ends still reads as a timeout, which only warns. So declining the limit does not stop a token holding root from starting under `enforce` when the client's timeout ends its probe. Only the Vault client's own per-request timeouts end a request, as they do for the store open, and they do not end everything: at least - a DNS server that never answers, a reply that trickles in, or a hung read of the token file holds - the start for as long as it lasts. + a reply that trickles in, or a hung read of the token file holds the start for as long as it + lasts. A name lookup the resolver gives up on is a network failure, which only warns. The same PR also added to the refusing set this ADR's Decision lists, at least the grants that create, rewrite or delete the hop's own Transit key, more Transit key administration paths and more diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index e667b8d12b..58fbc5646f 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -204,7 +204,8 @@ async def _probe_all( client's timeout ends still reads as a timeout, which only warns (decision d20261202T202356290-48e563). Nothing here ends a probe early: only the client's own per-request timeouts end a request, as they do for the store open, and a hang they do not end, - such as a DNS server that never answers or a reply that trickles in, holds the start. Each probe + such as a reply that trickles in, holds the start. A name lookup the resolver gives up on is a + network failure, which only warns. Each probe runs on a daemon thread of its own, not the loop's default executor, so a start cancelled while a probe runs does not wait on it, nor does the interpreter's exit; the thread runs on, and may go on calling Vault with the token, until the probe ends.""" @@ -233,27 +234,40 @@ def deliver(outcome: VaultTokenReading | BaseException) -> None: def run() -> None: # The thread only runs the probe and hands back its reading or whatever it raised, a - # raising log call inside the probe included. Nothing between the probe and the - # delivery logs or classifies, so nothing there can raise and leave the start waiting - # on this thread; the loop classifies and logs a raise (:func:`_probe_failed`). + # raising log call inside the probe included. Between the probe and the delivery, + # nothing there logs or classifies; the loop classifies and logs a raise + # (:func:`_probe_failed`). outcome: VaultTokenReading | BaseException try: outcome = context.run(probe, consumer) except BaseException as exc: # noqa: BLE001 - every raise is delivered, never a pass outcome = exc + + # Bound as a default, not passed as an argument: asyncio's debug mode logs a slow + # callback's arguments, and with them a raise's text. + def hand_over(delivered: VaultTokenReading | BaseException = outcome) -> None: + deliver(delivered) + try: - loop.call_soon_threadsafe(deliver, outcome) + loop.call_soon_threadsafe(hand_over) except RuntimeError: # the loop closed after a cancelled start stopped waiting # Nobody waits on this thread any more, so a log call that raises here holds - # nothing up. - log.debug( - "vault privilege preflight: %s finished after its loop closed", consumer.hop - ) + # nothing up. A raise is named by its type only, as the loop would name it. + if isinstance(outcome, BaseException): + log.warning( + "vault privilege preflight: %s: the probe raised %s after its loop closed", + consumer.hop, + type(outcome).__name__, + ) + else: + log.debug( + "vault privilege preflight: %s finished after its loop closed", + consumer.hop, + ) finally: - # A delivered raise's traceback holds this frame: dropping the frame's own - # reference to it leaves no cycle, so the probe's frames, the token and its client - # among them, are freed once the reading is built rather than at a GC pass. - del outcome + # A raise nobody reads is freed with this frame. One that is read is freed when + # the loop clears its traceback. + del outcome, hand_over try: threading.Thread( @@ -268,7 +282,13 @@ def run() -> None: return VaultTokenReading(problems=(problem,), unexcused=(type(exc).__name__,)) outcome = await done if isinstance(outcome, BaseException): - return _probe_failed(consumer, outcome) + try: + return _probe_failed(consumer, outcome) + finally: + # Its traceback holds the probe's frames, the token among them, and this + # thread's frame, which reaches it back through ``done``: a cycle only a + # collector pass would free. Cleared once read, they are freed here. + outcome.__traceback__ = None return outcome return list(await asyncio.gather(*(one(c) for c in consumers))) diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index 39ccce3639..a6ff971ed7 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -724,6 +724,117 @@ def hang(consumer: VaultConsumer) -> VaultTokenReading: release.set() +class _Held: + """Something a probe holds while it runs, as it would hold the token and its client.""" + + +async def test_a_failed_probes_frames_are_freed_without_the_collector() -> None: + """A delivered raise's traceback holds the probe's frames, the token among them: once the + preflight returns, none is reachable, with no collector pass to break a cycle.""" + import gc + import weakref + + refs: list[weakref.ref[_Held]] = [] + + def fail(consumer: VaultConsumer) -> VaultTokenReading: + held = _Held() + refs.append(weakref.ref(held)) + raise ValueError("synthetic probe failure") + + was_enabled = gc.isenabled() + gc.disable() + try: + [hop] = await run_vault_privilege_preflight( + _VAULT_SETTINGS, _AuditStore(), enforcing=False, over_grant_accepted=False, probe=fail + ) + assert hop.unexcused == ("ValueError",) + [ref] = refs + assert ref() is None + finally: + if was_enabled: + gc.enable() + + +def test_a_raise_after_the_loop_closed_is_a_warning_naming_only_its_type( + caplog: pytest.LogCaptureFixture, +) -> None: + """Nobody reads a raise that lands after a cancelled start's loop closed, so it is logged: at + WARNING, by its type, with none of its text.""" + started = threading.Event() + release = threading.Event() + ran_on: list[threading.Thread] = [] + + def late(consumer: VaultConsumer) -> VaultTokenReading: + ran_on.append(threading.current_thread()) + started.set() + release.wait(10) + raise ValueError("synthetic secret text") + + async def cancel_the_start() -> None: + task = asyncio.create_task( + run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=late, + ) + ) + for _ in range(500): + if started.is_set(): + break + await asyncio.sleep(0.01) + assert started.is_set() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + loop = asyncio.new_event_loop() + try: + loop.run_until_complete(cancel_the_start()) + finally: + loop.close() + with caplog.at_level(logging.DEBUG, logger=vault_preflight.log.name): + release.set() + [thread] = ran_on + thread.join(10) + assert not thread.is_alive() + late_lines = [r for r in caplog.records if r.name == vault_preflight.log.name] + assert [(r.levelno, "ValueError" in r.getMessage()) for r in late_lines] == [ + (logging.WARNING, True) + ] + assert "synthetic secret text" not in caplog.text + + +def test_no_probe_raise_text_reaches_any_log_in_asyncio_debug_mode( + caplog: pytest.LogCaptureFixture, +) -> None: + """Debug mode logs a callback's arguments when it runs slow; a slow-callback bound of zero + makes every callback slow, so a raise handed to the loop as an argument would be logged.""" + + def fail(consumer: VaultConsumer) -> VaultTokenReading: + raise ValueError("synthetic secret text") + + async def start() -> None: + asyncio.get_running_loop().slow_callback_duration = 0 + with pytest.raises(VaultPrivilegeError): + await run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=fail, + ) + + with caplog.at_level(logging.DEBUG): + asyncio.run(start(), debug=True) + # The positive control: debug mode logged the slow callbacks, so a quiet logger cannot pass. + assert any(r.name == "asyncio" and "Executing" in r.getMessage() for r in caplog.records) + # The asyncio log shortens a long argument to its two ends, so look for each end. + assert "synthetic" not in caplog.text + assert "secret text" not in caplog.text + + async def test_the_probes_run_side_by_side(monkeypatch: pytest.MonkeyPatch) -> None: """Two probes that each wait for the other finish only if they run at once.""" monkeypatch.setattr(vault_preflight, "vault_consumers", lambda settings: [_STORE, _KV]) From 9f0dbdf8bc1410dc09b864ebe61215c3e1736a78 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 16:51:06 -0600 Subject: [PATCH 28/31] Vault preflight frees a chained probe raise's frames too Review round 0763125020 on the answer to Lander hold 7360803139 (PR 3553, vault BACKLOG #4851): clearing only the delivered raise's traceback left a raise made inside an except block holding the probe's frames through the raise it carries, until a collector pass. The loop now clears the traceback of every exception in the chain once it has read it. Tests: the gc-off weakref test also covers a chained raise (seen failing before this fix); the debug-mode test gains a negative control showing a raise handed over as an argument does reach the asyncio log; the loop-closed test always releases its probe thread. Verified-by: tests --- messagefoundry/vault_preflight.py | 22 ++++++++-- tests/test_vault_privilege_preflight_4851.py | 42 ++++++++++++++------ 2 files changed, 48 insertions(+), 16 deletions(-) diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index 58fbc5646f..77f4ef7d3b 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -54,6 +54,7 @@ from messagefoundry.audit_write import write_audit_soft from messagefoundry.controlchars import scrub_log_argument +from messagefoundry.exception_origin import exception_chain from messagefoundry.privilege_check import ( VAULT_OVER_GRANT_OPT_OUT, VAULT_REFUSING_CLASS, @@ -195,6 +196,18 @@ def _probe_failed(consumer: VaultConsumer, exc: BaseException) -> VaultTokenRead return VaultTokenReading(problems=(problem,), unexcused=unexcused) +def _clear_tracebacks(exc: BaseException) -> None: + """Drop the traceback of ``exc`` and of every exception it carries, whose tracebacks reach the + same probe frames, so those frames are freed now rather than at a collector pass. Best effort: + a chain that cannot be walked whole keeps what it did not reach until that pass.""" + exc.__traceback__ = None + try: + for link in exception_chain(exc): + link.__traceback__ = None + except Exception: # noqa: BLE001 - freeing early is best effort; it judges nothing + log.debug("vault privilege preflight: a raise's chain could not be walked whole") + + async def _probe_all( consumers: list[VaultConsumer], probe: Callable[[VaultConsumer], VaultTokenReading] ) -> list[VaultTokenReading]: @@ -285,10 +298,11 @@ def hand_over(delivered: VaultTokenReading | BaseException = outcome) -> None: try: return _probe_failed(consumer, outcome) finally: - # Its traceback holds the probe's frames, the token among them, and this - # thread's frame, which reaches it back through ``done``: a cycle only a - # collector pass would free. Cleared once read, they are freed here. - outcome.__traceback__ = None + # Its traceback, and those of the raises it carries, hold the probe's frames, the + # token among them, and the probe thread's ``run`` frame, which reaches it back + # through ``done``: a cycle only a collector pass would free. Cleared once read, + # they are freed here. + _clear_tracebacks(outcome) return outcome return list(await asyncio.gather(*(one(c) for c in consumers))) diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index a6ff971ed7..c5cce22765 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -728,9 +728,11 @@ class _Held: """Something a probe holds while it runs, as it would hold the token and its client.""" -async def test_a_failed_probes_frames_are_freed_without_the_collector() -> None: +@pytest.mark.parametrize("chained", [False, True], ids=["a lone raise", "a chained raise"]) +async def test_a_failed_probes_frames_are_freed_without_the_collector(chained: bool) -> None: """A delivered raise's traceback holds the probe's frames, the token among them: once the - preflight returns, none is reachable, with no collector pass to break a cycle.""" + preflight returns, none is reachable, with no collector pass to break a cycle. A raise inside + an ``except`` block carries the first raise, whose traceback reaches the same frames.""" import gc import weakref @@ -739,7 +741,12 @@ async def test_a_failed_probes_frames_are_freed_without_the_collector() -> None: def fail(consumer: VaultConsumer) -> VaultTokenReading: held = _Held() refs.append(weakref.ref(held)) - raise ValueError("synthetic probe failure") + if not chained: + raise ValueError("synthetic probe failure") + try: + raise KeyError("synthetic first failure") + except KeyError: + raise ValueError("synthetic probe failure") # noqa: B904 - the implicit chain is the case was_enabled = gc.isenabled() gc.disable() @@ -791,14 +798,17 @@ async def cancel_the_start() -> None: loop = asyncio.new_event_loop() try: - loop.run_until_complete(cancel_the_start()) + try: + loop.run_until_complete(cancel_the_start()) + finally: + loop.close() + with caplog.at_level(logging.DEBUG, logger=vault_preflight.log.name): + release.set() + [thread] = ran_on + thread.join(10) + assert not thread.is_alive() finally: - loop.close() - with caplog.at_level(logging.DEBUG, logger=vault_preflight.log.name): release.set() - [thread] = ran_on - thread.join(10) - assert not thread.is_alive() late_lines = [r for r in caplog.records if r.name == vault_preflight.log.name] assert [(r.levelno, "ValueError" in r.getMessage()) for r in late_lines] == [ (logging.WARNING, True) @@ -816,7 +826,13 @@ def fail(consumer: VaultConsumer) -> VaultTokenReading: raise ValueError("synthetic secret text") async def start() -> None: - asyncio.get_running_loop().slow_callback_duration = 0 + loop = asyncio.get_running_loop() + loop.slow_callback_duration = 0 + # The negative control, kept apart from the preflight's text: a raise handed over as an + # argument does reach the log, so the searches below would see one. + handed = asyncio.Event() + loop.call_soon(lambda exc: handed.set(), ValueError("synthetic control text")) + await handed.wait() with pytest.raises(VaultPrivilegeError): await run_vault_privilege_preflight( _VAULT_SETTINGS, @@ -830,8 +846,10 @@ async def start() -> None: asyncio.run(start(), debug=True) # The positive control: debug mode logged the slow callbacks, so a quiet logger cannot pass. assert any(r.name == "asyncio" and "Executing" in r.getMessage() for r in caplog.records) - # The asyncio log shortens a long argument to its two ends, so look for each end. - assert "synthetic" not in caplog.text + # The asyncio log shortens a long argument to its two ends, so look for each end; the control + # shows the tail end survives the shortening. + assert "control text" in caplog.text + assert "synthetic secret" not in caplog.text assert "secret text" not in caplog.text From f2b229d12667db2ae89942a0bc0b259b62d3e6a9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 17:27:12 -0600 Subject: [PATCH 29/31] Vault preflight clears late raises and logs a raise handed over just before a cancel The Lander's hold on PR 3553 at 9f0dbdf8, four edits: 1. _clear_tracebacks sets the first traceback inside its try, so a raise whose traceback cannot be set no longer aborts a warn-mode start. 2. On a cancel around await done, a result already handed over is delivered, so its raise is logged as one handed over after the cancel. 3. Both late warnings clear the raise's tracebacks. 4. Two comments corrected to what frees a raise's frames. Two tests, each seen failing on 9f0dbdf8 before the fix. Vault BACKLOG #4851. Verified-by: tests --- messagefoundry/vault_preflight.py | 19 ++++-- tests/test_vault_privilege_preflight_4851.py | 68 ++++++++++++++++++++ 2 files changed, 81 insertions(+), 6 deletions(-) diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index 77f4ef7d3b..02ad1864de 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -200,8 +200,8 @@ def _clear_tracebacks(exc: BaseException) -> None: """Drop the traceback of ``exc`` and of every exception it carries, whose tracebacks reach the same probe frames, so those frames are freed now rather than at a collector pass. Best effort: a chain that cannot be walked whole keeps what it did not reach until that pass.""" - exc.__traceback__ = None try: + exc.__traceback__ = None for link in exception_chain(exc): link.__traceback__ = None except Exception: # noqa: BLE001 - freeing early is best effort; it judges nothing @@ -244,6 +244,7 @@ def deliver(outcome: VaultTokenReading | BaseException) -> None: consumer.hop, type(outcome).__name__, ) + _clear_tracebacks(outcome) def run() -> None: # The thread only runs the probe and hands back its reading or whatever it raised, a @@ -272,14 +273,14 @@ def hand_over(delivered: VaultTokenReading | BaseException = outcome) -> None: consumer.hop, type(outcome).__name__, ) + _clear_tracebacks(outcome) else: log.debug( "vault privilege preflight: %s finished after its loop closed", consumer.hop, ) finally: - # A raise nobody reads is freed with this frame. One that is read is freed when - # the loop clears its traceback. + # The loop, or the late branch here, clears a raise's traceback. del outcome, hand_over try: @@ -293,15 +294,21 @@ def hand_over(delivered: VaultTokenReading | BaseException = outcome) -> None: problem = f"the probe could not start a thread ({type(exc).__name__})" log.warning("vault privilege preflight: %s: %s", consumer.hop, problem) return VaultTokenReading(problems=(problem,), unexcused=(type(exc).__name__,)) - outcome = await done + try: + outcome = await done + except asyncio.CancelledError: + # A raise handed over just before the cancel is logged, as one handed over after it. + if done.done() and not done.cancelled(): + deliver(done.result()) + raise if isinstance(outcome, BaseException): try: return _probe_failed(consumer, outcome) finally: # Its traceback, and those of the raises it carries, hold the probe's frames, the # token among them, and the probe thread's ``run`` frame, which reaches it back - # through ``done``: a cycle only a collector pass would free. Cleared once read, - # they are freed here. + # through ``done``: a cycle only a collector pass would free. Cleared once read; + # an error the probe caught itself can still hold them until a collector pass. _clear_tracebacks(outcome) return outcome diff --git a/tests/test_vault_privilege_preflight_4851.py b/tests/test_vault_privilege_preflight_4851.py index c5cce22765..42cd5a87b0 100644 --- a/tests/test_vault_privilege_preflight_4851.py +++ b/tests/test_vault_privilege_preflight_4851.py @@ -724,6 +724,74 @@ def hang(consumer: VaultConsumer) -> VaultTokenReading: release.set() +async def test_a_raise_delivered_just_before_a_cancel_is_still_logged( + caplog: pytest.LogCaptureFixture, +) -> None: + """A raise handed over, and then the start cancelled before it read it: nobody reads it, so it + is logged, by its type, with none of its text. The loop is held while the probe thread hands + over, so the hand-over runs before the cancel and the cancel before the start reads it.""" + started = threading.Event() + release = threading.Event() + ran_on: list[threading.Thread] = [] + + def late(consumer: VaultConsumer) -> VaultTokenReading: + ran_on.append(threading.current_thread()) + started.set() + release.wait(10) + raise ValueError("synthetic secret text") + + loop = asyncio.get_running_loop() + task = asyncio.create_task( + run_vault_privilege_preflight( + _VAULT_SETTINGS, _AuditStore(), enforcing=True, over_grant_accepted=False, probe=late + ) + ) + try: + assert await asyncio.to_thread(started.wait, 5) + with caplog.at_level(logging.DEBUG, logger=vault_preflight.log.name): + release.set() + [thread] = ran_on + # Held on purpose: the thread queues its hand-over while the loop cannot run it. + thread.join(10) + assert not thread.is_alive() + loop.call_soon(task.cancel) + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(task, 5) + finally: + task.cancel() + release.set() + late_lines = [ + r.getMessage() + for r in caplog.records + if r.name == vault_preflight.log.name and r.levelno == logging.WARNING + ] + assert [("ValueError" in m, "stopped waiting" in m) for m in late_lines] == [(True, True)] + assert "synthetic secret text" not in caplog.text + + +class _ReadOnlyTraceback(ValueError): + """A raise whose traceback cannot be set, as a library's exception class might define it.""" + + @property + def __traceback__(self) -> None: # type: ignore[override] + return None + + +async def test_a_raise_whose_traceback_cannot_be_cleared_still_starts_under_warn() -> None: + """Freeing early is best effort: a raise that refuses it is still a reading, and warn starts.""" + + def fail(consumer: VaultConsumer) -> VaultTokenReading: + raise _ReadOnlyTraceback("synthetic probe failure") + + [hop] = await asyncio.wait_for( + run_vault_privilege_preflight( + _VAULT_SETTINGS, _AuditStore(), enforcing=False, over_grant_accepted=False, probe=fail + ), + 10, + ) + assert hop.unexcused == ("_ReadOnlyTraceback",) + + class _Held: """Something a probe holds while it runs, as it would hold the token and its client.""" From 24beee0737246012daa258bf4b4179ba8fea05c1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 17:37:52 -0600 Subject: [PATCH 30/31] Vault preflight keeps the second sentence the hold left in place The hold's edit 4 replaced only the first sentence of the run frame's comment; the second sentence is restored. Vault BACKLOG #4851. Verified-by: tests --- messagefoundry/vault_preflight.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index 02ad1864de..16ff73d744 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -280,7 +280,8 @@ def hand_over(delivered: VaultTokenReading | BaseException = outcome) -> None: consumer.hop, ) finally: - # The loop, or the late branch here, clears a raise's traceback. + # The loop, or the late branch here, clears a raise's traceback. One that is read + # is freed when the loop clears its traceback. del outcome, hand_over try: From 2807198ffb9f52542f8d894e931d8e36dca5ff0f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 17:51:22 -0600 Subject: [PATCH 31/31] Vault preflight drops the run frame comment's second sentence again Review found the restored sentence claims a read raise's frames are freed where a raise that refuses the clear keeps them. The comment is the hold's single replacement sentence, as first committed. Vault BACKLOG #4851. Verified-by: tests --- messagefoundry/vault_preflight.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/messagefoundry/vault_preflight.py b/messagefoundry/vault_preflight.py index 16ff73d744..02ad1864de 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -280,8 +280,7 @@ def hand_over(delivered: VaultTokenReading | BaseException = outcome) -> None: consumer.hop, ) finally: - # The loop, or the late branch here, clears a raise's traceback. One that is read - # is freed when the loop clears its traceback. + # The loop, or the late branch here, clears a raise's traceback. del outcome, hand_over try: