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..2f3352d59c --- /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 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/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 87d39d70f4..cf2a0307f9 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) | @@ -2292,10 +2292,12 @@ 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 - but `deny` counts, a read included. A write there lets the token widen its own reach, or take 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, 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. - **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 96a33284d5..f6781db615 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,10 +1174,35 @@ 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 (`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`, - `export` and `backup` paths. + `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 (read as written, + so two spellings of one server read as two), every path the store hop calls, and its keys' paths + 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 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, 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 +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. @@ -1253,9 +1278,13 @@ 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; 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 + 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 `GET /security/posture`. @@ -1271,6 +1300,21 @@ 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; 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 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 +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, +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 as not observed at every start unless its policy grants the two paths the probe reads. Neither 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..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 @@ -178,3 +178,58 @@ 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): the connector-secret token's grants on the store's paths can refuse + +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. 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. + +- **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 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`), 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. 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, + 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. 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 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 +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 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 9d907dc1d0..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. 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. 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/api/_ui_seam.py b/messagefoundry/api/_ui_seam.py index a7265df676..095562db48 100644 --- a/messagefoundry/api/_ui_seam.py +++ b/messagefoundry/api/_ui_seam.py @@ -1026,12 +1026,20 @@ #: the other's change, so neither held for the merged surface. Re-derived with ``--write`` over #: both, from ``649e40ac2b7f6902`` and ``be04f29ecb86c73b`` to ``955191cd49e25c20``. #: +#: 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``. +#: +#: Merge of the #4851 entry with main after the #3771 and #6638 entries: each digest was derived +#: without the other's change. Re-derived with ``--write`` over both, from ``55c01eec8a5e8c61`` and +#: ``955191cd49e25c20`` to ``95183db8e6f17738``. +#: #: 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 = "955191cd49e25c20" +ENGINE_UI_SEAM: str = "95183db8e6f17738" @dataclass(frozen=True, slots=True) diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 303a3a5859..87115ba89d 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -235,6 +235,8 @@ UploadedMessageSummary, UploadResendRequest, UploadResendResult, + VaultPrivilegeHopView, + VaultPrivilegeView, ) from messagefoundry.api.multipart import ( MultipartError, @@ -618,7 +620,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"] @@ -6028,6 +6034,32 @@ 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. + # 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. 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) + 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=capped_refusing(h) if visible is None else [], + refusing_count=len(h.refusing), + unexcused=list(h.unexcused), + partial=h.partial, + detail=capped_detail(h) if visible is None else "", + ) + 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() @@ -6075,6 +6107,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, @@ -14025,8 +14058,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 @@ -14050,7 +14083,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 cbe75eefa2..5d7ce3bef5 100644 --- a/messagefoundry/api/models.py +++ b/messagefoundry/api/models.py @@ -1563,6 +1563,38 @@ 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) + refusing_count: int = 0 + 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. ``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) + + 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 +1753,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/config/settings.py b/messagefoundry/config/settings.py index 011d9c2479..090f59ebde 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -8399,8 +8399,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. @@ -12062,8 +12062,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 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/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 deb26ed5ab..e1667c62fb 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 @@ -68,6 +68,7 @@ "EXIT_UNOBSERVABLE", "VAULT_ADMIN_PATHS", "VAULT_OVER_GRANT_OPT_OUT", + "VAULT_REFUSING_CLASS", "HopPrivilege", "HopState", "VaultConsumer", @@ -80,6 +81,7 @@ "serve_verdict", "settings_hops", "store_hop", + "transit_key_paths", "vault_consumers", "vault_admin_paths", "vault_hop", @@ -127,7 +129,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,8 +141,9 @@ class HopPrivilege: detail: str refusing: tuple[str, ...] = () 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, @@ -146,6 +152,7 @@ def as_dict(self) -> dict[str, str | list[str]]: "detail": self.detail, "refusing": list(self.refusing), "unexcused": list(self.unexcused), + "partial": self.partial, } @@ -210,56 +217,116 @@ 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 reach the root-token generation and rekey endpoints +#: (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", + "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 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", + "{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}/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 +#: 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 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 any grant " + "but read or list on a path that uses another hop's key" ) +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 + required: Mapping[str, frozenset[str]], + policies: Iterable[str], + *, + transit_mount: 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 config, rotate, export and backup paths, which + 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 in required: - # 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: - 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)) @@ -388,9 +455,22 @@ 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 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 + 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`` names other hops that hold the SAME token, any grant on a path only those hops need. One token @@ -399,12 +479,14 @@ 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 - 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.""" + **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; :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] = [] @@ -434,22 +516,101 @@ 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)})") + is_key = path in reading.transit_keys + 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") + # 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 extra: + if path in shared_paths or not extra: + continue + if path in reading.other_paths: + # 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 + 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: 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 " + "same token is unknown, a token not having been read" + ) + elif control: + grave.append( + f"{path} grants {_caps(control)}{what} 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" + ) + 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: - 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: + # 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 = [*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 + # 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,17 +629,20 @@ 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 + # 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) 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), *(f"over-granted: {o}" for o in over), *seen, *notes, ] - parts += [f"could not observe: {p}" for p in reading.problems] if state is HopState.CLEAN: parts.append( "paths the engine does not call were read only for the administrative ones; " @@ -496,6 +660,7 @@ def vault_hop( detail, refusing=tuple(grave), unexcused=reading.unexcused, + partial=bool(unread), ) @@ -504,16 +669,24 @@ 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 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`).""" 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 @@ -557,8 +730,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 +983,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 +996,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 +1024,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..f71c52ccd4 100644 --- a/messagefoundry/privilege_probes.py +++ b/messagefoundry/privilege_probes.py @@ -34,11 +34,13 @@ import functools import hashlib +import importlib 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 +from urllib.parse import urlsplit from messagefoundry.controlchars import scrub_log_argument, strip_control_chars from messagefoundry.exception_origin import ( @@ -48,7 +50,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__) @@ -62,6 +64,7 @@ __all__ = [ "VaultTokenReading", "excused_failure", + "preload_vault_probe_imports", "probe_vault", "read_ldap_bind", "read_vault_token", @@ -96,6 +99,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,6 +293,7 @@ def read_vault_token( address: Callable[[], str], build_client: Callable[[str, str], Any], required: Callable[[], Mapping[str, frozenset[str]]], + other_required: Callable[[], Iterable[str]] | None = None, ) -> VaultTokenReading: """Read one token's own policies and capabilities through the engine's client for that hop. @@ -296,6 +305,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_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.""" problems: list[str] = [] @@ -372,9 +386,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 - admin = vault_admin_paths(needed, policies, transit_mount=TRANSIT_MOUNT) + foreign: tuple[str, ...] = () + if other_required is not None: + try: + 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 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_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: @@ -408,9 +443,48 @@ def why(exc: BaseException) -> str: problems=tuple(problems), unexcused=tuple(unexcused), token_ref=token_ref, + transit_keys=transit_keys, + other_paths=other_paths, ) +#: 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", +) + + +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: @@ -442,9 +516,9 @@ def probe_vault( posture=posture, ), lambda: kv_required_capabilities(consumer.refs), + other_required=functools.partial(_store_paths, settings), ) from messagefoundry.store.keyprovider_vault import ( - kek_required_capabilities, store_vault_address, store_vault_client, store_vault_token, @@ -456,23 +530,67 @@ 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_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_paths`, so the two cannot disagree.""" + if kind == "transit": + from messagefoundry.store.crypto_transit import transit_cipher_required_capabilities + + return transit_cipher_required_capabilities() + if kind == "kek": + from messagefoundry.store.keyprovider_vault import 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 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_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 + + 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: """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..02ad1864de 100644 --- a/messagefoundry/vault_preflight.py +++ b/messagefoundry/vault_preflight.py @@ -7,13 +7,19 @@ 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 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, 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: -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`` @@ -38,16 +44,20 @@ from __future__ import annotations import asyncio +import contextvars import json import logging +import threading from collections.abc import Callable from functools import partial from typing import TYPE_CHECKING, Protocol 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, HopPrivilege, HopState, VaultConsumer, @@ -56,7 +66,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 @@ -70,6 +84,8 @@ "VaultAuditStore", "VaultPrivilegeAlertSink", "VaultPrivilegeError", + "capped_detail", + "capped_refusing", "run_vault_privilege_preflight", "vault_privilege_alert_subject", ] @@ -77,11 +93,29 @@ #: 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 + + +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 @@ -143,26 +177,142 @@ def _alert(sink: VaultPrivilegeAlertSink, hop: HopPrivilege, outcome: PreflightO log.exception("vault privilege preflight: the alert sink raised") -def _probe_all( +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.""" + name = type(exc).__name__ + problem = f"the probe raised {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) + + +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.""" + 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 + 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]: - """Each 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: + """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: 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 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.""" + 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 + # runs in the startup preflight, before any listener binds. + preload_vault_probe_imports() + + async def one(consumer: VaultConsumer) -> VaultTokenReading: + 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(outcome: VaultTokenReading | BaseException) -> None: + 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__, + ) + _clear_tracebacks(outcome) + + 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. 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(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. 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__, + ) + _clear_tracebacks(outcome) + else: + log.debug( + "vault privilege preflight: %s finished after its loop closed", + consumer.hop, + ) + finally: + # The loop, or the late branch here, clears a raise's traceback. + del outcome, hand_over + try: - out.append(probe(consumer)) - except Exception as exc: # noqa: BLE001 - classified below, never a pass - problem = f"the probe raised {type(exc).__name__}" + 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 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) - cause = unexcused_cause(exc) - unexcused = () if cause is None else (cause,) - out.append(VaultTokenReading(problems=(problem,), unexcused=unexcused)) - return out + return VaultTokenReading(problems=(problem,), unexcused=(type(exc).__name__,)) + 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; + # an error the probe caught itself can still hold them until a collector pass. + _clear_tracebacks(outcome) + return outcome + + return list(await asyncio.gather(*(one(c) for c in consumers))) async def run_vault_privilege_preflight( @@ -191,7 +341,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) hops = vault_hops(consumers, readings) outcomes = [ vault_preflight_outcome(hop, enforcing=enforcing, over_grant_accepted=over_grant_accepted) @@ -207,29 +357,32 @@ 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, - scrub_log_argument(hop.detail), + hop.partial, + scrub_log_argument(capped_detail(hop)), "; 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": 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/messagefoundry_webconsole/__init__.py b/messagefoundry_webconsole/__init__.py index 95caad4c1c..0c9db5c1f9 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({"955191cd49e25c20"}) +SUPPORTED_ENGINE_SEAMS: frozenset[str] = frozenset({"95183db8e6f17738"}) #: 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/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 diff --git a/tests/golden/webconsole_seam.snapshot b/tests/golden/webconsole_seam.snapshot index 7af88f0d0a..e8c50e09f9 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 -955191cd49e25c20 +95183db8e6f17738 ## dataclass messagefoundry.api._ui_seam.UiDeps engine_seam @@ -332,7 +332,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 @@ -348,6 +348,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, 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_no_store_phi_coverage.py b/tests/test_no_store_phi_coverage.py index cce4c70b34..817ad4d335 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 (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 + # 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 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..42cd5a87b0 --- /dev/null +++ b/tests/test_vault_privilege_preflight_4851.py @@ -0,0 +1,1122 @@ +# 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. 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. +""" + +from __future__ import annotations + +import asyncio +import json +import logging +import threading +from pathlib import Path +from types import SimpleNamespace +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_hops, + 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/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: + 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_required: Any = None) -> VaultTokenReading: + return read_vault_token( + lambda: _TOKEN, + lambda: _VAULT_ADDR, + lambda a, t: vault, + lambda: {_KV_PATH: frozenset({"read"})}, + 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_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"]}))) + assert alone.refusing == () + + +@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_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_required=lambda: [key])) + assert hop.state is HopState.OVER_GRANTED and hop.refusing == () + assert f"{key} grants read; the engine calls it only with another hop's token" in hop.detail + + +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; 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 + ) + + +@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}" + 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.""" + decrypt = f"transit/decrypt/{_KEK}" + 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]) + + +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 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 + # 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 + ) + # 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 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]) + assert any(r.startswith(f"{key} grants delete") for r in hop.refusing) + + +# --- 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, + *, + 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]) + release = _released_soon() + + def probe(consumer: VaultConsumer) -> VaultTokenReading: + 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())) + + return probe + + +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",)) + + def probe(consumer: VaultConsumer) -> VaultTokenReading: + started.set() + assert release.wait(10) + return _reading(vault) + + store = _AuditStore() + + 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 + ) + ) + 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 + + +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: + decrypt = f"transit/decrypt/{_KEK}" + 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"]) + + +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() + 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 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"]) + + +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 + # 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: + """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 KeyProviderError("the store key name is not set") + + reading = _kv_reading(_FakeVault(caps={_KV_PATH: ["read"]}), other_required=unset) + assert reading.capabilities + 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_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) + probe_vault(_KV, _VAULT_SETTINGS) + 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_required=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 ---------------------------------------------------------------------- + + +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 + 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. + 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["partial"] is False + assert detail["refusing_count"] > 20 + assert len(detail["refusing"]) == 20 + assert all(len(r) <= 300 for r in detail["refusing"]) + + +# --- the probes run side by side, off the event loop ------------------------------------------- + + +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 + + with pytest.raises(VaultPrivilegeError, match="Stop"): + await asyncio.wait_for( + run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=stop, + ), + 10, + ) + + +async def test_a_probe_thread_whose_logging_raises_still_refuses() -> None: + """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] = [] + + class RaiseOnProbeThreads(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + 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=r"vault\.store: RuntimeError"): + await asyncio.wait_for( + run_vault_privilege_preflight( + _VAULT_SETTINGS, + _AuditStore(), + enforcing=True, + over_grant_accepted=False, + probe=fail, + ), + 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: + """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() + ran_on: list[threading.Thread] = [] + + def hang(consumer: VaultConsumer) -> VaultTokenReading: + ran_on.append(threading.current_thread()) + started.set() + release.wait(10) + return VaultTokenReading() + + 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) + [thread] = ran_on + assert thread.is_alive() and thread.daemon + finally: + task.cancel() + 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.""" + + +@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. A raise inside + an ``except`` block carries the first raise, whose traceback reaches the same frames.""" + import gc + import weakref + + refs: list[weakref.ref[_Held]] = [] + + def fail(consumer: VaultConsumer) -> VaultTokenReading: + held = _Held() + refs.append(weakref.ref(held)) + 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() + 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: + 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: + release.set() + 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: + 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, + _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; 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 + + +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"] + # 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] + + +class _NoThread(threading.Thread): + def start(self) -> None: + raise RuntimeError("can't start new thread") + + +async def test_a_probe_thread_that_cannot_start_only_warns_under_warn( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # 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, + store, + enforcing=False, + over_grant_accepted=False, + probe=_probe(_FakeVault(caps=_least_caps())), + ) + assert hop.state is HopState.UNOBSERVABLE + 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.""" + # 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, + _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: + 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 + + # 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_no_such_module_4851", "colorsys"), + ) + assert "colorsys" not in sys.modules + privilege_probes.preload_vault_probe_imports() + assert "colorsys" in sys.modules + + +# --- 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 + + +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 + + 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"] == []