diff --git a/changelog.d/5526-remainder.security.md b/changelog.d/5526-remainder.security.md new file mode 100644 index 0000000000..e0f140debf --- /dev/null +++ b/changelog.d/5526-remainder.security.md @@ -0,0 +1,15 @@ +- **One credential owns the `Authorization` header on a SOAP or REST outbound.** A SOAP outbound + now refuses at construction a `bearer_token` beside a Basic pair, as REST and DICOMweb already + did; it used to send Basic and drop the token without a word. A SOAP or REST outbound refuses a + detached-JWS signing header named `Authorization`, in any spelling, beside a configured or + minted credential for that header, at least HTTP Basic, a `bearer_token`, an OAuth2 or SMART + provider, or an `Authorization` entry in `headers`. The signature is written after the + credential, so it replaced the credential on every send; beside HTTP Digest it was already + refused. The FHIR destination still refuses it only beside HTTP Digest. The static-credential + inventory lists HTTP Basic alone where both a `bearer_token` and a Basic pair are set. It reads + an `env()` `http_auth` as the build resolves it, and one it cannot resolve as HTTP Digest, + except beside an OAuth2 or SMART provider whose enabled flags, and SMART token URL, are + literal. The build refuses Digest beside a bearer provider, but at least an `env()` OAuth2 + token URL with no `oauth2_enabled` key can still resolve the provider off, and the inventory + does not list Digest there. + (`BACKLOG #5526`) diff --git a/changelog.d/5912.security.md b/changelog.d/5912.security.md index 5099d184ba..8c19f2b41f 100644 --- a/changelog.d/5912.security.md +++ b/changelog.d/5912.security.md @@ -1,48 +1,25 @@ - **A SOAP fault's Sender or Receiver class is read first from its code element.** The code is now - read first from the Fault's first child, a comment, CDATA section or processing instruction before - it stepped over whole: SOAP 1.1's `faultcode`, or SOAP 1.2's `Code` and the `Value` that is the Code's own - first child. The shipped code took the Fault's first `Value` ahead of any `faultcode`. Where the - first-child read yields a code, a `Value` inside a comment, CDATA section or processing - instruction ahead of it no longer decides the class; on a first deployment that could have made a - Sender fault read as a Receiver one and retry until the attempt limit. Where that first-child - read yields no code, the code falls back to the shipped search's rule: from the Fault start tag - the Fault search chose to the first `` after it, or the reply's end, the first `Value` - ahead of the first `faultcode`, else that `faultcode`; a `Value` there that holds no code is not passed - over. So there a `Value` in a Subcode, Role, - Node, Reason or Detail ahead of the code element, or one ahead of a SOAP 1.1 `faultcode`, or one - after a `Code` that is empty, self-closing or has no `Value` first, still decides the class, as - in the shipped code, and a Sender fault of such a shape may still retry. Like the shipped search, - the fallback steps over no markup: a `` inside a comment ends its range, and a - `faultcode` or `Value` inside markup counts. So - `busysoap:Server` - reads no code and dead-letters, as in the shipped code. At least these shapes, each ahead of the code - element, take the fallback: a SOAP 1.1 `faultstring` before the `faultcode`, a SOAP 1.2 `Reason` - before the `Code`, a DOCTYPE or other `` or `` inside it no longer ends the - first-child read; the Fault search reads the reply from its start, - so this holds even where the Body start tag sits in that markup. Where every Fault start tag after - the Body start tag (with no Body start tag, every Fault start tag) is inside such markup, the - first of them is still read as the Fault, as in the shipped code; where no Fault start tag - follows the Body start tag, the first before it outside such markup is read, else the first - before it. So such a reply never newly reads as delivered. - One first-child shape is read again: where the first `soap:Server` - reads `soap:Server` and retries. No other code text is read again, so such a read never - changes a Sender or Receiver reading. In the fallback such a `` or ``, inside such + markup no longer decides which Fault is read or where the read ends; `_find_fault` and + `_fault_code` say where that does not hold. Where every Fault start tag after the Body start + tag is inside such markup, the first of them is still read as the Fault, so such a reply never + newly reads as delivered. A Fault where neither read finds a code reads as a permanent fault, + as one with no code always did. The WS-Security check still searches the reply from where the + Fault search starts, so a WS-Security code ahead of the real Body start tag, behind a Body start + tag inside such markup, no longer dead-letters a reply whose Body holds a Receiver fault; that + reply now retries. Unchanged: whether a Fault counts. (`BACKLOG #5912`) diff --git a/changelog.d/6010-transit-key-name-refusals.fixed.md b/changelog.d/6010-transit-key-name-refusals.fixed.md new file mode 100644 index 0000000000..0049d98be8 --- /dev/null +++ b/changelog.d/6010-transit-key-name-refusals.fixed.md @@ -0,0 +1,8 @@ +- **A malformed or unset Vault Transit key name is refused with its own text.** The refusals of a + malformed `MEFOR_STORE_VAULT_TRANSIT_KEY`, `MEFOR_STORE_TRANSIT_KEY` or + `MEFOR_STORE_TRANSIT_AUDIT_KEY`, of an unset `MEFOR_STORE_TRANSIT_KEY`, and of an unwrapped DEK + that is not base64 of 32 bytes under `key_provider = "vault"` now reach the operator as written, naming the variable to fix, where a store open used to + show a generic "the key source failed" or "the Vault Transit cipher could not be built". A data + key name and an audit key name that are both wrong are named in one refusal. The Transit key + type check, the Transit cipher itself and the row seal verify now check the key name too. + (`BACKLOG #6010`, `BACKLOG #6710`) diff --git a/changelog.d/6015-read-over-grant-beside-unread.security.md b/changelog.d/6015-read-over-grant-beside-unread.security.md new file mode 100644 index 0000000000..3a2939040f --- /dev/null +++ b/changelog.d/6015-read-over-grant-beside-unread.security.md @@ -0,0 +1,16 @@ +- **A store over-grant that was read now refuses under enforce even when a neighbouring grant + could not be read.** On SQL Server, a probe answer that is NULL, or any value but 0 or 1, is + not read. Under `[security].enforcement = "enforce"` (the default) with + `[store].require_least_privilege` unset, an over-grant the store privilege preflight read as + held, such as `sysadmin`, `db_owner` or a `CONTROL`, used to be demoted to an unobserved + warning when a fixed role, `CONTROL SERVER` or database `CONTROL` was not read. The report now stays OBSERVED with that + over-grant in the excess, so the start refuses unless the audited over-grant opt-out accepts it, + and `check-privileges` exits 3 (over-grant) where it used to exit 4 (could not read). Under + `schema_management = "external"` the grants counted only there, at least `CREATE TABLE`, + `ALTER` on the default schema, `VIEW DEFINITION` and the audit-table rights, count as read + over-grants the same way. With `[store].require_least_privilege` set, the start refused before + and still does. Grants that were not read are named in the log line, the over-grant posture + entry and a new `unread` field in the preflight's audit row; the PostgreSQL store probe fills + that field too, for its audit-table grants and an unresolved schema. Under external, + `db_securityadmin` no longer adds a separate `VIEW DEFINITION` finding, since the role carries + that right. (`BACKLOG #6015`, `BACKLOG #6714`) diff --git a/changelog.d/6717-row-seal-transit-non-finite.fixed.md b/changelog.d/6717-row-seal-transit-non-finite.fixed.md new file mode 100644 index 0000000000..6c50d917b8 --- /dev/null +++ b/changelog.d/6717-row-seal-transit-non-finite.fixed.md @@ -0,0 +1,6 @@ +- **The Vault Transit row sealer refuses a non-finite float, and reads a non-text seal as + malformed.** It now refuses to seal a float that is a NaN or an infinity, as the local sealer + already did, and both raise `NonFiniteSealValueError`, a `ValueError` subclass. A stored seal + that is not text (a blob or a number) reads as malformed under Transit rather than raising: a + session read with one fails its seal check, and a write over such a row is refused as a failed + seal. The bytes a seal covers are unchanged. (`BACKLOG #6717`, `BACKLOG #6718`) diff --git a/changelog.d/8299-fhir-lookup-gate-order.fixed.md b/changelog.d/8299-fhir-lookup-gate-order.fixed.md new file mode 100644 index 0000000000..bf1127b851 --- /dev/null +++ b/changelog.d/8299-fhir-lookup-gate-order.fixed.md @@ -0,0 +1,11 @@ +- **A `FhirLookup` refused for a setting leaves no crossing record from another lookup first, in + at least these cases.** Its url and header screens, the length limits on its static url and + headers, its `timeout_seconds` and its hop declarations are now checked for every lookup before + any lookup reaches a hop gate, and a lookup's bearer is judged against a cleartext `http` read + before its SMART token provider is built. A length refusal now names the lookup. A refusal from + a check that runs later in the build can still follow such a record. A FHIR destination or + `FhirLookup` whose `headers` is not a table, which sets one of `basic_user` and + `basic_password` without the other, puts a `:` in `basic_user`, or sets `bearer_token` beside a + Basic pair is refused at build. These used to build and then send no headers, no Basic + credential, a Basic credential split at the wrong colon, or Basic in place of the bearer. + (`BACKLOG #8299`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5a4db31b9c..2b1d4bf099 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -179,15 +179,15 @@ backend-limited. | `group_commit_max_batch` | int | `64` | **SQLite only.** Flush threshold for the group-commit committer: once this many members are enrolled in the open batch it commits immediately rather than waiting out the rest of `group_commit_window_ms`, bounding batch size + latency under load. Ignored when group-commit is off (`group_commit_window_ms = 0`). | | `fifo_claim_batch` | int | `1` | all backends (ADR 0058). Max rows the **INGRESS/ROUTED** FIFO claim takes per commit. `1` = **OFF** (the workers claim one row per commit — byte-identical to before). `> 1` (clamped `1..64`) claims the **contiguous due head-prefix** in one commit and then processes each row in strict FIFO order with its own off-loop route/transform + separate handoff, amortizing the standalone claim commit toward 1/N. A not-due or producer-locked head still blocks the lane (strict per-lane FIFO, #285). The **outbound/delivery** claim is never batched. Opt-in throughput tuning (recommend `8`–`16`); size against worst-case message size, since N decrypted bodies are resident per lane between the claim and the N handoffs. | | `fifo_claim_fold_reset` | bool | `false` | **SQL Server only** ([ADR 0114](adr/0114-phase-4-claim-path-call-complexity-reduction-driver-interface-redesign-ingress-routed-reset-fold.md) sub-lever C). Folds the pooled claim's session `LOCK_TIMEOUT` reset into the claim batch on the **clean success path at INGRESS/ROUTED** (the write-less commit#2 disappears; the shielded finally-guard still runs on every non-clean exit — 1222, kept≠claimed, cancellation, any error). OUTBOUND/RESPONSE are never folded. `false` = **byte-identical** shipped batch + guard. Flip only after its own ADR 0114 §8 bench gate (AC-14). | -| `fifo_claim_proc` | bool | `false` | **SQL Server only** (ADR 0114 sub-lever A). Executes the pooled claim via the two lane-family versioned procs `mefor_claim_fifo_heads_cid_v2` / `_dst_v2`, deployed and called in the store's schema ([`DEPLOY-SERVER-DB.md`](DEPLOY-SERVER-DB.md) §1.1 says which) (fixed-arity `{CALL}`, one JSON lanes parameter) instead of the ~3 KB ad-hoc batch. Needs database `COMPATIBILITY_LEVEL >= 130` (SQL Server 2016); **fails safe to the batch, loudly**, whenever the startup gate cannot verify both deployed bodies against this build — at least: a missing proc, a body matching no form this build deploys (hand edit, hand deploy, or a body changed without bumping the proc version), a definition this principal cannot read (no `VIEW DEFINITION`, or `WITH ENCRYPTION`), or compat < 130 — never a lane outage. A hardened split-principal deployment must `GRANT EXECUTE` and `GRANT VIEW DEFINITION ON OBJECT::` on both called procs to the runtime principal, both again for each new proc version; the gate reads the bodies it verifies through that `VIEW DEFINITION`. Grant it on each proc and by no wider route: under `schema_management = "external"` the startup privilege preflight counts `VIEW DEFINITION` that reaches the login's default schema or `dbo` by any route as an over-grant, at least a grant on the schema, the database or the server, schema ownership, or a role or group membership ([`DEPLOY-SERVER-DB.md`](DEPLOY-SERVER-DB.md) §1.1; §1.3 says when an over-grant refuses the start). `false` = byte-identical. Flip only after its own §8 gate (AC-14). | +| `fifo_claim_proc` | bool | `false` | **SQL Server only** (ADR 0114 sub-lever A). Executes the pooled claim via the two lane-family versioned procs `mefor_claim_fifo_heads_cid_v2` / `_dst_v2`, deployed and called in the store's schema ([`DEPLOY-SERVER-DB.md`](DEPLOY-SERVER-DB.md) §1.1 says which) (fixed-arity `{CALL}`, one JSON lanes parameter) instead of the ~3 KB ad-hoc batch. Needs database `COMPATIBILITY_LEVEL >= 130` (SQL Server 2016); **fails safe to the batch, loudly**, whenever the startup gate cannot verify both deployed bodies against this build — at least: a missing proc, a body matching no form this build deploys (hand edit, hand deploy, or a body changed without bumping the proc version), a definition this principal cannot read (no `VIEW DEFINITION`, or `WITH ENCRYPTION`), or compat < 130 — never a lane outage. A hardened split-principal deployment must `GRANT EXECUTE ON OBJECT::` and `GRANT VIEW DEFINITION ON OBJECT::` on each of the two called procs to the runtime principal, both again for each new proc version; the gate reads the bodies it verifies through that `VIEW DEFINITION`. Grant it on each proc and by no wider route: under `schema_management = "external"` the startup privilege preflight counts `VIEW DEFINITION` that reaches the login's default schema or `dbo` by any route as an over-grant, at least a grant on the schema, the database or the server, schema ownership, or a role or group membership ([`DEPLOY-SERVER-DB.md`](DEPLOY-SERVER-DB.md) §1.1; §1.3 says when an over-grant refuses the start). `false` = byte-identical. Flip only after its own §8 gate (AC-14). | | `fifo_claim_prepared` | bool | `false` | **SQL Server only** (ADR 0114 sub-lever B). Stabilizes the pooled claim's statement text (one JSON lanes parameter) and retains a prepared claim cursor on store-owned dedicated connections (INGRESS/ROUTED; the non-DDL fallback lane to `fifo_claim_proc`). **Logs + no-ops unless `fifo_claim_fold_reset` is on** (without the fold the finally-guard's reset would evict the one-slot prepare cache every call). `false` = byte-identical. Flip only after its own §8 gate (AC-14). | | `encryption_key` | secret | — | **env only** (`MEFOR_STORE_ENCRYPTION_KEY`); base64 32-byte **active** key — when set, PHI columns (`raw`/`payload` + `error`/`last_error`/`detail`) are AES-256-GCM-encrypted at rest. Mint one with `messagefoundry gen-key`. **Not in a Windows service's environment lists:** `serve` and `supervise` refuse it there, so use `encryption_key_file` ([SERVICE.md](SERVICE.md#protect-the-store-encryption-key-at-rest-wp-11d)). Empty = off, unless `encryption_keys_retired` is set: then it is refused, as that row says. See [PHI.md §3](PHI.md#3-encryption-at-rest). | | `encryption_keys_retired` | secret | — | **env only** (`MEFOR_STORE_ENCRYPTION_KEYS_RETIRED`); comma-separated base64 **decrypt-only** keys kept available during a rotation until `messagefoundry rotate-key` finishes re-encrypting under the active key (ASVS 11.2.2). No engine start after it needs them for the secret-rotation watcher ([PHI.md §3](PHI.md#3-encryption-at-rest), BACKLOG #3472). Retired keys with no active key are **refused, not run keyless** (BACKLOG #5310, #5308): that is a rotation missing its new key, and a keyless store would write new rows unencrypted. Under `cipher_provider = "vault_transit"` Transit encrypts the rows, and the refusal names the DR backup and restore instead, which read the local keys and would find no active one. An `encryption_key` of blanks only counts as no active key. Under a built-in `key_provider` with no local active key configured, `serve`, `supervise` and `provision-admin` refuse before opening; an external provider such as `vault` supplies the active key itself, so the retired local keys stay decrypt-only beside it. At least a store open, a DR backup, `restore-verify`, `restore` and `rotate-key` refuse whenever no active key resolves. Under `cipher_provider = "vault_transit"` the store open reads no local key, so it does not refuse: a key that is configured but that the pinned `key_provider` ignores passes the start gate there, and only the DR paths refuse. Not under the Windows service: `serve` and `supervise` refuse a store key in the service's environment lists ([SERVICE.md](SERVICE.md#protect-the-store-encryption-key-at-rest-wp-11d)). | | `encryption_key_file` | path | — | Windows **DPAPI-protected** key file (WP-11d, ASVS 13.3.1) — a path produced by `messagefoundry protect-key`. When `encryption_key` is unset and this is set, the active key is `CryptUnprotectData`'d from this file at store open, so the plaintext key never sits in the service environment. Windows-only, and the **env key takes precedence** when both are present. A **path, not a secret** — it may live in the file. Unset = use `encryption_key`. **Under the Windows service, use this file:** `serve` and `supervise` refuse the store key in the service's environment lists ([SERVICE.md](SERVICE.md#protect-the-store-encryption-key-at-rest-wp-11d)). `protect-key` creates the file restricted and refuses to replace an existing one. When the provider reads this file, `serve` first checks that no broad account can read it, and refuses to start under `[security].enforcement = "enforce"` if one can ([PHI.md](PHI.md), "Key files"). | | `aad_bind` | bool | `true` | **not a secret** (`MEFOR_STORE_AAD_BIND`); cell binding (ASVS 11.3.3, [ADR 0019](adr/0019-pluggable-keyprovider-hsm-kms-vault.md)). New at-rest AES-256-GCM writes use the cell-bound writer, `mfenc:v4` (`mfenc:v2` before [ADR 0196](adr/0196-a-fresh-or-rewound-store-must-not-restart-a-store-key-s-aes-gcm-invocation-count.md), which seals each store under its own HKDF data sub-key) — each value is bound to its `(table, column, row)` cell via GCM Associated Data, so a ciphertext cut-and-pasted into another cell **fails the auth tag** (dead-lettered `CipherError`) instead of silently decrypting. **On by default** (ADR 0148 GIVEN 1: the shipped configuration runs the hardened path). Setting it `false` selects the frozen `mfenc:v1` writer (byte-identical at rest) and is a **loosening** — `security_loosenings()` names it, so the opt-out is never silent. No effect without an `encryption_key` (the identity cipher has nothing to bind). Legacy `v1` rows still decrypt (dual-read); `messagefoundry rotate-key` upgrades them `v1` to `v4`, so the default is safe and reversible on an existing store. | | `allow_unmarked_ciphertext` | bool | `false` | **not a secret** (`MEFOR_STORE_ALLOW_UNMARKED_CIPHERTEXT`); refuse unmarked values (ASVS 11.3.3, BACKLOG #1169). On a keyed store, a non-blank value with no `mfenc:` marker in an encrypted column is **refused** (`CipherError`, plus an `integrity_drift` alert with subject `store-cipher` naming only the table and column) instead of being read back as plaintext: it is a stripped marker or a planted row. A purged `''` is never refused. The keyed open seals legacy plaintext only on a `(table, column)` that is still unsealed, one transaction per column. A column is sealed once it holds ciphertext, or once the store has recorded it in its `keyed_surface` table (BACKLOG #3383). A writable keyed open that finishes its sweep records every column. So a plant into a recorded column is refused even when the column holds no ciphertext. Setting it `true` restores the old behaviour (plaintext passthrough, and the open seals every unmarked value, recorded column or not) and is a **loosening** — `security_loosenings()` names it. No effect without an `encryption_key`. **It covers the uploaded-file store too** (owner ruling 2026-09-23): on a keyed store a plaintext upload under `uploads_dir` is refused on every read, and `messagefoundry rotate-key` seals it where it can (not every one: [PHI.md](PHI.md) §3 says which it leaves, and what removes them), alerting under its own subject `upload-cipher`, and `serve` logs the count of such uploads at startup. Setting this `true` restores the upload passthrough as well. Under `cipher_provider = "vault_transit"` uploads keep the passthrough either way; [PHI.md](PHI.md) §3 says why. | -| `key_provider` | enum | `auto` | selects **how** the active/retired DEK bytes are *sourced* — never how they are used (the cipher, keyring, and `mfenc:v1` format are unchanged; ADR 0019, ASVS 13.3.3). `auto` (default) is the env-then-DPAPI ladder, **byte-identical** to the pre-seam behavior; `env` pins `MEFOR_STORE_ENCRYPTION_KEY` and `dpapi` pins `encryption_key_file`, and each ignores the other source. A key set only in the source the pinned provider ignores is **refused, not used as keyless** (BACKLOG #2077): `serve`, `supervise` and `provision-admin` refuse before opening, whatever the audited opt-out says, and `open_store` refuses for every other command. Set `auto` or the source the provider reads. Under `cipher_provider = "vault_transit"` the gate still counts any local key, because the store never resolves `key_provider` there; DR backups do, and refuse the ignored key. `vault` **is built** ([store/keyprovider_vault.py](../messagefoundry/store/keyprovider_vault.py)): it envelope-decrypts a wrapped DEK through HashiCorp Vault **Transit** and needs the optional `[vault]` extra. Its wiring comes from the environment. `MEFOR_STORE_VAULT_TRANSIT_KEY` (the KEK name; not the next row's `MEFOR_STORE_TRANSIT_KEY`) and `MEFOR_STORE_VAULT_WRAPPED_DEK` are required. `MEFOR_STORE_VAULT_ADDR` and `MEFOR_STORE_VAULT_TOKEN` are required too: an unset or empty one is **refused**, naming the variable, and hvac's own `VAULT_ADDR`, `VAULT_TOKEN` and `~/.vault-token` are never read (BACKLOG #2851). The token may come from the [secrets directory](#the-secrets-directory-mefor_secrets_directory) instead of the environment; on Windows, supply it only there. A Vault Agent sink can write it there except under the default virtual account or any other Windows account but a dedicated engine account the site already chose. `MEFOR_STORE_VAULT_CA_FILE` is optional. The unwrap runs wherever the key is resolved, at least at every store open and every DR backup pass. It reads the KEK's metadata to check its type before decrypting, so the token needs both. A missing required variable or extra, a KEK of an unsuitable type, a Vault that is off the box with no `vault_revocation_attested` (two rows below), or a failed unwrap **fails closed**: the store does not open, or that backup pass fails. Only the **active** key comes from Vault; retired keys still come from `encryption_keys_retired`, in plaintext. The unwrapped DEK feeds the in-process cipher, so unlike `cipher_provider = "vault_transit"` it does enter engine heap. **The keyless-PHI gate counts it as a key** (BACKLOG #1998). `_store_key_configured` in [`__main__.py`](../messagefoundry/__main__.py) treats every external provider as a configured key without resolving it, because the gate runs before the store opens and must not need the network. So a PHI instance set to `vault` with no local key passes the gate, and a provider that cannot resolve fails closed when the store opens. Under `cipher_provider = "vault_transit"` the store never resolves `key_provider`; DR backups still do, and fail closed there. The four external names ADR 0019 declared and nobody built, `aws_kms`, `azure_kv`, `gcp_kms` and `pkcs11`, were removed (vault BACKLOG #2595). The setting is not checked when the settings load, so an unknown name **fails closed** wherever the key is resolved: at store open, or, under `cipher_provider = "vault_transit"`, at the first DR backup pass. Never a silent downgrade. Names a *provider*, not key material, so it is **not** a secret. | -| `cipher_provider` | enum | `aesgcm` | selects the at-rest **cipher itself** — distinct from `key_provider`, which only *sources* DEK bytes for the in-process cipher ([ADR 0138](adr/0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md), ASVS 13.3.3). `aesgcm` (the default) is that in-process AES-256-GCM cipher, byte-identical to today. `vault_transit` performs the bulk encrypt/decrypt **inside** Vault/OpenBao Transit, so the plaintext DEK never enters engine heap; at-rest values then carry the `mfenc:v3:` marker, the local `encryption_key`/`key_provider` go unused (Transit holds the key), and the audit chain is keyed by Transit's `generate_hmac` — computed inside the vault, so no HMAC key enters heap either. Threaded through **all three** backends. Vault address / token / data-key name come from `MEFOR_STORE_VAULT_ADDR`, `MEFOR_STORE_VAULT_TOKEN` and `MEFOR_STORE_TRANSIT_KEY` (optionally `MEFOR_STORE_TRANSIT_AUDIT_KEY`). All three are required: an unset address or token is refused as the previous row says, with no fallback to `VAULT_ADDR`, `VAULT_TOKEN` or `~/.vault-token` (BACKLOG #2851). The token is read as the previous row says, from the secrets directory before the environment, and on Windows supplied only in that directory. This cipher reads it once, when the store opens, so a token replaced later takes effect only at the next start. Names a *provider*, not key material, so it is **not** a secret. Any other value **fails closed** at `open_store` — never a silent downgrade to plaintext. **Needs the optional `[vault]` extra** (`pip install 'messagefoundry[vault]'` — hvac); lazy-imported, so a base install pulls no Vault SDK and an absent extra fails closed at `open_store` rather than degrading. **At least four preconditions before you plan a deployment on this — read the three here, and the `vault_revocation_attested` row below for the fourth: a Vault that is off the box is refused without it.** (1) *The keyless-PHI serve gate does not treat this setting as a key.* [`__main__.py`](../messagefoundry/__main__.py)'s gate tests `encryption_key` / `encryption_key_file` and an external `key_provider` (previous row). It consults `cipher_provider` only to count a local key that a pinned `key_provider` ignores (BACKLOG #2077). All three built-in environment names derive PHI, so a PHI instance configured for `vault_transit` **with no local key and no external `key_provider` still refuses to start (exit 2)** and points you at `messagefoundry gen-key`. Forcing past it with `[security].allow_unencrypted_phi` (+ `…_under_strict_enforcement`) makes `security_loosenings()` and `GET /security/posture` publish the instance as *PHI stored UNENCRYPTED at rest* while it is in fact encrypted inside Transit — a false read-out, not a real posture. Until the gate learns `cipher_provider`, **also configure a local `encryption_key`**, with a `key_provider` that reads it (`auto` or `env`): the Transit cipher never reads it, but it satisfies the gate, and it remains the key `.mfbak` DR archives actually use (`resolve_active_key` never consults `cipher_provider`, so Transit does **not** cover backups). (2) *Greenfield stores only.* The Transit cipher **fails closed** (`CipherError`) on any pre-existing `mfenc:v1`/`v2`/`v4` value, and `rotate-key` refuses to run in this mode — so there is **no in-place migration** off an already-encrypted store today. Flipping this on a populated store makes its historical PHI unreadable. (3) *The AES-GCM bound is yours, and `serve` needs your recorded attestation of it* (BACKLOG #2337). The engine counts no encryptions on this cipher, so rotate the Transit data key (`MEFOR_STORE_TRANSIT_KEY`) before any one key version seals 2^32 values; plan to rotate by 2^31, sized from the peak encrypt rate (Vault's `auto_rotate_period`, or a manual schedule). Then run `messagefoundry store attest-transit-bound --reason ""` once, on the host, or `serve` **refuses to start** under `[security].enforcement = enforce`. What the record holds, what keeps or voids it, and what it does not check are in [SECURITY.md](SECURITY.md), *On vault_transit, a recorded attestation stands in for the AES-GCM count*. | +| `key_provider` | enum | `auto` | selects **how** the active/retired DEK bytes are *sourced* — never how they are used (the cipher, keyring, and `mfenc:v1` format are unchanged; ADR 0019, ASVS 13.3.3). `auto` (default) is the env-then-DPAPI ladder, **byte-identical** to the pre-seam behavior; `env` pins `MEFOR_STORE_ENCRYPTION_KEY` and `dpapi` pins `encryption_key_file`, and each ignores the other source. A key set only in the source the pinned provider ignores is **refused, not used as keyless** (BACKLOG #2077): `serve`, `supervise` and `provision-admin` refuse before opening, whatever the audited opt-out says, and `open_store` refuses for every other command. Set `auto` or the source the provider reads. Under `cipher_provider = "vault_transit"` the gate still counts any local key, because the store never resolves `key_provider` there; DR backups do, and refuse the ignored key. `vault` **is built** ([store/keyprovider_vault.py](../messagefoundry/store/keyprovider_vault.py)): it envelope-decrypts a wrapped DEK through HashiCorp Vault **Transit** and needs the optional `[vault]` extra. Its wiring comes from the environment. `MEFOR_STORE_VAULT_TRANSIT_KEY` (the KEK name; not the next row's `MEFOR_STORE_TRANSIT_KEY`) and `MEFOR_STORE_VAULT_WRAPPED_DEK` are required. The KEK name must be in the shape Vault gives Transit key names: ASCII letters, digits and underscores, with dots or hyphens only between them. Any other name is **refused**, naming the variable (BACKLOG #6010). The wrapped DEK must unwrap to base64 of exactly 32 bytes; any other plaintext is **refused** (BACKLOG #6710). `MEFOR_STORE_VAULT_ADDR` and `MEFOR_STORE_VAULT_TOKEN` are required too: an unset or empty one is **refused**, naming the variable, and hvac's own `VAULT_ADDR`, `VAULT_TOKEN` and `~/.vault-token` are never read (BACKLOG #2851). The token may come from the [secrets directory](#the-secrets-directory-mefor_secrets_directory) instead of the environment; on Windows, supply it only there. A Vault Agent sink can write it there except under the default virtual account or any other Windows account but a dedicated engine account the site already chose. `MEFOR_STORE_VAULT_CA_FILE` is optional. The unwrap runs wherever the key is resolved, at least at every store open and every DR backup pass. It reads the KEK's metadata to check its type before decrypting, so the token needs both. A missing required variable or extra, a KEK of an unsuitable type, a Vault that is off the box with no `vault_revocation_attested` (two rows below), or a failed unwrap **fails closed**: the store does not open, or that backup pass fails. Only the **active** key comes from Vault; retired keys still come from `encryption_keys_retired`, in plaintext. The unwrapped DEK feeds the in-process cipher, so unlike `cipher_provider = "vault_transit"` it does enter engine heap. **The keyless-PHI gate counts it as a key** (BACKLOG #1998). `_store_key_configured` in [`__main__.py`](../messagefoundry/__main__.py) treats every external provider as a configured key without resolving it, because the gate runs before the store opens and must not need the network. So a PHI instance set to `vault` with no local key passes the gate, and a provider that cannot resolve fails closed when the store opens. Under `cipher_provider = "vault_transit"` the store never resolves `key_provider`; DR backups still do, and fail closed there. The four external names ADR 0019 declared and nobody built, `aws_kms`, `azure_kv`, `gcp_kms` and `pkcs11`, were removed (vault BACKLOG #2595). The setting is not checked when the settings load, so an unknown name **fails closed** wherever the key is resolved: at store open, or, under `cipher_provider = "vault_transit"`, at the first DR backup pass. Never a silent downgrade. Names a *provider*, not key material, so it is **not** a secret. | +| `cipher_provider` | enum | `aesgcm` | selects the at-rest **cipher itself** — distinct from `key_provider`, which only *sources* DEK bytes for the in-process cipher ([ADR 0138](adr/0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md), ASVS 13.3.3). `aesgcm` (the default) is that in-process AES-256-GCM cipher, byte-identical to today. `vault_transit` performs the bulk encrypt/decrypt **inside** Vault/OpenBao Transit, so the plaintext DEK never enters engine heap; at-rest values then carry the `mfenc:v3:` marker, the local `encryption_key`/`key_provider` go unused (Transit holds the key), and the audit chain is keyed by Transit's `generate_hmac` — computed inside the vault, so no HMAC key enters heap either. Threaded through **all three** backends. Vault address / token / data-key name come from `MEFOR_STORE_VAULT_ADDR`, `MEFOR_STORE_VAULT_TOKEN` and `MEFOR_STORE_TRANSIT_KEY` (optionally `MEFOR_STORE_TRANSIT_AUDIT_KEY`). Each key name must have the KEK name's shape (previous row) and is **refused** otherwise, one refusal naming each variable to fix (BACKLOG #6010). All three are required: an unset address or token is refused as the previous row says, with no fallback to `VAULT_ADDR`, `VAULT_TOKEN` or `~/.vault-token` (BACKLOG #2851). The token is read as the previous row says, from the secrets directory before the environment, and on Windows supplied only in that directory. This cipher reads it once, when the store opens, so a token replaced later takes effect only at the next start. Names a *provider*, not key material, so it is **not** a secret. Any other value **fails closed** at `open_store` — never a silent downgrade to plaintext. **Needs the optional `[vault]` extra** (`pip install 'messagefoundry[vault]'` — hvac); lazy-imported, so a base install pulls no Vault SDK and an absent extra fails closed at `open_store` rather than degrading. **At least four preconditions before you plan a deployment on this — read the three here, and the `vault_revocation_attested` row below for the fourth: a Vault that is off the box is refused without it.** (1) *The keyless-PHI serve gate does not treat this setting as a key.* [`__main__.py`](../messagefoundry/__main__.py)'s gate tests `encryption_key` / `encryption_key_file` and an external `key_provider` (previous row). It consults `cipher_provider` only to count a local key that a pinned `key_provider` ignores (BACKLOG #2077). All three built-in environment names derive PHI, so a PHI instance configured for `vault_transit` **with no local key and no external `key_provider` still refuses to start (exit 2)** and points you at `messagefoundry gen-key`. Forcing past it with `[security].allow_unencrypted_phi` (+ `…_under_strict_enforcement`) makes `security_loosenings()` and `GET /security/posture` publish the instance as *PHI stored UNENCRYPTED at rest* while it is in fact encrypted inside Transit — a false read-out, not a real posture. Until the gate learns `cipher_provider`, **also configure a local `encryption_key`**, with a `key_provider` that reads it (`auto` or `env`): the Transit cipher never reads it, but it satisfies the gate, and it remains the key `.mfbak` DR archives actually use (`resolve_active_key` never consults `cipher_provider`, so Transit does **not** cover backups). (2) *Greenfield stores only.* The Transit cipher **fails closed** (`CipherError`) on any pre-existing `mfenc:v1`/`v2`/`v4` value, and `rotate-key` refuses to run in this mode — so there is **no in-place migration** off an already-encrypted store today. Flipping this on a populated store makes its historical PHI unreadable. (3) *The AES-GCM bound is yours, and `serve` needs your recorded attestation of it* (BACKLOG #2337). The engine counts no encryptions on this cipher, so rotate the Transit data key (`MEFOR_STORE_TRANSIT_KEY`) before any one key version seals 2^32 values; plan to rotate by 2^31, sized from the peak encrypt rate (Vault's `auto_rotate_period`, or a manual schedule). Then run `messagefoundry store attest-transit-bound --reason ""` once, on the host, or `serve` **refuses to start** under `[security].enforcement = enforce`. What the record holds, what keeps or voids it, and what it does not check are in [SECURITY.md](SECURITY.md), *On vault_transit, a recorded attestation stands in for the AES-GCM count*. | | `vault_revocation_attested` | bool | `false` | attests that revocation of the **store Vault's** server certificate is covered outside the engine (vault BACKLOG #2983, owner ruling 2026-10-13). It covers both store hops to that Vault: `key_provider = "vault"` and `cipher_provider = "vault_transit"`. The engine verifies that certificate, and its handshake checks no CRL and no OCSP. So each client build **refuses** a Vault that is off the box unless this is `true`. On the box means a loopback host reached with no proxy, decided on the address the client will really dial. The refusal applies under `[security].enforcement = enforce`, and wherever a client is built without a known posture, which counts as enforcing. A caller that hands its posture down crosses with a WARNING on an `enforcement = warn` instance, and a command that holds none refuses; [`SECURITY-LOOSENING.md`](SECURITY-LOOSENING.md) names the callers. **Under `enforce` this flag is the only way across:** no CRL lever is built for these hops, and the process-wide `MEFOR_TLS_REVOCATION_ATTESTED` does not cross an enforcing hop. Setting it adds no check on the wire. It never lifts the cleartext or proxy-credential refusals. Through an `https://` proxy it also claims the proxy's certificate, whose TLS leg is judged under the same rule (vault BACKLOG #3561). A loosening, named as `store.vault_revocation_attested`: read [`SECURITY-LOOSENING.md`](SECURITY-LOOSENING.md) for what the attestation can truthfully rest on. Not a secret. Env: `MEFOR_STORE_VAULT_REVOCATION_ATTESTED` | | `vault_revocation_attested_reason` | str | — | **required** with `vault_revocation_attested = true`: what covers revocation of the store Vault's certificate, for example its short lifetime, and of an `https://` proxy's in front of it. The flag without it, a blank one, one holding a control character or a lone surrogate, or a reason without the flag is refused at load. It is printed in the loosening report and the serve-time warning, so put no secret in it. Env: `MEFOR_STORE_VAULT_REVOCATION_ATTESTED_REASON` | | `require_encryption` | bool | `false` | keeps the keyless refusal in force past the audited opt-out. It does not create that refusal, which is the default; [PHI.md](PHI.md#3-encryption-at-rest) §3 states the rule and the opt-out. It encrypts nothing itself, so a key is still needed. | diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 0ad1c862bd..177b06a1cf 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -3034,9 +3034,9 @@ follow-on and is **not** built. | `soap_action` | — | the `SOAPAction` (1.1 header; 1.2 `action` content-type param) | | `soap_version` | `1.1` | `1.1` (`text/xml`) or `1.2` (`application/soap+xml`) | | `headers` | `{}` | extra **static** headers (no secrets — an `env()` ref *inside* the table is refused at load; `env()` for the whole table is fine) | -| `bearer_token` | — | `Authorization: Bearer …` (a **secret** — via `env()`). A Basic pair set beside it wins | +| `bearer_token` | — | `Authorization: Bearer …` (a **secret** — via `env()`). Beside a Basic pair it is refused at construction, since the two share the header (BACKLOG #5526) | | `basic_user` / `basic_password` | — | HTTP Basic auth (secrets — via `env()`). Set both or neither: one alone is refused at construction (BACKLOG #5526). A configured `bearer_token` or Basic pair replaces a static `Authorization` header of any casing | -| OAuth2 client credentials | — | wrap the spec: `with_oauth2_client_credentials(Soap(...), token_url=..., client_id=..., client_secret=...)` (from `messagefoundry.transports.http_auth`; keep the secret in `env()`). A static `Authorization` header, a `bearer_token` and a Basic pair are then not sent, and the construction length check does not judge them. | +| OAuth2 client credentials | — | wrap the spec: `with_oauth2_client_credentials(Soap(...), token_url=..., client_id=..., client_secret=...)` (from `messagefoundry.transports.http_auth`; keep the secret in `env()`). A static `Authorization` header, a `bearer_token` or a Basic pair is then not sent, and the construction length check does not judge it; a `bearer_token` and a Basic pair together are still refused at construction (BACKLOG #5526). | | `timeout_seconds` | `30` | per-request timeout, in seconds above zero: zero or a negative is refused when the connection is built | | `verify_tls` | `true` | TLS cert verification — the same posture-keyed cell as [REST](#rest--rest): `false` is **refused at construction** off loopback, and the `MEFOR_ALLOW_INSECURE_TLS` escape is **clamped inert** while `[security].enforcement = enforce` (the shipped default) | | `tls_allow_expired` | `false` | **(#129, ADR 0094)** tolerate an **expired** server cert with the chain's signatures + hostname still verified (not the other chain certificates' validity periods; see the MLLP row). **No posture gate and no escape variable covers the setting itself**. It takes one lever away from the revocation gate: a `[tls].crl_file` cannot admit a hop that sets it, so off-box on an enforcing instance only `tls_revocation_attested` with its reason crosses (ADR 0173 §13). It **is reported**: a WARNING at each build, a `tls-allow-expired` line in `messagefoundry check` and a `security_loosenings()` entry, and so `GET /security/posture` (CORRECTED 2026-10-01: this row said `security_loosenings()` never reports it, stale since BACKLOG #333) — see the [MLLP row](#mllp--mllp) | @@ -3048,34 +3048,23 @@ follow-on and is **not** built. 500 **or** an HTTP 200 body). A **Sender/Client** fault → `NegativeAckError` → **dead-letter** (the request is rejected; a retry won't help). A **Receiver/Server** fault → `DeliveryError` → **retry**. The Sender/Receiver class is read first from the Fault's first child element: SOAP 1.2's `Code`, then the -`Value` that is that Code's own first child, or SOAP 1.1's `faultcode`. A comment, CDATA section or -processing instruction before either child is stepped over, with at least these exceptions, each of -which leaves that read with no code: such markup that has no terminator; a `soap:Server` reads `soap:Server` and retries. Where that read -yields no code, for -those shapes, for a first child that is neither element (a SOAP 1.1 `faultstring` before the -`faultcode`, a SOAP 1.2 `Reason` before the `Code`), or for a code element that holds no code, the -code falls back to the earlier search's rule, from the Fault start tag to the first `` -after it, or the reply's end: the first `Value` ahead of the Fault's first `faultcode`, else that -`faultcode`, and an empty one is not passed over for a later one. Like the earlier -search, the fallback steps over no markup: a `faultcode` or `Value` inside a comment counts, and a -`` inside one ends its range. For example, +`Value` that is that Code's own first child, or SOAP 1.1's `faultcode`. A terminated comment, CDATA +section or processing instruction before either child is stepped over. Where that read yields no code, +for at least a first child that is neither element (a SOAP 1.1 `faultstring` before the `faultcode`, a +SOAP 1.2 `Reason` before the `Code`), a code element that is empty, self-closing or holds only +whitespace, and markup the read does not step over, the code falls back to the search the engine ran +before BACKLOG #5912. That fallback steps over no markup: a `faultcode` or `Value` inside a comment +can decide the class, and a `` inside one ends its range, so `busysoap:Server` -reads no code and dead-letters, as the earlier search read it. A Fault start tag inside terminated markup is stepped over when -the Fault is chosen, and a `` or `` inside terminated markup does not end the -first-child read, except where the Fault was itself taken from inside markup; only where every Fault start tag after the first Body start tag, -or with none there every one, is inside such markup is the first of them taken as the Fault, so such -a reply never reads as delivered. A Fault where neither read finds a code reads as a permanent fault. +reads no code and dead-letters. The read, its fallback and the one shape read again are stated once, +in the `_fault_code` and `_child_code_text` docstrings in +[`transports/soap.py`](../messagefoundry/transports/soap.py). The +Fault is the first Fault start tag after the first Body start tag outside terminated markup, or with +no Fault after it the first in the reply, the Fault start tag also searched for outside such markup; only where every Fault start tag after that Body start tag (with none there, every +one) is inside such markup is the first of them taken as the Fault, so such a reply never reads as +delivered. A Fault where neither read finds a code reads as a permanent fault. The WS-Security check is separate: a WS-Security code anywhere from where the Fault search starts (after -the first Body start tag when a Fault follows it, else the whole reply), inside the Fault or not, still +the first Body start tag outside terminated markup when a Fault follows it, else the whole reply), inside the Fault or not, still dead-letters the reply. An unrecognized fault is treated as permanent (so a rejected request can't loop the lane). With no fault, the HTTP status decides (2xx delivered, 5xx retry, other 4xx / refused 3xx dead-letter); a connection/timeout @@ -3152,7 +3141,7 @@ wrapping an HL7 payload) — **not** the full envelope. The transport builds the element with a close tag (SOAP 1.1 `faultcode`, or SOAP 1.2 `Code` with its `Subcode`) that names a WS-Security code, the fault reads as `MessageExpired` only if that element names it. Otherwise it does if `MessageExpired` is anywhere the WS-Security code search looks: after the - first Body start tag when a Fault follows it, else the whole reply (BACKLOG #5798). This bullet is where the rule is stated; the `soap.py` + first Body start tag outside terminated markup when a Fault follows it, else the whole reply (BACKLOG #5798). This bullet is where the rule is stated; the `soap.py` module docstring points here. ```python @@ -3484,18 +3473,18 @@ source (`Http()`, File, a `Loopback` re-ingress) as a `RawMessage`. | Setting | Default | Meaning | |---------|---------|---------| -| `url` | — (required) | the FHIR service **base** URL (e.g. `https://host/fhir`); `http`/`https` only. Use `env()`. | +| `url` | — (required) | the FHIR service **base** URL (e.g. `https://host/fhir`); `http`/`https` only. Use `env()`. A url that is not ASCII, or holds whitespace or a `#`, is refused at construction (BACKLOG #5911) | | `fhir_version` | `R4B` | `R4B` (default) / `R5` / `STU3` — explicit (no plain-R4 on pydantic-v2 wheels) | | `format` | `json` | `json` only; FHIR-XML is deferred to a hardened-`lxml` path | | `interaction` | `create` | `create` (`POST {base}/{ResourceType}`) / `update` (`POST {base}` with a one-entry `transaction` `Bundle` whose entry is `PUT {ResourceType}/{id}`; see [the id stays out of the URL](#an-update-keeps-the-resource-id-out-of-the-url)) / `transaction` / `batch` (`POST {base}` with a `Bundle`) | | `conditional` | — | opt-in: `if-none-exist` (conditional create) / `conditional-update` (search-based PUT) / `if-match` (version-aware update, sent like `update` with the ETag in the entry, or in an `If-Match` header with `update_url_form="path"`) | -| `conditional_query` | — | FHIR search params for `if-none-exist` / `conditional-update` (e.g. `identifier=sys\|val`). A `#` is refused at construction under either (percent-encode it as `%23`). With either set, a credential-looking parameter or segment in it is refused at construction on an `https` hop with `verify_tls = false`, loopback included, and on plain `http` to a host off this machine. It is not refused on a verified `https` hop or on plain `http` to this machine, whatever `verify_tls` says, since plain `http` has no certificate to verify. There it is warned about once the connection constructs; a connection that another construction check refuses first logs no warning. The refusal and the warning name each credential-looking parameter of the `&`-split query, never its value. Where that split names none, a credential-looking segment can still be reported, unnamed, as for `identifier=sys\|1;token=...`: the message carries `conditional_query segment with a credential-looking name`. At least some shapes are not counted, such as a segment beside a named parameter, a bare name with no `=` (`api_key;identifier=1`), and a percent-encoded `;` (`%3B`). Nor is a `code` name, which is FHIR's search parameter (BACKLOG #5350, #5353) | +| `conditional_query` | — | FHIR search params for `if-none-exist` / `conditional-update` (e.g. `identifier=sys\|val`). A `#` is refused at construction under either (percent-encode it as `%23`). With either set, a credential-looking parameter or segment in it is refused at construction on an `https` hop with `verify_tls = false`, loopback included, and on plain `http` to a host off this machine. It is not refused on a verified `https` hop or on plain `http` to this machine, whatever `verify_tls` says, since plain `http` has no certificate to verify. There it is warned about once the connection constructs; a connection that another construction check refuses first logs no warning. The refusal and the warning name each credential-looking parameter of the `&`-split query, never its value. Where that split names none, a credential-looking segment can still be reported, unnamed, as for `identifier=sys\|1;token=...`: the message carries `conditional_query segment with a credential-looking name`. At least some shapes are not counted, such as a segment beside a named parameter, a bare name with no `=` (`api_key;identifier=1`), and a percent-encoded `;` (`%3B`). Nor is a `code` name, which is FHIR's search parameter (BACKLOG #5350, #5353). At least these are refused at construction too, rather than at each send: an all-whitespace value; under `conditional-update`, a value that is not ASCII or holds a space, and one that makes a request URL over the length limit; under `if-none-exist`, a value Latin-1 cannot encode (BACKLOG #5911) | | `update_url_form` | `transaction` | how an `update` or `if-match` is sent. `transaction` keeps the id out of the URL. `path` is the plain `PUT {base}/{ResourceType}/{id}` with the ETag in an `If-Match` header, for a server with no `transaction` interaction. `path` is a **listed loosening**; see [vendor compatibility](#vendor-compatibility-and-the-path-form-opt-in) An `env()` value is read by `check` and `GET /security/posture` as [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md#update_url_form--path-on-a-fhir-connection--the-resource-id-in-the-request-url) says | | `allowed_entry_methods` | — (**required** on `transaction`/`batch`) | (vault BACKLOG #2804) the verbs a Bundle entry may carry, from `GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `PATCH`, spelled in upper case. There is no default: a `transaction` or `batch` connection without it does not load, or, where `interaction` is an `env()`, does not build. Refused on any other interaction. Both lists take an `env()` for the whole list: its default is checked at load, and the value it resolves to when the connection is built. A bad item is named by position, never quoted. See [A Bundle connection screens every entry](#a-bundle-connection-screens-every-entry) | | `allowed_entry_types` | — (any type) | (vault BACKLOG #2804) `transaction`/`batch` only: the resource types an entry's `request.url` may name, such as `["Patient", "Encounter"]`. Unset means any type. Refused on any other interaction | -| `headers` | `{}` | extra **static** headers (no secrets — an `env()` ref *inside* the table is refused at load; `env()` for the whole table is fine) | +| `headers` | `{}` | extra **static** headers (no secrets — an `env()` ref *inside* the table is refused at load; `env()` for the whole table is fine). Refused at construction, among others: a value that is not a table, a header name that is not an RFC 9110 token, and a value holding a control character other than HTAB (BACKLOG #5911, #8299) | | `bearer_token` | — | `Authorization: Bearer …` (SMART/OAuth — a **secret**, via `env()`) | -| `basic_user` / `basic_password` | — | HTTP Basic auth (secrets — via `env()`) | +| `basic_user` / `basic_password` | — | HTTP Basic auth (secrets — via `env()`). Set both or neither, with no `:` in `basic_user`, and not beside `bearer_token`; a FHIR destination or `FhirLookup` that breaks one of these is refused at construction (BACKLOG #8299) | | `timeout_seconds` | `30` | per-request timeout, in seconds above zero: zero or a negative is refused when the connection is built | | `verify_tls` | `true` | TLS cert verification — the same posture-keyed cell as [REST](#rest--rest): `false` is **refused at construction** off loopback, and the `MEFOR_ALLOW_INSECURE_TLS` escape is **clamped inert** while `[security].enforcement = enforce` (the shipped default) | | `tls_allow_expired` | `false` | **(#129, ADR 0094)** tolerate an **expired** server cert with the chain's signatures + hostname still verified (not the other chain certificates' validity periods; see the MLLP row). **No posture gate and no escape variable covers the setting itself**. It takes one lever away from the revocation gate: a `[tls].crl_file` cannot admit a hop that sets it, so off-box on an enforcing instance only `tls_revocation_attested` with its reason crosses (ADR 0173 §13). It **is reported**: a WARNING at each build, a `tls-allow-expired` line in `messagefoundry check` and a `security_loosenings()` entry, and so `GET /security/posture` (CORRECTED 2026-10-01: this row said `security_loosenings()` never reports it, stale since BACKLOG #333) — see the [MLLP row](#mllp--mllp) | @@ -5277,7 +5266,7 @@ reading this page already applies to a file the scan never opened. | Syslog forwarder (`[logging].forward_host`) | 5 s pinned on the socket for both `tcp` and `tls` (the TLS handshake runs under it); UDP is connectionless and carries none | a single long-lived socket owned by the logging handler | on timeout the handler drops **that record** and continues | **single-shot** per record — no retry | | SNTP clock-sync probe (`[logging].ntp_peer`) | 2 s pinned with `sock.settimeout`, so a silent peer cannot block `serve()` | the datagram socket is closed after the single probe | skew warns loudly, or refuses to start under `time_sync_fail_closed` | **single-shot** — one probe per start | | Forward / egress web proxy (`[egress].proxy_url`) | **inherits the destination connector's `timeout_seconds`** — the proxy hop has no separate timeout | released with the destination request; the per-connection `ProxyHandler` never mutates the shared opener | a proxy error surfaces as the destination request's failure | the destination's `RetryPolicy` | -| Loopback ECH sidecar (`ech_sidecar`) | **inherits the connection's `timeout_seconds`** | released with the destination request | fails closed at config load, and on a connector built directly, on at least a missing or non-loopback sidecar, or one with a credential, a query or a fragment in its URL; at config load also on one not in `[egress].allowed_ech_sidecar` (BACKLOG #5528) | the destination's `RetryPolicy` | +| Loopback ECH sidecar (`ech_sidecar`) | **inherits the connection's `timeout_seconds`** | released with the destination request | fails closed at config load, and on a connector built directly, on at least a missing or non-loopback sidecar, or one with a credential, a query or a fragment in its URL; on a REST connection, at build, beside HTTP Digest, whose handler cannot answer a challenge through the sidecar (BACKLOG #5529); at config load also on one not in `[egress].allowed_ech_sidecar` (BACKLOG #5528) | the destination's `RetryPolicy` | ## Competitive parity — full connector catalog diff --git a/docs/DEPLOY-SERVER-DB.md b/docs/DEPLOY-SERVER-DB.md index aa08e43ab9..62cd157b37 100644 --- a/docs/DEPLOY-SERVER-DB.md +++ b/docs/DEPLOY-SERVER-DB.md @@ -178,11 +178,16 @@ messagefoundry check-privileges --service-config \messagefoundry.t `UPDATE`, `DELETE`, `ALTER`, `CONTROL` or `TAKE OWNERSHIP` on `audit_log`, and an `UPDATE` granted on one column, which outranks the table-level `DENY`. So is `VIEW DEFINITION` reaching its default schema or `dbo` by any route, at least a grant on the - schema, the database or the server, schema ownership, or a role or group membership. Remove it - and run the check again. -- It **exits 4** when the probe could not read the login at all, for example on a failed connection - or a permission read that came back NULL, or as a value that is not 0 or 1. That is not a clean - result. + schema, the database or the server, schema ownership, or a role or group membership. A named + role or `CONTROL` grant hides the lines for rights it carries, which the gMSA must never hold + either: at least `db_owner`, `sysadmin`, database `CONTROL` or `CONTROL SERVER` hides the + schema-DDL, `audit_log` and `VIEW DEFINITION` lines, `db_securityadmin` the `VIEW DEFINITION` + line, and `db_ddladmin` the schema-DDL lines and `ALTER` on `audit_log`. The output can also + list grants it could not read. Remove each grant it names and run the check again; once nothing + over-granted is left, a grant it still could not read makes it exit 4. +- It **exits 4** when the probe could not read the login, for example on a failed connection, or + when a permission read came back NULL, or as a value that is not 0 or 1, and nothing it did read + is over-granted. That is not a clean result. A read over-grant beside such a read exits 3. - It exits 1 when the service settings do not load. It also probes each Vault token the engine uses and the AD bind account, when they are diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index 3a39767cc8..13fcc1b84e 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -2175,7 +2175,12 @@ count is above `0` (vault BACKLOG #2613). - **When acceptable:** during bring-up, while a DBA reduces the grant. Not as a steady state. - **It is never silent:** a WARN at every start naming each excess grant; a `store_privilege_preflight` audit row; a `store_principal_over_granted` entry here and in `GET /security/posture`, whose - `store_privilege` field carries the full observation. + `store_privilege` field carries the observation's status, excess list and detail. When the probe + also named grants it could not read, the entry lists them and says the excess list may be + incomplete (BACKLOG #6015). An entry without that clause is not proof the list is complete: at + least a failed SQL Server user-defined role enumeration is noted in the detail, and the audit + row's, rather than in the entry, and a SQL Server read with a fixed role unread skips that + enumeration without noting it. - **How it refuses:** by default under `enforce`. `[store].require_least_privilege = true` ([`CONFIGURATION.md`](CONFIGURATION.md)) makes the refusal outrank the opt-out and extends it to an unobservable probe. The refuse/warn split is `[security].enforcement`. diff --git a/docs/adr/0015-ws-soap-outbound-mtls-wssecurity.md b/docs/adr/0015-ws-soap-outbound-mtls-wssecurity.md index 76b9a0fefc..57b5d4bfb7 100644 --- a/docs/adr/0015-ws-soap-outbound-mtls-wssecurity.md +++ b/docs/adr/0015-ws-soap-outbound-mtls-wssecurity.md @@ -157,11 +157,16 @@ in the reply, else the first Value, the Header included, and an empty ``, so `` does not match, and `_CODE_END_RE` is its close tag. Each of the three start-tag patterns is tried at most once, anchored, by the first read: `faultcode` and `Code` at the Fault's first child element, `Value` at the Code's first child. Where that read yields no code, -the fallback searches forward once each for the first `faultcode` and a `Value` ahead of it, the -search the code ran before #5912, from the Fault start tag `_find_fault` chose to the first plain -`_FAULT_END_RE` match, stepping over no markup; that Fault can differ from the one the earlier code -chose. Only a `faultcode` or `Value` match reaches -`_code_text`; the `_fault_code` docstring says how. The Fault start-tag search, where some Fault start tag on its side lies outside markup, and the Fault and Code close-tag searches that bound the first read, step over a terminated comment, CDATA section or processing instruction whole, with `str.find`, as the first-child search does; `_search_outside_markup` says how. The fallback's own Fault close-tag search does not. This decision is unchanged.)* There is no `xml.etree` / `ElementTree` / `lxml` / `defusedxml` import anywhere under +the code falls back to the search the code ran before #5912; the `_fault_code` docstring states that +fallback and its range, once (BACKLOG #5912 closing step 17). Only a `faultcode` or `Value` match +reaches `_code_text`. The Body start-tag search, the Fault start-tag search, and the Fault and Code +close-tag searches that bound the first read step over a terminated comment, CDATA section or +processing instruction whole, as the first-child search does; `_search_outside_markup` says how. +Two exceptions: where every Fault start tag after the Body start tag, or with none there every +Fault start tag in the reply, lies inside such markup, the first of them is taken; and where the +Fault start tag was itself taken from inside markup, a close tag later in that same markup ends +the read. The fallback's own Fault close-tag search steps over no markup. This decision is +unchanged.)* There is no `xml.etree` / `ElementTree` / `lxml` / `defusedxml` import anywhere under `messagefoundry/`. *(Corrected 2026-11-04: that sentence, the "regex-only" premise and the heading's "no XML parser" are no longer true of the codebase. The engine imports XML parsers, and `tests/test_security_static.py` keeps the allowlist of where. `transports/soap.py` is on it: it imports diff --git a/docs/adr/0139-ech-egress-sidecar-sni-hiding-for-asvs-12-1-5-demand-gated.md b/docs/adr/0139-ech-egress-sidecar-sni-hiding-for-asvs-12-1-5-demand-gated.md index f884325d9a..e27ed171f8 100644 --- a/docs/adr/0139-ech-egress-sidecar-sni-hiding-for-asvs-12-1-5-demand-gated.md +++ b/docs/adr/0139-ech-egress-sidecar-sni-hiding-for-asvs-12-1-5-demand-gated.md @@ -17,7 +17,7 @@ (mutually exclusive). Per-connection `ech_egress` / `ech_sidecar` settings. fhir/soap/dicomweb switched to the resolver (byte-identical when `ech_egress` is unset; smart/http_auth inherit via the threaded proxy). - **Fail-closed, at least these:** sidecar down → the hop errors (no direct, SNI-leaking fallback); non-loopback / missing - sidecar refused, and, added 2026-11-10 (BACKLOG #5528), a sidecar URL that carries a credential or that urllib would dial differently from how it reads (*Amendment 2026-11-10* below names those refusals); and, added 2026-11-09 (vault BACKLOG #2977), a `verify_tls = false` beside it. Added 2026-11-10 (BACKLOG #5528): a sidecar whose `host:port` is not in `[egress].allowed_ech_sidecar` is refused at config load, by the egress check (*Amendment 2026-11-10* below). Operator recipe: [`samples/ech-sidecar/`](../../samples/ech-sidecar/README.md). + sidecar refused, and, added 2026-11-10 (BACKLOG #5528), a sidecar URL that carries a credential or that urllib would dial differently from how it reads (*Amendment 2026-11-10* below names those refusals); and, added 2026-11-09 (vault BACKLOG #2977), a `verify_tls = false` beside it; and, on a REST connection, HTTP Digest beside it (BACKLOG #5529 limb 3; recorded here 2026-11-23, BACKLOG #5526 item 12), because the Digest handler's password is keyed on the destination URL while the request goes to the sidecar, so no challenge would be answered. Added 2026-11-10 (BACKLOG #5528): a sidecar whose `host:port` is not in `[egress].allowed_ech_sidecar` is refused at config load, by the egress check (*Amendment 2026-11-10* below). Operator recipe: [`samples/ech-sidecar/`](../../samples/ech-sidecar/README.md). - **Verified:** ruff + `mypy --strict` clean; 13 tests incl. a **stub-proxy behavioral test** proving egress routes THROUGH the sidecar and fails closed when it is down; 309 existing connector tests still pass. diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index a32b989ade..cbbc6c5578 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -291,6 +291,11 @@ class StorePrivilegePosture: excess: tuple[str, ...] = () #: Why the probe could not observe (``UNOBSERVABLE``), or what it observed against (otherwise). detail: str = "" + #: Grants the probe named as not read (BACKLOG #6015). Beside an ``OBSERVED`` excess the + #: over-grant entry names them, so it does not read as a complete observation. Empty does not + #: mean every grant was read: at least a failed SQL Server user-defined role enumeration is + #: noted in ``detail`` and not here. + unread: tuple[str, ...] = () class SchemaManagement(str, Enum): # noqa: UP042 @@ -11627,13 +11632,19 @@ def security_loosenings( ) elif store_privilege.excess: named = ", ".join(store_privilege.excess) + not_read = ( + "; these grants were not read, so the list may be incomplete: " + f"{', '.join(store_privilege.unread)}" + if store_privilege.unread + else "" + ) out.append( ( "store_principal_over_granted", f"the store principal holds {len(store_privilege.excess)} privilege(s) BEYOND the " f"least-privilege grant docs/DEPLOY-SERVER-DB.md prescribes ({named}) — the " "engine's own database credential can reach data and administrative operations " - "its runbook says it must not", + f"its runbook says it must not{not_read}", ) ) # --- the AUDIT CHAIN's observed keying (BACKLOG #1905). An observation, like the entry above: no diff --git a/messagefoundry/config/static_credentials.py b/messagefoundry/config/static_credentials.py index 5ab5fc0030..fb6a08e0ee 100644 --- a/messagefoundry/config/static_credentials.py +++ b/messagefoundry/config/static_credentials.py @@ -47,7 +47,8 @@ **Classification reads settings keys, not the built connector**, so each rule below mirrors what the connector does with those keys: a client certificate counts only with ``tls`` on, HTTP Basic only when -both halves are set, a WS-Security UsernameToken only with ``ws_security`` on, and a static +both halves are set, a WS-Security UsernameToken only with ``ws_security`` on and both +``ws_username`` and ``ws_password`` set (BACKLOG #5526 item 11), and a static ``Authorization`` credential not at all when SMART or OAuth2 replaces that header with a minted token. An HTTP-family hop's ``headers`` table and ``url`` query are read too (BACKLOG #5510), by the redaction screen's header test and the query-credential reader; ``_http_literal_static`` says how. @@ -79,12 +80,13 @@ Not every function here is pure. At least these do more than read their arguments: :func:`apply_static_credential_gate` and the guard :func:`make_static_credential_guard` returns, which log, the guard also reading the ``env()`` values the engine sets around it; ``_digest``, -which logs at debug the ``http_auth`` refusal it absorbs (BACKLOG #5529); ``_is_https``, which logs -at debug a proxy target that does not parse; and ``_http_literal_static`` (BACKLOG #5510) and -``_dicomweb_build_refused`` (vault BACKLOG #5359), whose ``env()`` resolution runs an operator -``cast`` as the build does. A caller inherits its callee's effect: at least -:func:`static_credential_hops` and :func:`run_static_credential_gate` can run an operator ``cast`` -and log, and :func:`http_hop_credentials` logs through ``_digest`` and resolves no ``env()``. +which logs at debug the ``http_auth`` refusal it absorbs (BACKLOG #5529) and, like +``_http_literal_static`` (BACKLOG #5510) and ``_dicomweb_build_refused`` (vault BACKLOG #5359), +resolves ``env()`` with an operator ``cast`` as the build does (BACKLOG #5526 item 9); and +``_is_https``, which logs at debug a proxy target that does not parse. A caller inherits its +callee's effect: at least :func:`static_credential_hops` and :func:`run_static_credential_gate` +can run an operator ``cast`` and log, and :func:`http_hop_credentials` logs through ``_digest`` +and, through it, resolves an ``env()`` ``http_auth`` to its ``default=``, which is never cast. **A detail cannot carry a secret, by construction.** Every detail is fixed text chosen from a closed set, plus at most one peer label. The peer label (:func:`~messagefoundry.config.wiring._peer_label`) is built from parsed parts, so it holds @@ -182,35 +184,73 @@ def _oauth2(settings: Mapping[str, Any]) -> bool: return oauth2_auth_configured(settings) -def _digest(settings: Mapping[str, Any]) -> bool: +def _digest( + settings: Mapping[str, Any], *, token: bool = False, env_values: Mapping[str, Any] | None = None +) -> bool: + """Whether ``http_auth`` selects Digest, read as the REST, SOAP and FHIR destinations read it. + DICOMweb and ``FhirLookup`` build no Digest handler, so on them a ``True`` here names a + credential the hop does not send; the census lists it all the same. + + BACKLOG #5526 item 9: an ``env()`` ``http_auth`` is read as the build resolves it, against + ``env_values``, else its literal ``default=`` (``config.wiring._resolved_setting``), as + :func:`_http_literal_static` reads ``headers``. One this reading cannot resolve may resolve to + ``digest``, so it reads as Digest, except beside a minted bearer (``token``) whose SMART and + OAuth2 flags, and SMART token URL, are not themselves ``env()`` references: the build refuses + Digest beside a bearer provider, so none crosses there. Where one of them is an ``env()`` + reference, the provider may resolve off, so the mode still reads as Digest. An ``env()`` + OAuth2 token URL is not counted. Beside a written ``oauth2_enabled``, as + ``with_oauth2_client_credentials`` writes it, one that resolves blank refuses the build + (``http_auth.refuse_oauth2_settings``). With no ``oauth2_enabled`` key, one that resolves to + nothing leaves the provider off and Digest can cross, and this reading does not list it: a + known gap (BACKLOG #5526 item 9, review round-117c3b9418).""" from messagefoundry.transports.http_auth import HttpAuthError, http_digest_selected + mode = _resolved_setting(settings, "http_auth", None, env_values or {}) + if mode is _UNRESOLVED: + # BACKLOG #5526 item 9: an env() SMART token URL may resolve empty, which leaves that + # provider off, so it counts as an env() flag does. + keys = ("oauth2_enabled", "smart_enabled", "smart_token_url") + return not token or any(isinstance(settings.get(key), EnvRef) for key in keys) + if mode is not settings.get("http_auth"): + settings = {**settings, "http_auth": mode} try: return http_digest_selected(settings) except HttpAuthError as exc: - # An unrecognised mode refuses the connector (#5529), so no Digest credential crosses. The - # message names the connection and never the value; the connector's build reports it loudly. + # An unrecognised mode refuses the REST, SOAP and FHIR destinations (#5529), so no Digest + # credential crosses there. The message names the connection and never the value; the + # connector's build reports it loudly. logging.getLogger(__name__).debug("static-credential census: %s", exc) return False def _static_authorization(settings: Mapping[str, Any]) -> list[str]: - """The static credentials the connector writes into its own ``Authorization`` header.""" - out: list[str] = [] - if settings.get("bearer_token"): - out.append("static bearer token") + """The static credential the connector writes into its own ``Authorization`` header. With both + a ``bearer_token`` and a Basic pair set, only Basic is listed (BACKLOG #5526 item 2). REST, + SOAP, DICOMweb, the FHIR destination and ``FhirLookup`` (BACKLOG #8299 item 8) refuse to build + on both when the pair is set, so this listing then describes a hop that does not build: this + reader does not take the connector type. It also reads the unresolved settings, so an ``env()`` + Basic half counts as set here even where it resolves empty; that hop builds and sends the + bearer, and this listing still names Basic.""" if settings.get("basic_user") and settings.get("basic_password"): - out.append("HTTP Basic") - return out + return ["HTTP Basic"] + if settings.get("bearer_token"): + return ["static bearer token"] + return [] -def _http_static(ctype: ConnectorType, settings: Mapping[str, Any], token: bool) -> list[str]: +def _http_static( + ctype: ConnectorType, + settings: Mapping[str, Any], + token: bool, + *, + env_values: Mapping[str, Any] | None = None, +) -> list[str]: """The static credentials an HTTP-family hop actually puts on the wire. A minted SMART or OAuth2 bearer replaces the ``Authorization`` header, so a static bearer or Basic credential configured beside it never leaves the engine. Basic needs both halves: SOAP - and DICOMweb (vault BACKLOG #5359) refuse to build on one, and REST and FHIR send nothing on - one. A WS-Security + and DICOMweb (vault BACKLOG #5359), REST (BACKLOG #5354) and FHIR (BACKLOG #8299) refuse to + build on one. A WS-Security UsernameToken rides in the SOAP body, so token auth does not displace it, but it is stamped only with ``ws_security`` on. Its user and password are ``ws_username`` and ``ws_password`` alone; they stopped falling back to the Basic pair in BACKLOG #5526. ``Soap()`` hoists ``body_secrets`` into @@ -218,7 +258,7 @@ def _http_static(ctype: ConnectorType, settings: Mapping[str, Any], token: bool) out = [] if token else _static_authorization(settings) # The connector answers a Digest challenge only in http_auth='digest' mode, and refuses to build # in that mode with either half missing, so the mode is the predicate, not the credential keys. - if _digest(settings): + if _digest(settings, token=token, env_values=env_values): out.append("HTTP Digest") if ctype is ConnectorType.SOAP: # With ws_security on the connector refuses to build on one half of the pair (#5526), so @@ -340,7 +380,7 @@ def _http_hop( presents (:func:`_http_literal_static`), so it lists the hop even beside a compliant kind.""" compliant_kind = ctype is not ConnectorType.DICOMWEB token = _http_token(ctype, settings, lookup=lookup) - static = _http_static(ctype, settings, token) + static = _http_static(ctype, settings, token, env_values=env_values) displaced = token or bool(_static_authorization(settings)) static += _http_literal_static(ctype, settings, displaced=displaced, env_values=env_values) if static: diff --git a/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index 2bf9daed9a..87782fc4d4 100644 --- a/messagefoundry/config/tls_policy.py +++ b/messagefoundry/config/tls_policy.py @@ -3748,9 +3748,12 @@ def requests_verify_from_anchor(anchor: TrustAnchor, *, cell: str) -> str | None so instead. Worth stating plainly, because the direction is counter-intuitive: this hop is not one of the - broadly-trusting ones. ``requests`` defaults to the PUBLIC certifi bundle, not the OS store, so an - internal-CA Vault fails closed today rather than being widely trusted. What was missing here is - the ability to reach such a Vault at all. + broadly-trusting ones by default. With no anchor passed, hvac and ``requests`` choose the CA + from the process environment, as ``store/keyprovider_vault.py``'s ``_ENV_CA_FILE`` comment + records, and fall back to ``requests``' PUBLIC certifi bundle, not the OS store, only when it + names none. So an internal-CA Vault fails closed unless the environment names a CA source + holding its CA, and then that source is what the hop trusts. What was missing here is the + ability to name this hop's CA in the engine's own setting. A ``crl_file`` on the anchor is **refused** for the same reason ``augment`` is (BACKLOG #299): ``verify=`` names one bundle and cannot carry a revocation flag, so honouring the CA while dropping diff --git a/messagefoundry/sqlserver_roles.py b/messagefoundry/sqlserver_roles.py index b71173066b..928999ffe0 100644 --- a/messagefoundry/sqlserver_roles.py +++ b/messagefoundry/sqlserver_roles.py @@ -18,11 +18,15 @@ The server set is the eight classic roles. The ``##MS_...##`` fixed server roles SQL Server 2022 added are not in it, so neither probe reads them. + +Both probes read each answer with :func:`probed_grant`, which lives here for the same reason. It +is not SQL Server specific: the PostgreSQL store probe reads its audit-table answers with it too, +and reads its other answers another way. """ from __future__ import annotations -__all__ = ["SQLSERVER_FIXED_DATABASE_ROLES", "SQLSERVER_FIXED_SERVER_ROLES"] +__all__ = ["SQLSERVER_FIXED_DATABASE_ROLES", "SQLSERVER_FIXED_SERVER_ROLES", "probed_grant"] #: The closed set of SQL Server FIXED SERVER roles. SQLSERVER_FIXED_SERVER_ROLES: tuple[str, ...] = ( @@ -48,3 +52,24 @@ "db_denydatareader", "db_denydatawriter", ) + + +def probed_grant(value: object) -> bool | None: + """Read one privilege-probe answer THREE ways: ``True`` held, ``False`` not held, ``None`` **not + read**. Only an int or a bool that is 0 or 1 reads; anything else, a NULL, the text ``"1"``, a + ``2``, ``1.0`` or bytes, is not read (BACKLOG #6015). + + ``IS_SRVROLEMEMBER``, ``IS_ROLEMEMBER`` and ``HAS_PERMS_BY_NAME`` each return NULL, not 0, when + the name they are asked about does not resolve for this caller: an unknown or renamed role, a + principal the caller cannot see, a permission name this server version does not carry + (BACKLOG #1234). Folding that NULL, or an answer of a type a driver changed to, into "not held" + would read as clean, so a probe that read nothing could render as a clean bill of health. + ``True`` and ``False`` from a driver that returns booleans read as ``1`` and ``0``. + + Callers include the SQL Server store preflight (``store/privilege.py`` re-exports it), the + PostgreSQL store preflight for its audit-table columns only, and the partner-login probe + (``transports/database.py`` ``classify_login_roles``), so a change here changes how each of + them reads.""" + if isinstance(value, int) and value in (0, 1): + return bool(value) + return None diff --git a/messagefoundry/store/crypto_transit.py b/messagefoundry/store/crypto_transit.py index 33cac4443a..352a8eec2e 100644 --- a/messagefoundry/store/crypto_transit.py +++ b/messagefoundry/store/crypto_transit.py @@ -29,8 +29,9 @@ ASVS 16.4.2 residual for this mode). The MAC key defaults to the data key and is overridable to a dedicated Transit key via ``MEFOR_STORE_TRANSIT_AUDIT_KEY`` for domain separation. -**Fail-closed (ADR 0138).** Missing config, an unreachable/unknown Transit key, or a key whose TYPE -cannot run the operation asked of it (BACKLOG #1166) raises +**Fail-closed (ADR 0138).** At least missing config, a key name that is not a Transit key name +(BACKLOG #6010), an unreachable/unknown Transit key, or a key whose TYPE cannot run the operation +asked of it (BACKLOG #1166) raises :class:`~messagefoundry.store.keyprovider.KeyProviderError` at construction (``open_store`` propagates it → ``serve`` refuses to start, never an in-process fallback). A per-operation Transit failure raises :class:`CipherError` — the store's existing at-rest error discipline. On ``encrypt`` and ``decrypt``, a failure that gave no verdict @@ -50,7 +51,6 @@ import base64 import contextlib import logging -import os import threading import time import weakref @@ -91,14 +91,17 @@ TRANSIT_KEY_TYPES_DATA, TRANSIT_MOUNT, _build_client, + _recorded_refusal, _vault_ca_kwargs, checked_transit_key_name, + is_transit_key_name, is_vault_bad_request, is_vault_forbidden, is_vault_timeout_reply, is_vault_unavailable, require_transit_key_type, store_vault_hop, + transit_key_name_setting, vault_failure_text, ) from messagefoundry.store.row_seal import transit_mac_version @@ -603,6 +606,12 @@ def __init__( allow_unmarked: bool = False, client_factory: Callable[[], Any] | None = None, ) -> None: + # Both names go into request paths, so they are checked here as well as where the + # environment is read (BACKLOG #6010 item 9), before the cipher holds any client. Each + # refusal names the variable the name comes from there. + checked_transit_key_name(key_name, selector=_ENV_TRANSIT_KEY) + if audit_key: + checked_transit_key_name(audit_key, selector=_ENV_AUDIT_KEY) # BACKLOG #5963: requests does not document its Session as thread-safe, and this cipher is # called on the event loop and in worker threads. With a ``client_factory`` each thread # keeps its own client, ``client`` serving the thread that builds the cipher, and this @@ -1376,7 +1385,14 @@ def verify_seal_hmac(self, key_name: str, digest: bytes, mac: str) -> object: checks its shape. An HTTP 400 or 403 raises :class:`~messagefoundry.store.crypto.TransitSealRefused` with that status, raised outside the handler so no chain carries Vault's reply; anything else raises :class:`CipherError`. - Blocking.""" + Blocking. + + ``key_name`` goes into the request path, so a name that is not a Transit key name raises + :class:`CipherError` before any request (BACKLOG #6010 item 9).""" + if not is_transit_key_name(key_name): + raise CipherError( + "Transit row seal verify was given a key name that is not a Transit key name" + ) refused = 0 try: return self._transit_verify(key_name, digest, mac) @@ -1414,24 +1430,48 @@ def verify(self, data: bytes, stored: str, /) -> bool: return self._cipher.verify_audit_hmac(data, stored) +def _refusal_text(exc: KeyProviderError, selector: str) -> str: + """The text the engine recorded for ``exc`` when it built it, else a fixed text naming + ``selector``. The instance's own text is never read, so a refusal raised by code this module + did not vet cannot pass its text through the store's fixed-text seams.""" + from messagefoundry.store.base import _recorded_text + + return _recorded_text(exc) or f"{selector} could not be read as a Vault transit key name." + + def _key_names() -> tuple[str, str]: """The Transit data key and audit key from the environment, read in one place for the cipher and for :func:`transit_cipher_required_capabilities`. Raises :class:`KeyProviderError` when the data-key name is not set, and when either name is not a Transit key name (BACKLOG #6010): both - go into Transit request paths, so each is checked here, before any client is built.""" - key_name = os.environ.get(_ENV_TRANSIT_KEY) - if not key_name: - raise KeyProviderError( - f"[store].cipher_provider={PROVIDER_NAME!r} is selected but {_ENV_TRANSIT_KEY} is not set — " - f"supply the Transit data-key name via the environment." - ) - key_name = checked_transit_key_name(key_name, selector=_ENV_TRANSIT_KEY) + go into Transit request paths, so each is checked here, before any client is built. Both are + read before either refuses, so one refusal names each variable to fix (BACKLOG #6010 item 7), + as :func:`~messagefoundry.store.keyprovider_vault.store_vault_hop` does for the address and + token.""" + refusals: list[str] = [] + key_name: str | None = None + audit_key: str | None = None + try: + key_name = transit_key_name_setting(_ENV_TRANSIT_KEY) + except KeyProviderError as exc: + refusals.append(_refusal_text(exc, _ENV_TRANSIT_KEY)) + else: + if key_name is None: + refusals.append( + f"[store].cipher_provider={PROVIDER_NAME!r} is selected but {_ENV_TRANSIT_KEY} is " + f"not set — supply the Transit data-key name via the environment." + ) # Optional dedicated audit-HMAC key; unset ⇒ reuse the data key. Either way the type is checked # at build — see the _ENV_AUDIT_KEY comment above for which types each use admits and why. - audit_key = os.environ.get(_ENV_AUDIT_KEY) - return key_name, ( - checked_transit_key_name(audit_key, selector=_ENV_AUDIT_KEY) if audit_key else key_name - ) + try: + audit_key = transit_key_name_setting(_ENV_AUDIT_KEY) + except KeyProviderError as exc: + refusals.append(_refusal_text(exc, _ENV_AUDIT_KEY)) + # Raised outside the handlers, so nothing a read held rides along on the chain (BACKLOG #2307). + # Each text is one the engine built from a variable name alone, read from its record, so the + # joined text is recorded and the store's fixed-text seams keep it (BACKLOG #6010 item 3). + if refusals or key_name is None: + raise _recorded_refusal(" ".join(refusals)) + return key_name, audit_key or key_name def build_transit_cipher( @@ -1443,9 +1483,10 @@ def build_transit_cipher( (vault BACKLOG #2983). ``None`` counts as enforcing. ``settings`` is accepted for signature parity with ``make_cipher``/``build_store_cipher`` (the Vault - address/token/key are env-only secrets/provisioning outputs, like the KEK-unwrap provider). A missing - key name, a missing extra, or an unreachable/unknown Transit key raises :class:`KeyProviderError` so - ``open_store`` refuses to start rather than degrading to plaintext.""" + address/token/key are env-only secrets/provisioning outputs, like the KEK-unwrap provider). At + least a missing or malformed key name (:func:`_key_names`), a missing extra, or an + unreachable/unknown Transit key raises :class:`KeyProviderError` so ``open_store`` refuses to + start rather than degrading to plaintext.""" key_name, audit_key = _key_names() # Read once, and every client this cipher builds takes this token: the startup client below, # each thread's own on its first call there, and each rebuild after close_connections (BACKLOG @@ -1541,7 +1582,8 @@ def transit_cipher_required_capabilities() -> dict[str, frozenset[str]]: ``transit/hmac/``, which is the data key when no audit key is set, and the audit walk's check (:meth:`TransitCipher.verify_audit_hmac`, BACKLOG #2720) and the row seal check (:meth:`TransitCipher.verify_seal_hmac`, ADR 0217) update ``transit/verify/``. Raises - :class:`KeyProviderError` when the data-key name is not set, as the cipher itself does.""" + :class:`KeyProviderError` when the data-key name is not set or either name is malformed, as + the cipher itself does (:func:`_key_names`).""" key_name, audit_key = _key_names() read, update = frozenset({"read"}), frozenset({"update"}) return { diff --git a/messagefoundry/store/keyprovider_vault.py b/messagefoundry/store/keyprovider_vault.py index af629412fa..807e35fbcf 100644 --- a/messagefoundry/store/keyprovider_vault.py +++ b/messagefoundry/store/keyprovider_vault.py @@ -523,8 +523,13 @@ def require_transit_key_type( fix is a new key under ``selector``. ``after_switch`` is appended when that alone is not enough for this use, such as a KEK whose wrapped DEK has to move with it. + ``key_name`` goes into the request path, so it is checked here with + :func:`checked_transit_key_name` before the read, whatever the caller already checked (BACKLOG + #6010 item 9). + Raises :class:`KeyProviderError` so ``open_store`` propagates it and ``serve`` refuses to start (ADR 0019 §4 / ADR 0138 fail-closed), never a degrade to a weaker path.""" + checked_transit_key_name(key_name, selector=selector) response: Any = client.secrets.transit.read_key(name=key_name) data = response.get("data") if isinstance(response, Mapping) else None raw = data.get("type") if isinstance(data, Mapping) else None @@ -567,8 +572,9 @@ def __init__(self, settings: StoreSettings, *, posture: HopPosture | None = None # The instance posture the caller holds, for the revocation guard on this hop (vault # BACKLOG #2983). `None` counts as enforcing. self._posture = posture - # BACKLOG #6010: a malformed KEK name refuses here, at construction. `active_key` reads the - # name again through the same check, as the capability probe does. + # BACKLOG #6010: a malformed KEK name refuses here, at construction. The shipped dispatch + # calls `active_key` straight after, which reads and checks the name again, so this adds + # nothing there (item 4); it is kept so a provider built and not yet asked refuses too. _kek_name() def active_key(self) -> str | None: @@ -665,8 +671,11 @@ def active_key(self) -> str | None: # wrong size, or one wrapped as its own base64, refuses here, naming this provider, rather # than wherever a caller first decodes it. Matched as text rather than decoded, so the # check makes no extra copy of the key. Fixed text: no key material. + # Recorded (:func:`_recorded_refusal`), so the key seam's fixed-text replacement keeps this + # text rather than "the key source failed" (BACKLOG #6710 item 3). The name in it has + # passed :func:`checked_transit_key_name`. if _B64_32_BYTES.fullmatch(plaintext) is None: - raise KeyProviderError( + raise _recorded_refusal( f"[store].key_provider={_EXTRA!r} got a plaintext from Vault transit (key " f"{transit_key!r}) that is not base64 of 32 bytes; {_ENV_WRAPPED_DEK} must wrap " f"exactly the raw 32 DEK bytes, not a key of another length and not its base64." @@ -719,28 +728,55 @@ def store_token_setting() -> str | None: _B64_32_BYTES = re.compile(r"[A-Za-z0-9+/]{43}=") +def _recorded_refusal(text: str) -> KeyProviderError: + """A :class:`KeyProviderError` with ``text``, recorded as built by the engine, so a seam that + replaces a provider error with fixed text (``base.resolve_active_key``, ``build_store_cipher``) + keeps ``text``, read from the record and never from the instance. Only for a text built from + configuration this module has checked, never from a reply or key material.""" + from messagefoundry.store.base import _recorded + + refusal = KeyProviderError(text) + _recorded(refusal, text) + return refusal + + +def is_transit_key_name(name: str) -> bool: + """Whether ``name`` is in the shape :func:`checked_transit_key_name` admits, for a caller that + refuses with its own error class.""" + return _TRANSIT_KEY_NAME.fullmatch(name) is not None + + def checked_transit_key_name(name: str, *, selector: str) -> str: """``name``, refused unless it is a Transit key name (BACKLOG #6010). hvac quotes a name into the request path with ``/`` left unescaped, and requests drops ``..`` segments, so ``a/../../../sys/x`` would reach ``/v1/sys/x`` with the store token, and the capability probe would ask about a path the request never takes. ``selector`` names the - variable the name came from. The refusal is fixed text and does not echo the name.""" - if _TRANSIT_KEY_NAME.fullmatch(name) is None: - raise KeyProviderError( - f"{selector} is not a Vault transit key name: use letters, digits and underscores, " - f"with dots or hyphens only between them. Any other name could change which Vault " - f"path a request reaches, so it is refused." + variable the name came from. The refusal is fixed text and does not echo the name; it is + recorded, so the store's fixed-text seams keep it (BACKLOG #6010 item 3).""" + if not is_transit_key_name(name): + raise _recorded_refusal( + f"{selector} is not a Vault transit key name: use ASCII letters, digits and " + f"underscores, with dots or hyphens only between them. A slash, or a name of dots " + f"alone, could change which Vault path a request reaches, and a name outside the " + f"shape Vault gives its key names is refused with it." ) return name +def transit_key_name_setting(selector: str) -> str | None: + """The Transit key name in the environment variable ``selector``, ``None`` when it is unset + or empty, refused by :func:`checked_transit_key_name` when it is malformed. The one read for + the KEK name here and for the Transit cipher's data and audit key names.""" + name = os.environ.get(selector) or None + return None if name is None else checked_transit_key_name(name, selector=selector) + + def _kek_name() -> str | None: - """The KEK's Transit key name, ``None`` when unset. One read for :meth:`VaultKeyProvider.active_key` - and for :func:`kek_required_capabilities`, so the probe asks about the key the provider unwraps - under; both go through :func:`checked_transit_key_name`, which refuses a malformed name.""" - name = os.environ.get(_ENV_TRANSIT_KEY) or None - return None if name is None else checked_transit_key_name(name, selector=_ENV_TRANSIT_KEY) + """The KEK's Transit key name, ``None`` when unset, read by :func:`transit_key_name_setting`. + :meth:`VaultKeyProvider.active_key` and :func:`kek_required_capabilities` both read it here, so + the probe asks about the key the provider unwraps under.""" + return transit_key_name_setting(_ENV_TRANSIT_KEY) def store_vault_token() -> str: diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 1bfddad0f1..d8c93fc8f3 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -3142,6 +3142,7 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: status=StorePrivilegeStatus.UNOBSERVABLE, principal=str(scalar["principal"] or ""), database=database, + unread=("CREATE on the store's schema",), detail=( "current_schema() resolved to NULL, so CREATE on the store's schema was not read; " "[store].schema_management is 'external', which requires the runtime role to hold " @@ -3168,7 +3169,8 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: # read unobserved rather than clean. With an over-grant already found it stays OBSERVED, # so the start still refuses on what WAS read: a partial read only understates. unread_note = ( - f"the audit-table grants read NULL for {', '.join(audit_unread)}, so whether this " + "the audit-table grants read NULL, or a value that is not true or false, for " + f"{', '.join(audit_unread)}, so whether this " "role can change audit rows was not read; [store].schema_management is " "'external', which requires INSERT and SELECT only on audit_log" ) @@ -3178,6 +3180,7 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: status=StorePrivilegeStatus.UNOBSERVABLE, principal=str(scalar["principal"] or ""), database=database, + unread=audit_unread, detail=unread_note, ) unread_note = "; " + unread_note @@ -3192,6 +3195,8 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: server_roles=(), database_roles=tuple(f.name for f in facts if not f.is_self), excess=excess, + # #6015 item 2: an unread audit grant beside a read over-grant reaches the summary. + unread=audit_unread if external else (), detail=( "roles are every role this principal may assume (pg_has_role MEMBER, so roles reached by " "inheritance and by the set-role command alike); role ATTRIBUTES (SUPERUSER/CREATEROLE/CREATEDB/REPLICATION/BYPASSRLS) " diff --git a/messagefoundry/store/privilege.py b/messagefoundry/store/privilege.py index 4d2dd2a20c..48cfaebfa6 100644 --- a/messagefoundry/store/privilege.py +++ b/messagefoundry/store/privilege.py @@ -61,6 +61,7 @@ from messagefoundry.sqlserver_roles import ( SQLSERVER_FIXED_DATABASE_ROLES, SQLSERVER_FIXED_SERVER_ROLES, + probed_grant, ) from messagefoundry.support.redact import redact_log_line @@ -214,17 +215,6 @@ def audit_write_alias(table: str, privilege: str) -> str: return f"aw_{table}_{privilege.lower().replace(' ', '_')}" -def probed_grant(value: object) -> bool | None: - """Read one privilege-probe answer THREE ways: ``True`` held, ``False`` not held, ``None`` **not - read**. Only an int or a bool that is 0 or 1 reads; anything else, a NULL, the text ``"1"``, a - ``2``, ``1.0`` or bytes, is not read (BACKLOG #6015), as ``classify_login_roles`` reads the - partner login. Folding an unexpected value to "not held" would read as clean, so a driver that - changed its answer type could turn the probe into a false clean.""" - if isinstance(value, int) and value in (0, 1): - return bool(value) - return None - - def classify_audit_writes( row: Mapping[str, object], privileges: Sequence[str] ) -> tuple[tuple[str, ...], tuple[str, ...]]: @@ -295,7 +285,8 @@ def sqlserver_excess( Only ``provision-admin`` needs that grant, to read the catalog before a mint (``docs/DEPLOY-SERVER-DB.md`` §1.1), so the runtime login holding it is excess. Counted under ``external`` only, like the direct schema-DDL rights, and suppressed when ``db_owner``, - ``sysadmin``, database ``CONTROL`` or ``CONTROL SERVER`` is named, since each carries it. + ``sysadmin``, database ``CONTROL``, ``CONTROL SERVER`` or ``db_securityadmin`` is named, since + each carries it: ``db_securityadmin`` holds ``VIEW DEFINITION`` on the database. ``audit_writes`` names the row-changing rights the login holds on the append-only audit tables (:func:`audit_write_grant` wording, owner ruling R16). ``db_datawriter`` grants them on every table, @@ -341,7 +332,8 @@ def sqlserver_excess( if alter_schema and not ddladmin: out.append(f"ALTER on schema {alter_schema}") out.extend(w for w in audit_writes if not (ddladmin and w.startswith("ALTER "))) - if view_definition: + # db_securityadmin, named above, carries VIEW DEFINITION on the database (#6714 item 2). + if view_definition and "db_securityadmin" not in database_roles: out.append(view_definition_grant(*dict.fromkeys(view_definition))) return tuple(out) @@ -489,6 +481,19 @@ class StorePrivilegeReport: database_roles: tuple[str, ...] = () excess: tuple[str, ...] = () detail: str = "" + #: Grants the probe could NOT read and named (BACKLOG #6015 item 2). An OBSERVED report carries + #: them only beside an over-grant it found, so the over-grant WAS read and is weighed as one + #: (under enforce with no accepted opt-out, it refuses), and the summary names them, so the log + #: line and the alert do not imply the rest was read. Some UNOBSERVABLE + #: reports carry them too. An empty tuple does not mean every grant was read: at least a probe + #: that raised or returned no row reads nothing and names nothing here. + unread: tuple[str, ...] = () + + def __post_init__(self) -> None: + # `finding` reads status and excess only, so OBSERVED with nothing found and something + # unread would classify as clean. Refused here rather than trusted to each backend. + if self.status is StorePrivilegeStatus.OBSERVED and self.unread and not self.excess: + raise ValueError("an OBSERVED report with unread grants must carry the excess it found") @property def finding(self) -> str | None: @@ -502,7 +507,9 @@ def posture(self) -> StorePrivilegePosture: """The settings-layer view :func:`security_loosenings` consumes (a plain data type, so ``config.settings`` never has to know the store package — the same reason the connection-scoped deviations arrive there as plain names).""" - return StorePrivilegePosture(status=self.status, excess=self.excess, detail=self.detail) + return StorePrivilegePosture( + status=self.status, excess=self.excess, detail=self.detail, unread=self.unread + ) def summary(self, *, quote: Callable[[str], str] = repr) -> str: """One operator-readable line. The three statuses read differently ON PURPOSE. @@ -522,10 +529,13 @@ def summary(self, *, quote: Callable[[str], str] = repr) -> str: ) who = f"{quote(self.principal)} on {quote(self.database)}" if self.excess: + not_read = ( + f"; these grants were not read: {', '.join(self.unread)}" if self.unread else "" + ) return ( f"store privilege preflight: the {self.backend.value} store principal " f"{who} holds {len(self.excess)} privilege(s) " - f"BEYOND the documented least-privilege grant: {', '.join(self.excess)}" + f"BEYOND the documented least-privilege grant: {', '.join(self.excess)}{not_read}" ) return ( f"store privilege preflight: OBSERVED the {self.backend.value} store principal " @@ -544,6 +554,7 @@ def audit_detail(self) -> dict[str, object]: "server_roles": list(self.server_roles), "database_roles": list(self.database_roles), "excess": list(self.excess), + "unread": list(self.unread), "detail": self.detail, } @@ -556,7 +567,17 @@ class PrivilegeProbeStore(Protocol): not is reported UNOBSERVABLE rather than skipped: an unimplemented probe is a thing the engine could not observe, which is precisely what that status means.""" - async def probe_principal_privileges(self) -> StorePrivilegeReport: ... + async def probe_principal_privileges(self) -> StorePrivilegeReport: + """Read this store principal's effective privileges (BACKLOG #6015 item 3). + + ``OBSERVED`` with an empty ``excess`` is a clean read; ``UNOBSERVABLE`` is the absence of + one; ``NOT_APPLICABLE`` is SQLite's, which has no principal. ``unread`` names grants the + backend could not read; :class:`StorePrivilegeReport` refuses an ``OBSERVED`` report that + carries them with an empty ``excess``. A read can be left out of ``unread``: at least a + probe that raised or returned no row, and the SQL Server probe's failed best-effort + enumeration of user-defined roles, which it notes in ``detail`` only. Which grants a backend reads, how it reads each, and what it does with one + it could not read differ by backend; each backend's method says so.""" + ... class PrivilegeAlertSink(Protocol): diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index 18832fb2bf..4b7dee4197 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -32,7 +32,12 @@ text ``"None"`` encode differently, and a seal of one kind never verifies as another. Floats are encoded with :meth:`float.hex`, which is exact, so a value that round-trips through a ``REAL`` / ``DOUBLE PRECISION`` / ``FLOAT`` column seals identically on every backend. ``-0.0`` encodes as -``0.0`` does, and :meth:`RowSealer.seal` refuses a float that is not finite (BACKLOG #6717). +``0.0`` does, for every caller of the encoder, because a SQLite ``REAL`` column reads ``-0.0`` back +as ``0.0``; that one change to v1 predates any deployment. :meth:`RowSealer.seal` and +:meth:`TransitRowSealer.seal_async` raise :class:`NonFiniteSealValueError` when a field is a float +that is not finite. :func:`seal_bytes` itself encodes one without refusing it, so a check over a +row someone set to such a value fails rather than raises. Other callers of :func:`seal_bytes`, at +least the store's ``passkey_digest``, encode one without refusing it too (BACKLOG #6717). """ from __future__ import annotations @@ -45,6 +50,7 @@ import hashlib import hmac import logging +import math import time from collections.abc import Callable, Iterable from concurrent.futures import ThreadPoolExecutor @@ -70,8 +76,8 @@ log = logging.getLogger(__name__) #: The marker every stored seal starts with. Versioned, so a later format is an added version and -#: never a silent change to what an existing seal means. One change predates any deployment: v1's -#: encoding of ``-0.0`` moved onto ``0.0``'s (BACKLOG #6717). +#: never a silent change to what an existing seal means. The module docstring, *One encoder*, names +#: the one change to v1 that predates any deployment. SEAL_PREFIX: Final = "mfseal:v1:" #: The kind a session row is sealed under. Each sealed table has its own kind. @@ -115,8 +121,16 @@ _MAC_HEX_LEN: Final = 64 # HMAC-SHA256, hex -# A float strictly inside (-inf, inf) is finite; a NaN compares false both ways, so it is not. -_FLOAT_INF: Final = float("inf") + +class NonFiniteSealValueError(ValueError): + """Raised when a seal is made over a float that is a NaN or an infinity (BACKLOG #6717). + + SQLite stores a NaN as ``NULL``: a ``NOT NULL`` column refuses the write, and a nullable one + reads back ``None``, so the seal would fail the next read as if the row had been changed. An + infinity round-trips, but no sealed field means anything by one, so it is refused with the NaN. + Its own type, so a caller can tell it from the ``ValueError`` a malformed field pair raises + when it is unpacked. It is raised before any field is encoded, so a row that also holds a value + the encoder cannot read raises this, whatever the field order.""" class RowSealError(Exception): @@ -238,7 +252,7 @@ def _encode_value(value: object) -> tuple[bytes, bytes]: if isinstance(value, int): return _TYPE_INT, str(value).encode("ascii") if isinstance(value, float): - # -0.0 == 0.0, so this moves -0.0 alone onto 0.0's encoding and leaves every other float's. + # The module docstring, *One encoder*, says why -0.0 takes 0.0's encoding. return _TYPE_FLOAT, (0.0 if value == 0.0 else value).hex().encode("ascii") if isinstance(value, str): # surrogatepass, so a value a driver decoded with surrogateescape still encodes. @@ -252,6 +266,16 @@ def seal_bytes(kind: str, fields: Iterable[tuple[str, object]]) -> bytes: """The canonical bytes a seal is computed over: the scheme tag, ``kind``, then each ``(name, value)`` in the order given. The caller supplies a fixed order (a dataclass's field order), so two processes encoding one row agree.""" + return _seal_bytes(kind, fields, finite=False) + + +def _seal_bytes(kind: str, fields: Iterable[tuple[str, object]], *, finite: bool) -> bytes: + # ``finite`` is set only where a seal is made (the module docstring says why). The fields are + # read whole first, so the refusal precedes any encoder error, as NonFiniteSealValueError says. + if finite: + fields = tuple(fields) + if any(isinstance(v, float) and not math.isfinite(v) for _, v in fields): + raise NonFiniteSealValueError("a row seal refuses a float that is not finite") out = [_part(_SCHEME), _part(kind.encode("utf-8"))] for name, value in fields: type_byte, encoded = _encode_value(value) @@ -319,16 +343,11 @@ def _matches(key: bytes, kind: str, fields: Iterable[tuple[str, object]], mac: s def seal(self, kind: str, fields: Iterable[tuple[str, object]]) -> str: """The stored seal for a row of ``kind`` holding ``fields``. - Raises at least what the encoder raises, and ``ValueError`` when a float is a NaN or an - infinity (BACKLOG #6717). SQLite stores a NaN as ``NULL``, so its seal would fail the next - read as if the row had been changed. An infinity round-trips, but no sealed field means - anything by one, so it is refused with the NaN rather than sealed. The check is here and not in the encoder, so a row someone set to - such a value still fails :meth:`verify` rather than raising from it, and so that - :func:`seal_bytes`'s other callers keep their encodings.""" - fields = tuple(fields) - if any(isinstance(v, float) and not -_FLOAT_INF < v < _FLOAT_INF for _, v in fields): - raise ValueError("a row seal refuses a float that is not finite") - mac = hmac.new(self._key, seal_bytes(kind, fields), hashlib.sha256).hexdigest() + Raises at least what the encoder raises, and :class:`NonFiniteSealValueError` when a float + is a NaN or an infinity.""" + mac = hmac.new( + self._key, _seal_bytes(kind, fields, finite=True), hashlib.sha256 + ).hexdigest() return f"{SEAL_PREFIX}{self.key_id}:{mac}" def verify(self, kind: str, fields: Iterable[tuple[str, object]], stored: str | None) -> bool: @@ -698,8 +717,9 @@ def __init__( self._clock = clock self._throttle = SealFailureThrottle() - def _digest(self, kind: str, fields: Iterable[tuple[str, object]]) -> bytes: - return hashlib.sha256(self._prefix + _part(seal_bytes(kind, fields))).digest() + def _digest(self, kind: str, fields: Iterable[tuple[str, object]], *, finite: bool) -> bytes: + encoded = _seal_bytes(kind, fields, finite=finite) + return hashlib.sha256(self._prefix + _part(encoded)).digest() def _outage(self, exc: CipherError) -> TransitSealUnavailableError: # ERROR line, throttled per cause so a second cause inside the window is still logged. A @@ -714,9 +734,10 @@ def _outage(self, exc: CipherError) -> TransitSealUnavailableError: return TransitSealUnavailableError() @staticmethod - def _parse(stored: str | None) -> tuple[str, str, int] | None: - """``(key id, Transit string, version)`` from a well-formed stored seal, or ``None``.""" - if not stored or not stored.startswith(SEAL_PREFIX): + def _parse(stored: object) -> tuple[str, str, int] | None: + """``(key id, Transit string, version)`` from a well-formed stored seal, or ``None``. A + value that is not text is malformed, as :meth:`RowSealer._parse` reads it (BACKLOG #6718).""" + if not isinstance(stored, str) or not stored.startswith(SEAL_PREFIX): return None key_id, sep, mac = stored[len(SEAL_PREFIX) :].partition(":") version = transit_mac_version(mac) if sep else None @@ -731,8 +752,9 @@ def is_active(self, stored: str | None) -> bool: return parsed is not None and parsed[0] == self.key_id async def seal_async(self, kind: str, fields: Iterable[tuple[str, object]]) -> str: - """The stored seal for a row of ``kind`` holding ``fields``: one Transit ``hmac`` call.""" - digest = self._digest(kind, fields) + """The stored seal for a row of ``kind`` holding ``fields``: one Transit ``hmac`` call. + Raises :class:`NonFiniteSealValueError`, before any call, as :meth:`RowSealer.seal` does.""" + digest = self._digest(kind, fields, finite=True) failure: CipherError | None = None mac: object = None try: @@ -804,7 +826,7 @@ async def _check( key_name, retired = held if retired and not accept_retired: return False - digest = self._digest(kind, fields) + digest = self._digest(kind, fields, finite=False) entry = hashlib.sha256( _part(digest) + _part(key_id.encode("ascii")) + _part(mac.encode("ascii")) ).digest() @@ -995,15 +1017,12 @@ async def require_seal_for_write( here; a whole token hash in it would reach ``args``.""" if sealer is None: return - if kind != SESSION_KIND and stored is not None and not isinstance(stored, str): - # A record's stored seal that is not text (a BLOB a writer put there) is no seal: Forged, - # as main's record checks read it. A session's propagates as a TypeError, as on main. - raise RowSealError(kind, subject) fields = list(fields) if kind != SESSION_KIND: # A record holding a value the encoder cannot read fails its seal, as main's record checks # say. Only the encoding is inside this try, so a TypeError from a defect anywhere in the - # check below propagates as itself. A session's encoding error propagates, as on main. + # check below propagates as itself. A session's encoding error propagates, as on main, + # unless its stored seal is malformed (not text included), which fails before encoding. unreadable = False try: seal_bytes(kind, fields) diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index 0e590a8091..b2fe193753 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -3561,21 +3561,6 @@ def _any_grant(answers: str) -> str: ) -def _probed_grant(value: Any) -> bool | None: - """Classify one privilege-probe column THREE ways: ``True`` held, ``False`` not held, ``None`` **not - read**. A NULL never becomes a boolean here, and that is the whole point (BACKLOG #1234). - - ``IS_SRVROLEMEMBER``, ``IS_ROLEMEMBER`` and ``HAS_PERMS_BY_NAME`` each return **NULL** — not 0 — - when the name they are asked about does not resolve *for this caller*: an unknown or renamed role, - a principal the caller cannot see, a permission name this server version does not carry. Folding - that NULL through ``== 1`` yields ``False``, which reads as *"not a member"* and therefore as - clean, so a probe that read NOTHING would render as a clean bill of health — the exact false-clean - :meth:`SqlServerStore.probe_principal_privileges` names catalog enumeration to avoid, arriving by - the other door. ``True``/``False`` from a driver that returns booleans still read as ``1``/``0``; - any other value is not read either, by :func:`~messagefoundry.store.privilege.probed_grant`.""" - return probed_grant(value) - - class SqlServerStore: """SQL Server-backed durable queue (the :class:`Store` protocol). Open with :meth:`open`.""" @@ -5198,15 +5183,25 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: SERVER``, ``CONTROL`` on the database), so a principal over-granted by direct ``GRANT`` rather than by role membership is still seen. - **A NULL column is NOT READ, and a read that is not complete is never ``OBSERVED``** (BACKLOG - #1234). All three built-ins answer NULL when the name does not resolve for the caller, so the - argument above — *an empty enumeration must not render as a clean bill of health* — was - defeated by its own replacement until this arm distinguished the three states. Any probed - grant that reads NULL makes the whole report :attr:`StorePrivilegeStatus.UNOBSERVABLE`, named - grant by grant in the detail, because the documented grant is then genuinely UNVERIFIED: a - role that was never read is not a role the principal does not hold. Grants that DID read as - held are still reported, since a partial read can only understate an over-grant, never invent - one.""" + **A NULL column is NOT READ, and so is any answer but 0 or 1** (BACKLOG #1234, #6015, by + :func:`~messagefoundry.sqlserver_roles.probed_grant`). All three built-ins answer NULL when + the name does not resolve for the caller, so the argument above — *an empty enumeration must + not render as a clean bill of health* — was defeated by its own replacement until this arm + distinguished the three states. A fixed role, ``CONTROL SERVER`` or database ``CONTROL`` + that is not read is named grant by grant in the detail and in ``unread``: a role that was + never read is not a role the principal does not hold. With no over-grant read, that makes + the report :attr:`StorePrivilegeStatus.UNOBSERVABLE` (#1234). With one read, such as + ``sysadmin``, ``db_owner`` or a ``CONTROL``, the report stays ``OBSERVED`` with it in the + excess, so under enforce with no accepted opt-out the start refuses (owner ruling + 2026-11-23 on #6015 item 1). A partial read can only understate an over-grant, never + invent one. + + The grants that count only under ``external`` (``CREATE TABLE``, ``ALTER`` on the default + schema, ``VIEW DEFINITION`` on the default schema and ``dbo``, the audit-table rights) are + weighed after the excess (#6714): unread with nothing else found, the report is + ``UNOBSERVABLE``; unread beside an over-grant that WAS read, it stays ``OBSERVED`` and names + them in :attr:`~messagefoundry.store.privilege.StorePrivilegeReport.unread`, so the + over-grant is weighed as one (under enforce with no accepted opt-out, the start refuses).""" server_cols = [ f"IS_SRVROLEMEMBER(?) AS srv_{i}" for i in range(len(SQLSERVER_FIXED_SERVER_ROLES)) ] @@ -5226,7 +5221,9 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: # counted only under external, where the runtime login must hold none. " HAS_PERMS_BY_NAME(DB_NAME(), 'DATABASE', 'CREATE TABLE') AS create_table," " SCHEMA_NAME() AS default_schema," - " HAS_PERMS_BY_NAME(SCHEMA_NAME(), 'SCHEMA', 'ALTER') AS alter_schema," + # QUOTENAME (#6015 item 4), as the VIEW DEFINITION columns below and the proc-deploy + # guard pass their schema, so the schema probes quote one way. + " HAS_PERMS_BY_NAME(QUOTENAME(SCHEMA_NAME()), N'SCHEMA', N'ALTER') AS alter_schema," # #6714: VIEW DEFINITION on the two schemas a store's tables resolve through. Only # provision-admin needs it, so under external the runtime login holding it is excess. " HAS_PERMS_BY_NAME(QUOTENAME(SCHEMA_NAME()), N'SCHEMA', N'VIEW DEFINITION')" @@ -5242,27 +5239,27 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: detail="the privilege query returned no row", ) database = str(row["db_name"] or self._settings.database or "") - # Three-way, never two: held / not held / NOT READ. See _probed_grant for why a NULL folded to + # Three-way, never two: held / not held / NOT READ. See probed_grant for why a NULL folded to # False is a false-clean rather than a rounding error. unread: list[str] = [] held_server: list[str] = [] for i, name in enumerate(SQLSERVER_FIXED_SERVER_ROLES): - grant = _probed_grant(row[f"srv_{i}"]) + grant = probed_grant(row[f"srv_{i}"]) if grant is None: unread.append(f"server role {name}") elif grant: held_server.append(name) held_database: list[str] = [] for i, name in enumerate(SQLSERVER_FIXED_DATABASE_ROLES): - grant = _probed_grant(row[f"dbr_{i}"]) + grant = probed_grant(row[f"dbr_{i}"]) if grant is None: unread.append(f"database role {name}") elif grant: held_database.append(name) - control_server = _probed_grant(row["control_server"]) + control_server = probed_grant(row["control_server"]) if control_server is None: unread.append("control server") - control_database = _probed_grant(row["control_db"]) + control_database = probed_grant(row["control_db"]) if control_database is None: unread.append(f"CONTROL on database {database}") external = self._settings.resolved_schema_management() is SchemaManagement.EXTERNAL @@ -5270,19 +5267,19 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: # unread one never turns an over-grant that WAS read into an unobserved report: it is # weighed after the excess, below (#6714), so a read db_owner still refuses under enforce. external_unread: list[str] = [] - create_table = _probed_grant(row["create_table"]) + default_schema = str(row["default_schema"] or "") or "(unresolved default schema)" + create_table = probed_grant(row["create_table"]) if create_table is None: external_unread.append(f"create table on database {database}") - alter_schema = _probed_grant(row["alter_schema"]) + alter_schema = probed_grant(row["alter_schema"]) if alter_schema is None: - external_unread.append("ALTER on the default schema") + external_unread.append(f"ALTER on schema {default_schema}") # #6714: one column per distinct schema; when the default schema is dbo the two name one. - default_schema = str(row["default_schema"] or "") or "(unresolved default schema)" view_def_columns = {default_schema: "view_def_default"} view_def_columns.setdefault("dbo", "view_def_dbo") view_definition: list[str] = [] for schema, column in view_def_columns.items(): - grant = _probed_grant(row[column]) + grant = probed_grant(row[column]) if grant is None: external_unread.append(view_definition_grant(schema)) elif grant: @@ -5295,25 +5292,59 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: probed = len(SQLSERVER_FIXED_SERVER_ROLES) + len(SQLSERVER_FIXED_DATABASE_ROLES) + 2 held_labels = [f"server role {r}" for r in server_roles] held_labels += [f"database role {r}" for r in database_roles] + # A read CONTROL is an over-grant this report may refuse on, so it is named as read. + if control_server: + held_labels.append("control server") + if control_database: + held_labels.append(f"CONTROL on database {database}") also_unread = "" if external: # owner ruling R16 and #6714: each is a finding there + if create_table: + held_labels.append(f"create table on database {database}") + if alter_schema: + held_labels.append(f"ALTER on schema {default_schema}") held_labels += list(audit_writes) if view_definition: held_labels.append(view_definition_grant(*view_definition)) if external_unread: also_unread = f"; also not read: {', '.join(external_unread)}" - # The catalog enumeration below is skipped deliberately: it is additive only, and widening - # a report already saying the read was incomplete buys nothing an operator can act on. + # Owner ruling 2026-11-23 on #6015 item 1 ("Refuse when read"): an over-grant that WAS + # read keeps the report OBSERVED with it in the excess, so it is weighed as one (under + # enforce it refuses) rather than demoted to an unobserved warning by a neighbouring + # unread column. Unread reads as not held here, which can only understate the excess. + read_excess = sqlserver_excess( + server_roles=server_roles, + database_roles=database_roles, + control_server=control_server is True, + control_database=control_database is True, + database=database, + external=external, + create_table=create_table is True, + alter_schema=(default_schema if alter_schema else None), + audit_writes=audit_writes, + view_definition=tuple(view_definition), + ) + # The catalog enumeration below is skipped on this path, so a user-defined role is not + # weighed here: with no fixed-role over-grant read, a login whose only over-grant is a + # user-defined role reads unobserved, which under enforce warns unless + # [store].require_least_privilege is declared. return StorePrivilegeReport( backend=self.backend, - status=StorePrivilegeStatus.UNOBSERVABLE, + status=( + StorePrivilegeStatus.OBSERVED + if read_excess + else StorePrivilegeStatus.UNOBSERVABLE + ), principal=str(row["login_name"] or ""), database=database, server_roles=server_roles, database_roles=database_roles, + excess=read_excess, + unread=tuple(unread + (external_unread if external else [])), detail=( f"the privilege query returned NULL, or a value that is not 0 or 1, for" - f" {len(unread)} of {probed} probed grant(s), so they were not read and must not" + f" {len(unread)} of the {probed} role and CONTROL grant(s) probed, so they were" + " not read and must not" f" be reported as absent: {', '.join(unread)}" " (IS_SRVROLEMEMBER / IS_ROLEMEMBER / HAS_PERMS_BY_NAME answer NULL when the name" " does not resolve for this caller); what DID read as held:" @@ -5350,7 +5381,8 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: database=database, external=external, create_table=bool(create_table), - alter_schema=(str(row["default_schema"] or "") if alter_schema else None), + # The unresolved label, never "": an empty name would read as no grant (a false clean). + alter_schema=(default_schema if alter_schema else None), audit_writes=audit_writes, view_definition=tuple(view_definition), ) @@ -5371,6 +5403,7 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: database=database, server_roles=server_roles, database_roles=database_roles, + unread=tuple(external_unread), detail=( f"{note}; [store].schema_management is 'external', which requires INSERT and" " SELECT only on audit_log, no schema DDL right and no view definition on" @@ -5385,6 +5418,8 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: server_roles=server_roles, database_roles=database_roles, excess=excess, + # #6015 item 2: an unread external grant beside a read over-grant reaches the summary. + unread=tuple(external_unread) if external else (), detail=( f"database user {str(row['db_user'] or '')!r}; {note}; measured against the " + ( diff --git a/messagefoundry/transports/database.py b/messagefoundry/transports/database.py index a7f19bb6f1..aa321b2c4d 100644 --- a/messagefoundry/transports/database.py +++ b/messagefoundry/transports/database.py @@ -137,6 +137,7 @@ from messagefoundry.sqlserver_roles import ( SQLSERVER_FIXED_DATABASE_ROLES, SQLSERVER_FIXED_SERVER_ROLES, + probed_grant, ) from messagefoundry.transports.base import ( DEFAULT_MAX_ITEMS_PER_POLL, @@ -5797,10 +5798,10 @@ class LoginRoleReading: def classify_login_roles(row: Sequence[Any]) -> LoginRoleReading: """Judge one row of the role probe (BACKLOG #2617). Pure, so every verdict is unit-testable. - Read three ways, as ``store/privilege.py`` ``probed_grant`` reads the store login: ``1`` held, - ``0`` not held, NULL **not read**. Only an int or a bool that is 0 or 1 reads, so any other - value, such as the text ``"1"``, ``1.0`` or ``2``, is not read either, and ``probed_grant`` - reads all three the same way (BACKLOG #6015). Not even a ``1`` of another type reads as held, + Read three ways by :func:`~messagefoundry.sqlserver_roles.probed_grant`, the function the SQL + Server store preflight reads its own login with (BACKLOG #6015): ``1`` held, ``0`` not held, NULL + **not read**. Only an int or a bool that is 0 or 1 reads, so any other value, such as the text + ``"1"``, ``1.0`` or ``2``, is not read either. Not even a ``1`` of another type reads as held, because a held ``db_denydatawriter`` takes a finding away. ``IS_SRVROLEMEMBER`` and ``IS_ROLEMEMBER`` answer NULL for a name that does not resolve for this login, and a NULL folded to "not a member" would be a false clean. A role read as held is still @@ -5823,10 +5824,10 @@ def classify_login_roles(row: Sequence[Any]) -> LoginRoleReading: held: list[tuple[str, str]] = [] unread: list[str] = [] for (kind, role), value in zip(_LOGIN_ROLE_PROBE_ROLES, row, strict=True): - # The rule is the docstring's: anything but an int or bool 0 or 1 is unread. - if not isinstance(value, int) or value not in (0, 1): + grant = probed_grant(value) + if grant is None: unread.append(f"{kind} role {role}") - elif value == 1: + elif grant: held.append((kind, role)) allowed = set(LOOKUP_LOGIN_READ_ROLES) if ("database", "db_denydatawriter") in held: diff --git a/messagefoundry/transports/fhir.py b/messagefoundry/transports/fhir.py index 08a29e3e4f..6643ffa967 100644 --- a/messagefoundry/transports/fhir.py +++ b/messagefoundry/transports/fhir.py @@ -75,6 +75,7 @@ from messagefoundry.config.tls_policy import ( InsecureHopRefused, TrustAnchorPolicy, + hop_name_prefix, refuse_chain_check_on_os_roots, ) from messagefoundry.connection_names import fhir_lookup_record_name @@ -122,6 +123,7 @@ _no_redirect_opener, _query_credentials_sent, _redact_url, + _refuse_unsendable_static_auth, _shared_no_redirect_opener, assert_probe_hop, auth_challenge_refused, @@ -862,6 +864,24 @@ def _reject_config_control_chars(value: str, setting: str, where: str = "destina return value +def _refuse_unsendable_static_headers( + s: Mapping[str, Any], *, setting: str, connection: str | None +) -> None: + """Refuse at construction at least these static settings ``_build_headers`` would drop or + send other than as configured (BACKLOG #8299 item 8): a ``headers`` that is not a ``dict``, the + one table type ``_build_headers`` and the static-credential census read, and the credential + rules of :func:`~messagefoundry.transports.rest._refuse_unsendable_static_auth`. A static + ``Authorization`` entry in ``headers`` beside ``bearer_token`` or Basic is not refused here. + Names settings, never a value.""" + extra = s.get("headers") + if extra is not None and not isinstance(extra, dict): + raise ValueError( + f"{hop_name_prefix(connection)}{setting} 'headers' must be a table of header names " + "to values" + ) + _refuse_unsendable_static_auth(s, connection=connection, transport=setting) + + def _refuse_unsendable_conditional_query(query: str, conditional: str | None, base: str) -> None: """Refuse at CONSTRUCTION a ``conditional_query`` its sink could never send (BACKLOG #5911). @@ -1098,13 +1118,14 @@ def __init__(self, config: Destination) -> None: self.base_url = url # BACKLOG #2060: names this hop in a bounded-read refusal, which never carries the URL. self._hop = hop_identity("FHIR", config.name) - # BACKLOG #5529: refused before any hop gate logs a crossing for a connection that never builds. + # BACKLOG #5529: refused before any hop gate, so a build this refuses logs no crossing. from messagefoundry.transports.http_auth import ( refuse_authorization_signer_beside_digest, refuse_http_digest_conflicts, ) digest_selected = refuse_http_digest_conflicts(s) + _refuse_unsendable_static_headers(s, setting="FHIR destination", connection=config.name) self.fhir_version: str = str(s.get("fhir_version", "R4B")) self.format: str = str(s.get("format", "json")) if self.format != "json": @@ -1215,7 +1236,7 @@ def __init__(self, config: Destination) -> None: } # BACKLOG #5911: a static url or header the wire refuses fails the connection here, as a # bad conditional_query does, rather than every message at send time. Before any hop gate, - # so none audits a crossing for a connection that never builds (#5529). A static + # so a build this screen refuses leaves no crossing record (#5529). A static # conditional moved into the Bundle entry above is JSON there, never an HTTP header, so it # is not judged by the header rules. refuse_unsendable_static_request(url, self._headers, setting="FHIR destination") @@ -2000,6 +2021,29 @@ def _mint_bearer(token: Any, prefix: str) -> str: return bearer +def _bounded_lookup_request(url: str, headers: dict[str, str], label: str) -> None: + """:func:`enforce_outbound_length_limits` for a ``FhirLookup``, its refusal named by + :func:`hop_name_prefix` (BACKLOG #8299 item 9).""" + try: + enforce_outbound_length_limits(url, headers) + except ValueError as exc: + raise ValueError(f"{hop_name_prefix(label)}FhirLookup {exc}") from exc + + +class _LookupPlan(NamedTuple): + """What :meth:`FhirLookupExecutor._planned` settles for one lookup before any is built.""" + + url: str + scheme: str + headers: dict[str, str] + timeout: float + attested: bool + accepted: bool + reason: str | None + revocation_attested: bool + revocation_reason: str | None + + class FhirLookupExecutor: """GET-only executor for handler-callable **live** FHIR reads (``fhir_lookup``, ADR 0043). @@ -2043,15 +2087,16 @@ def __init__( # the runner. A FhirLookup connection has no Destination to carry it (unlike every other # HTTP-family hop), which is why this executor's opener map could not name an internal CA at # all. `None` (a direct test build) = the OS trust store, byte-identical. - from messagefoundry.transports.smart import token_provider_from_settings - - # BACKLOG #5911: every lookup's static url and headers are screened before any lookup is - # built, so a refusal from this screen leaves no hop-gate crossing record (#5529). A - # failure later in the loop below still can leave one, from the failing lookup itself or - # from a lookup built before it. - screened = { - cname: self._screened_static_request(cname, raw) for cname, raw in connections.items() - } + from messagefoundry.transports.smart import ( + smart_auth_configured, + token_provider_from_settings, + ) + + # BACKLOG #5911, #8299 items 2, 3 and 9: the checks _planned runs, for every lookup, come + # before any lookup is built, so a lookup one of them refuses leaves no hop-gate crossing + # record (#5529). A refusal later in the loop below, from a check _planned does not run, + # still can leave one, from the failing lookup itself or from a lookup built before it. + planned = {cname: self._planned(cname, raw) for cname, raw in connections.items()} self._base: dict[str, str] = {} self._headers: dict[str, dict[str, str]] = {} self._timeout: dict[str, float] = {} @@ -2071,33 +2116,13 @@ def __init__( # are their own namespace: an outbound and a lookup may share a name, and the records must # still tell them apart. The same prefix the loosening reports use (accepted_cleartext_hops). label = fhir_lookup_record_name(cname) - url, scheme, headers = screened[cname] + plan = planned[cname] + url, scheme, headers = plan.url, plan.scheme, plan.headers + attested, lk_accepted, lk_reason = plan.attested, plan.accepted, plan.reason self._base[cname] = url - # BACKLOG #5959: above zero, as REST's; positive_seconds says why. - self._timeout[cname] = positive_seconds( - s.get("timeout_seconds", 30.0), - knob="timeout_seconds", - transport=f"FhirLookup {cname!r}", - ) + self._timeout[cname] = plan.timeout self._encoding[cname] = str(s.get("encoding", "utf-8")) - # #200 (ADR 0092): the per-connection insecure-hop attestation keys the posture-keyed refusal. - # Validated like the DB lookups': a flag written into this mutable dict without its - # reason is refused here rather than crossing unexplained. - # ADR 0153: a FhirLookup connection has no Destination, so its cleartext-acceptance pair - # arrives in these settings, mirrored from the spec's typed fields by - # wiring_runner._fhir_lookup_settings (never from a raw key in `spec.settings`, BACKLOG #2050). - # Vault BACKLOG #3139: a refusal from either reader names the lookup, as the url checks do. - try: - attested = hop_attestation_from_settings(s) - lk_accepted, lk_reason, _ = cleartext_acceptance_from_settings(s) - # FhirLookupSpec refuses an acceptance or a revocation attestation with no reason, - # and FhirLookup() and the runner's settings builder refuse the attested-plus- - # accepted pair. A directly built executor meets those rules here too. - _check_cleartext_acceptance(lk_accepted, lk_reason) - _check_revocation_attestation(*revocation_attestation_from_settings(s)[:2]) - check_attested_and_accepted(attested, lk_accepted) - except ValueError as exc: - raise ValueError(f"FhirLookup {cname!r}: {exc}") from exc + smart = smart_auth_configured(s) # BACKLOG #112/#127/#128 (ADR 0126): per-connection forward/egress proxy for the read hop AND # the SMART token endpoint (None → byte-identical). Bypass resolved per target host (#128). proxy = egress_route_from_settings( @@ -2111,13 +2136,13 @@ def __init__( proxy_handlers = proxy_dest.opener_handlers() if proxy_dest is not None else () if proxy_dest is not None: headers.update(proxy_dest.auth_headers()) # pre-emptive Proxy-Authorization (0126) + # ASVS 4.2.5: _planned bounded the static url and headers; this bounds the header + # just added, after the proxy route's gate. + _bounded_lookup_request(url, headers, label) # The read sends Authorization (static or SMART) — refuse it over cleartext http. - # #1660: the SMART token hop takes the same instance [tls] anchor policy the read hop - # resolves below, against the TOKEN host rather than this lookup's base URL. - token = token_provider_from_settings( - s, proxy=proxy, trust_anchor_policy=trust_anchor_policy - ) - check_headers = {**headers, "Authorization": "Bearer"} if token is not None else headers + # BACKLOG #8299 item 4: judged before the SMART provider is built, so a lookup this + # refuses builds no token hop. smart_auth_configured is the provider's own switch. + check_headers = {**headers, "Authorization": "Bearer"} if smart else headers refuse_cleartext_credentials( scheme, check_headers, @@ -2131,6 +2156,11 @@ def __init__( ), connection=label, ) + # #1660: the SMART token hop takes the same instance [tls] anchor policy the read hop + # resolves below, against the TOKEN host rather than this lookup's base URL. + token = token_provider_from_settings( + s, proxy=proxy, trust_anchor_policy=trust_anchor_policy + ) # ASVS 12.2.1: a cleartext read pulls the PHI resource/searchset back over the wire, so a # cleartext http read to a non-loopback host is refused too (loopback stays byte-identical). self._hop_guard[cname] = refuse_cleartext_egress( @@ -2141,10 +2171,6 @@ def __init__( cleartext_reason=lk_reason, connection=label, ) - # ASVS 4.2.5: this executor never called the construction gate at all -- fhir.py's only - # call site was the DESTINATION's __init__, so a lookup connection's base URL and static - # headers were unbounded on both sides. - enforce_outbound_length_limits(url, headers) self._headers[cname] = headers self._token[cname] = token if bool_setting(s, "verify_tls", default=True): @@ -2173,16 +2199,12 @@ def __init__( # the hop that pulls patient data back. Called AFTER the opener, and handed it, so a # [tls].crl_file that reached THIS lookup's own context relaxes the refusal and a # lookup the CRL never reached keeps it (BACKLOG #2188). - try: - rev_attested, rev_reason, _ = revocation_attestation_from_settings(s) - except ValueError as exc: - raise ValueError(f"FhirLookup {cname!r}: {exc}") from exc refuse_unrevoked_verified_hop( scheme, url, connector=f"FhirLookup {cname!r}", - revocation_attested=rev_attested, - revocation_attested_reason=rev_reason, + revocation_attested=plan.revocation_attested, + revocation_attested_reason=plan.revocation_reason, opener=self._opener[cname], connection=label, description="sends read requests over verified https, with no certificate " @@ -2207,10 +2229,11 @@ def __init__( self._opener[cname] = _insecure_opener(*proxy_handlers) @classmethod - def _screened_static_request( - cls, cname: str, s: Mapping[str, Any] - ) -> tuple[str, str, dict[str, str]]: - """The lookup's base url, its scheme and its static headers, once they pass the screens. + def _planned(cls, cname: str, s: Mapping[str, Any]) -> _LookupPlan: + """What this lookup's checks run before any lookup is built settle, once it passes them + (BACKLOG #8299 items 2, 3 and 9): its base url, scheme and static headers, screened and + bounded, its timeout, and its hop declarations. Each refusal names the lookup. The build + loop runs at least the cleartext-credential check and the SMART settings checks later. #1241: the SECOND url construction site in this module. The destination screens its own; screening one and not its sibling reproduces the asymmetry the item reports. BACKLOG #5911: @@ -2225,9 +2248,43 @@ def _screened_static_request( f"FhirLookup {cname!r} 'url' must be http or https, got scheme {scheme!r}" ) refuse_url_credentials(url, f"FhirLookup {cname!r} 'url'") + # Named by hop_name_prefix, whose `;` keeps a credential-word lookup name from making + # the log scrubber redact the rest of the refusal. + label = fhir_lookup_record_name(cname) + _refuse_unsendable_static_headers(s, setting="FhirLookup", connection=label) headers = cls._build_headers(s) refuse_unsendable_static_request(url, headers, setting=f"FhirLookup {cname!r}") - return url, scheme, headers + # BACKLOG #5959: above zero, as REST's; positive_seconds says why. + timeout = positive_seconds( + s.get("timeout_seconds", 30.0), + knob="timeout_seconds", + transport=f"FhirLookup {cname!r}", + ) + # ASVS 4.2.5: the lookup's static url and headers are bounded at construction, as the + # destination's are. Before this gate was added here, they were unbounded on both sides. + _bounded_lookup_request(url, headers, label) + # #200 (ADR 0092): the per-connection insecure-hop attestation keys the posture-keyed refusal. + # Validated like the DB lookups': a flag written into this mutable dict without its + # reason is refused here rather than crossing unexplained. + # ADR 0153: a FhirLookup connection has no Destination, so its cleartext-acceptance pair + # arrives in these settings, mirrored from the spec's typed fields by + # wiring_runner._fhir_lookup_settings (never from a raw key in `spec.settings`, BACKLOG #2050). + # Vault BACKLOG #3139: a refusal from either reader names the lookup, as the url checks do. + try: + attested = hop_attestation_from_settings(s) + accepted, reason, _ = cleartext_acceptance_from_settings(s) + # FhirLookupSpec refuses an acceptance or a revocation attestation with no reason, + # and FhirLookup() and the runner's settings builder refuse the attested-plus- + # accepted pair. A directly built executor meets those rules here too. + _check_cleartext_acceptance(accepted, reason) + rev_attested, rev_reason, _ = revocation_attestation_from_settings(s) + _check_revocation_attestation(rev_attested, rev_reason) + check_attested_and_accepted(attested, accepted) + except ValueError as exc: + raise ValueError(f"FhirLookup {cname!r}: {exc}") from exc + return _LookupPlan( + url, scheme, headers, timeout, attested, accepted, reason, rev_attested, rev_reason + ) @staticmethod def _build_headers(s: Mapping[str, Any]) -> dict[str, str]: diff --git a/messagefoundry/transports/http_auth.py b/messagefoundry/transports/http_auth.py index 43c03fae57..7c55b035f3 100644 --- a/messagefoundry/transports/http_auth.py +++ b/messagefoundry/transports/http_auth.py @@ -82,6 +82,7 @@ "digest_handler_from_settings", "http_digest_selected", "is_authorization_header_name", + "refuse_authorization_signer_beside_credential", "refuse_authorization_signer_beside_digest", "refuse_http_digest_conflicts", "oauth2_auth_configured", @@ -525,15 +526,15 @@ def refuse_http_digest_conflicts(s: Mapping[str, Any]) -> bool: is refused under the same rule. Also refuses, here rather than late, a SMART or OAuth2 bearer provider beside Digest and a missing Digest user or password. Names settings, never a value. A signing header named ``Authorization`` is refused later, once the signer is built, by - :func:`refuse_authorization_signer_beside_digest`.""" + :func:`refuse_authorization_signer_beside_digest` or + :func:`refuse_authorization_signer_beside_credential`.""" if not http_digest_selected(s): return False # Read strictly: a non-bool flag raises HttpAuthError naming the connection (#2232). _, (_, _, conn), _ = hop_declarations_from_settings(s, HttpAuthError) prefix = hop_name_prefix(conn) static = [name for name in ("bearer_token", "basic_user", "basic_password") if s.get(name)] - extra = s.get("headers") - if isinstance(extra, Mapping) and any(is_authorization_header_name(str(k)) for k in extra): + if _static_authorization_header(s): static.append("an Authorization entry in headers") if static: raise HttpAuthError( @@ -561,10 +562,56 @@ def refuse_authorization_signer_beside_digest( so under that name it would replace the Digest response on the wire. ``sign_header`` is the built signer's ``header_name``, or ``None`` when signing is off, so the typed ``Destination.sign`` and the flat ``sign_*`` settings are read by the one rule that builds the - signer. Called by REST, SOAP and FHIR, the Digest connectors that build a signer.""" - if digest and sign_header is not None and is_authorization_header_name(sign_header): + signer. Called by FHIR; REST and SOAP call + :func:`refuse_authorization_signer_beside_credential`, which also reads Digest.""" + _refuse_authorization_signer(sign_header, "HTTP Digest" if digest else None, connection) + + +def authorization_credential(s: Mapping[str, Any], *, digest: bool) -> str | None: + """The credential a connection configures for its ``Authorization`` header, named for a + refusal, or ``None`` when it configures none (BACKLOG #5526 item 6). ``digest`` is + :func:`refuse_http_digest_conflicts`'s answer, which the caller already holds. Names a + setting or a mode, never a value.""" + if digest: + return "HTTP Digest" + if smart_auth_configured(s) or oauth2_auth_configured(s): + return "a bearer-token provider" + if s.get("basic_user") and s.get("basic_password"): + return "HTTP Basic" + if s.get("bearer_token"): + return "a bearer_token" + if _static_authorization_header(s): + return "an Authorization entry in headers" + return None + + +def _static_authorization_header(s: Mapping[str, Any]) -> bool: + """Whether the static ``headers`` table holds ``Authorization`` in any spelling.""" + extra = s.get("headers") + return isinstance(extra, Mapping) and any(is_authorization_header_name(str(k)) for k in extra) + + +def refuse_authorization_signer_beside_credential( + sign_header: str | None, s: Mapping[str, Any], *, digest: bool, connection: str | None +) -> None: + """Refuse a detached-JWS signing header named ``Authorization``, however spelled, beside any + credential the connection configures for that header (:func:`authorization_credential`; + BACKLOG #5526 item 6). ``_post`` writes the signature per request after the configured or + minted credential, so under that name it would replace the credential on every send. Called + by REST and SOAP; a signature under that name with no credential beside it still builds.""" + if sign_header is None or not is_authorization_header_name(sign_header): + return + _refuse_authorization_signer( + sign_header, authorization_credential(s, digest=digest), connection + ) + + +def _refuse_authorization_signer( + sign_header: str | None, credential: str | None, connection: str | None +) -> None: + if credential and sign_header is not None and is_authorization_header_name(sign_header): raise HttpAuthError( - f"{hop_name_prefix(connection)}HTTP Digest cannot be configured beside a signing " + f"{hop_name_prefix(connection)}{credential} cannot be configured beside a signing " "header named Authorization; configure exactly one" ) diff --git a/messagefoundry/transports/rest.py b/messagefoundry/transports/rest.py index 91e7f494c5..b25f7a4c72 100644 --- a/messagefoundry/transports/rest.py +++ b/messagefoundry/transports/rest.py @@ -2931,31 +2931,36 @@ def egress_route_from_settings( ) -def _refuse_unsendable_static_auth(s: Mapping[str, Any], *, connection: str | None) -> None: - """Refuse at construction a static REST credential :meth:`RestDestination._build_headers` - could not send as configured (BACKLOG #5354). Read on the resolved settings, since the +def _refuse_unsendable_static_auth( + s: Mapping[str, Any], *, connection: str | None, transport: str = "REST destination" +) -> None: + """Refuse at construction a static HTTP credential the connector's ``_build_headers`` could + not send as configured (BACKLOG #5354; the FHIR destination and ``FhirLookup`` since BACKLOG + #8299 item 8, with ``transport`` naming them). Read on the resolved settings, since the factory sees ``env()`` references and cannot tell one that resolves empty from a set value. One Basic half without the other, or a half that resolves empty, would send no Authorization at all. A ``:`` in ``basic_user`` would move the rest of the user into the password, since RFC 7617 splits the pair at the first colon. ``bearer_token`` beside a Basic pair would be replaced - by it without a word. Each refusal names settings, never a value. Digest beside either was - already refused by ``refuse_http_digest_conflicts``.""" + by it without a word. Each refusal names settings, never a value. On the REST and FHIR + destinations, Digest beside either was already refused by ``refuse_http_digest_conflicts``, + which they call first. ``FhirLookup`` does not call that function and builds no Digest + handler.""" prefix = hop_name_prefix(connection) user, password = s.get("basic_user"), s.get("basic_password") if bool(user) != bool(password): raise HttpAuthError( - f"{prefix}REST destination basic_user and basic_password must be set together; one " + f"{prefix}{transport} basic_user and basic_password must be set together; one " "without the other, or one that resolves empty, would send no HTTP Basic credential" ) if user and ":" in str(user): raise HttpAuthError( - f"{prefix}REST destination basic_user must not contain ':'; HTTP Basic splits the " + f"{prefix}{transport} basic_user must not contain ':'; HTTP Basic splits the " "user from the password at the first colon (RFC 7617)" ) if user and s.get("bearer_token"): raise HttpAuthError( - f"{prefix}REST destination sets both bearer_token and basic_user/basic_password; " + f"{prefix}{transport} sets both bearer_token and basic_user/basic_password; " "they share the Authorization header, so configure exactly one" ) @@ -3018,10 +3023,10 @@ def __init__(self, config: Destination) -> None: accepted, accept_reason = config.cleartext_accepted, config.cleartext_reason # Captured at construction; re-asserted (zero I/O) at the byte-crossing in _post (decision 4). self._hop_guard: InsecureHopGuard | None = None - # BACKLOG #5529: an http_auth this connection cannot honour is refused first, so a connection - # that never builds logs no insecure-hop crossing or warning below. Lazy: http_auth imports rest. + # BACKLOG #5529: an http_auth this connection cannot honour is refused first, so a build + # this refuses logs no insecure-hop crossing or warning below. Lazy: http_auth imports rest. from messagefoundry.transports.http_auth import ( - refuse_authorization_signer_beside_digest, + refuse_authorization_signer_beside_credential, refuse_http_digest_conflicts, ) @@ -3040,7 +3045,7 @@ def __init__(self, config: Destination) -> None: # destination, so verify_tls=false turns off no verification the engine does. It used to skip # the revocation guard below, which runs only on the verify-ON branch. Refused here, above # refuse_verify_off, so that gate logs no attested crossing and no DISABLED warning for a - # connection that never builds. No attestation crosses it, as with proxy_url above. + # connection this refuses. No attestation crosses it, as with proxy_url above. verify = bool_setting(s, "verify_tls", default=True) if self._ech_sidecar is not None and not verify: raise ValueError( @@ -3122,8 +3127,11 @@ def __init__(self, config: Destination) -> None: # identical). Built here so a bad key/algorithm fails loud at connector construction (check/ # dry-run/start), like a bad TLS cert; the per-request signature is minted in _post (off-loop). self._signer: MessageSigner | None = signer_from_destination(config) - refuse_authorization_signer_beside_digest( + # BACKLOG #5526 item 6: under the Authorization name the signature would replace the + # configured or minted credential _post writes before it. + refuse_authorization_signer_beside_credential( None if self._signer is None else self._signer.header_name, + s, digest=digest_selected, connection=config.name, ) diff --git a/messagefoundry/transports/soap.py b/messagefoundry/transports/soap.py index fc6808a405..7308e0e042 100644 --- a/messagefoundry/transports/soap.py +++ b/messagefoundry/transports/soap.py @@ -75,6 +75,7 @@ flag_from_settings, ) from messagefoundry.config.tls_policy import ( + MIRRORED_CONNECTION_SETTING, SYSTEM_TRUST_ANCHOR, TrustAnchor, build_verifying_client_context, @@ -154,8 +155,8 @@ # not a cosmetic miss. Kept identical to _HEADER_EL_RE below, which already had it right. _FAULT_RE = re.compile(r"<\s*(?:[\w.\-]+:)?Fault[\s/>]", re.IGNORECASE) # The SOAP Body start tag. BACKLOG #2827: a SOAP 1.1 or 1.2 fault is a Body child, so _classify_soap -# searches for the Fault, and for a WS-Security code, from the first one; _find_fault says when it -# searches the whole reply instead. +# searches for the Fault, and for a WS-Security code, from the first one outside markup +# (_BODY_OUTSIDE_MARKUP_RE); _find_fault says when it searches the whole reply instead. _BODY_RE = re.compile(r"<\s*(?:[\w.\-]+:)?Body[\s/>]", re.IGNORECASE) _SENDER_RE = re.compile(r"client|sender", re.IGNORECASE) _RECEIVER_RE = re.compile(r"server|receiver", re.IGNORECASE) @@ -170,14 +171,8 @@ # from every start tag lacking a close, so a partner reply of repeated start tags cost the square of # its length. _code_text finds the `>` and `])", re.IGNORECASE) _CODEVALUE_RE = re.compile(r"<\s*(?:[\w.\-]+:)?Value\b", re.IGNORECASE) @@ -197,6 +192,9 @@ # instruction that holds a Fault start tag or a Fault or Code close tag. The openers stay # case-sensitive, as XML has them; only each tag is matched in any case. _FAULT_OUTSIDE_MARKUP_RE = re.compile(r"soap:Client" + "soap:Server" + "", + "soap-sender", + ), + "header-wssecurity-code": ( + "FailedAuthentication" + "soap:Server" + "", + "wssecurity", + ), + "cdata-body-tag": ( + "]]>soap:Client" + "soap:Server" + "", + "soap-sender", + ), +} + + +@pytest.mark.parametrize( + ("body", "unanchored"), + list(_BODY_TAG_IN_MARKUP_BEFORE_THE_HEADER.values()), + ids=list(_BODY_TAG_IN_MARKUP_BEFORE_THE_HEADER), +) +def test_a_body_start_tag_inside_markup_is_not_the_anchor( + body: str, unanchored: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """The real Body's Receiver fault decides, on 200 and 500. Control: with the plain Body + pattern patched in for the outside-markup one, the Body start tag inside markup is the anchor + again and the Header decides, as before the fix.""" + assert _outcome(_classify_soap(200, body)) == "transient" + assert _outcome(_classify_soap(500, body)) == "transient" + assert _fault_code(body) == "soap:Server" + monkeypatch.setattr(soap, "_BODY_OUTSIDE_MARKUP_RE", soap._BODY_RE) + assert _outcome(_classify_soap(200, body)) == unanchored + + +def test_with_every_body_start_tag_inside_markup_the_whole_reply_is_searched() -> None: + """A Body start tag only inside markup is no Body, so the Fault search reads the reply whole, + as it reads one with no Body start tag, and the reply still reads as a fault.""" + body = "soap:Client" + assert _outcome(_classify_soap(200, body)) == "soap-sender" + + +# --- step 9: a whitespace-only code element reads as one that holds no code ----------------------- + +#: Replies that differ only in whether the first-child code element is empty or holds only +#: whitespace. Before the fix the empty one fell back to the earlier search and the blank one did +#: not, so the two read differently. +_EMPTY_AND_BLANK = { + "faultcode-after-a-commented-value": ( + "{}" + "" + ), + "value-after-a-commented-value": ( + "{}" + "" + ), +} + + +@pytest.mark.parametrize("shape", list(_EMPTY_AND_BLANK.values()), ids=list(_EMPTY_AND_BLANK)) +@pytest.mark.parametrize("blank", [" ", "\n\t ", "\r\n"]) +def test_a_blank_code_element_reads_as_an_empty_one(shape: str, blank: str) -> None: + """Control: the empty element's reading, which the fallback decides.""" + empty, spaced = shape.format(""), shape.format(blank) + assert _outcome(_classify_soap(200, empty)) == "transient" + assert _fault_code(spaced) == _fault_code(empty) + assert _outcome(_classify_soap(200, spaced)) == _outcome(_classify_soap(200, empty)) + + +# --- step 11: the fallback reuses the close-tag search where no markup was stepped over ----------- + + +class _CountingPattern: + """A stand-in for a compiled pattern that records each ``search`` call's range.""" + + def __init__(self, pattern: re.Pattern[str]) -> None: + self._pattern = pattern + self.searches: list[tuple[int, int]] = [] + + def search(self, string: str, pos: int = 0, endpos: int | None = None) -> Any: + end = len(string) if endpos is None else endpos + self.searches.append((pos, end)) + return self._pattern.search(string, pos, end) + + def match(self, string: str, pos: int = 0, endpos: int | None = None) -> Any: + return self._pattern.match(string, pos, len(string) if endpos is None else endpos) + + +#: Replies whose first child yields no code, so the fallback runs; none holds markup. +_FALLBACK_NO_MARKUP = { + "faultstring-first": ( + "busysoap:Server" + "" + "" * 50 + ), + "reason-first": ( + "busy" + "env:Receiver" + ), + "no-close-tag": "busyServer", +} + + +@pytest.mark.parametrize("body", list(_FALLBACK_NO_MARKUP.values()), ids=list(_FALLBACK_NO_MARKUP)) +def test_the_fallback_does_not_rescan_for_the_fault_close_tag( + body: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """Where the first-child read's close-tag search stepped over no markup, its Fault close tag + is the fallback's, so no plain ``_FAULT_END_RE`` scan runs past the Fault start tag. Control: + the code read is a Receiver one, which only the fallback finds in these shapes.""" + expected = _fault_code(body) + assert soap._RECEIVER_RE.search(expected), "the shape must reach the fallback's code" + counting = _CountingPattern(soap._FAULT_END_RE) + monkeypatch.setattr(soap, "_FAULT_END_RE", counting) + assert _fault_code(body) == expected + fault = soap._FAULT_RE.search(body) + assert fault is not None + gt = body.index(">", fault.end() - 1) + # At most the bounded search of the Fault start tag's own text, never one past its end. + assert all(end <= gt + 1 for _, end in counting.searches), counting.searches + + +def test_the_fallback_still_ends_at_a_close_tag_inside_markup() -> None: + """Where the close-tag search stepped over markup, the fallback's range still ends at the first + plain Fault close tag, as before #5912 (the shape the changelog names).""" + body = ( + "busy" + "soap:Server" + ) + assert _fault_code(body) == "" + assert _outcome(_classify_soap(200, body)) == "soap-fault" + + +def test_a_close_tag_inside_the_fault_start_tag_still_ends_the_fallback_range() -> None: + """The earlier search's range starts where the Fault's name ends, so a Fault close tag inside + the start tag's own text ends it, as before.""" + body = "xsoap:Server" + assert _fault_code(body) == "" + + +def test_a_leading_xml_declaration_keeps_the_plain_body_anchor( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Review round 2: a reply that opens with an XML declaration and holds no other markup ahead + of the Body reads the plain Body start tag, without the Python-level step-over. Control: the + reply still reads its Body's Receiver fault.""" + body = ( + 'soap:Client' + "soap:Server" + "" + ) + assert _outcome(_classify_soap(200, body)) == "transient" + calls: list[object] = [] + original = soap._search_outside_markup + + def counting(pattern: Any, *args: Any, **kwargs: Any) -> Any: + calls.append(pattern) + return original(pattern, *args, **kwargs) + + monkeypatch.setattr(soap, "_search_outside_markup", counting) + assert _outcome(_classify_soap(200, body)) == "transient" + assert soap._BODY_OUTSIDE_MARKUP_RE not in calls + + +def test_a_body_tag_inside_the_xml_declaration_still_takes_the_step_over() -> None: + """A Body start tag inside the declaration itself is not taken as the anchor.""" + body = ( + ' ?>' + "soap:Client" + "soap:Server" + ) + assert _outcome(_classify_soap(200, body)) == "transient" diff --git a/tests/test_soap_fault_scan_linear.py b/tests/test_soap_fault_scan_linear.py index bf1042e096..a541f0c7ce 100644 --- a/tests/test_soap_fault_scan_linear.py +++ b/tests/test_soap_fault_scan_linear.py @@ -74,7 +74,12 @@ def _old_fault_code(body: str, fault: object = None) -> str: #: Markup that is not an element, whole: what the first-child search steps over and, BACKLOG #: #5912, what the Fault search and the Fault and Code close-tag searches step over. _REF_MARKUP = r"||<\?.*?\?>" -_REF_BODY_RE = re.compile(r"<\s*(?:[\w.\-]+:)?Body[\s/>](.*)", re.IGNORECASE | re.DOTALL) +#: The reply read from its start as tokens: each markup whole, a Body start tag (group 1), or one +#: character, so a Body start tag in group 1 is outside markup (BACKLOG #5912 closing step 6). +_REF_BODY_TOKEN_RE = re.compile( + r"(?>||<\?.*?\?>)|((?i:<\s*(?:[\w.\-]+:)?Body[\s/>]))|.", + re.DOTALL, +) #: Text read lazily, each markup taken whole; atomic, so no backtrack lets a tag inside one match. _REF_TEXT = rf"(?:(?>{_REF_MARKUP}|.))*?" _REF_FAULT_TAG = r"(?i:<\s*(?:[\w.\-]+:)?Fault[\s/>])" @@ -112,11 +117,11 @@ def _ref_fault_tag_end(body: str) -> int | None: and, failing that, any (BACKLOG #5912).""" outside = [t.span(1) for t in _REF_TOKEN_RE.finditer(body) if t.group(1)] anywhere = [t.span() for t in _REF_FAULT_ANYWHERE_RE.finditer(body)] - in_body = _REF_BODY_RE.search(body) + in_body = next((t for t in _REF_BODY_TOKEN_RE.finditer(body) if t.group(1)), None) sides = ( [(0, len(body))] if in_body is None - else [(in_body.start(1), len(body)), (0, in_body.start())] + else [(in_body.end(1), len(body)), (0, in_body.start(1))] ) for low, high in sides: for spans in (outside, anywhere): @@ -136,7 +141,7 @@ def _ref_fault_code(body: str) -> str: fault_inner = _REF_FAULT_INNER_RE.match(body, fault_tag.end()) inner = "" if fault_inner is None else fault_inner.group(1) code = _ref_first_child_code(inner) - if code: + if code.strip(): return code plain_end = _REF_FAULT_CLOSE_ANYWHERE_RE.search(body, name_end) return _ref_searched_code( @@ -856,6 +861,7 @@ def test_the_fault_is_read_from_the_body( code, anywhere was read.""" assert _outcome(_classify_soap(200, body)) == outcome monkeypatch.setattr(soap, "_BODY_RE", _NO_BODY_ANCHOR) + monkeypatch.setattr(soap, "_BODY_OUTSIDE_MARKUP_RE", _NO_BODY_ANCHOR) assert _outcome(_classify_soap(200, body)) == unanchored @@ -940,6 +946,21 @@ def test_the_fault_is_read_from_the_body( "soap-sender", "soap-sender", ), + # BACKLOG #5912 closing step 24: with two Faults, each inside markup, the first is read. The + # pair holds the same two Faults in both orders, so a search that took any other one would + # read one of the two shapes otherwise. + "only-commented-faults-client-first": ( + "" + "", + "soap-sender", + "soap-sender", + ), + "only-commented-faults-server-first": ( + "" + "", + "transient", + "transient", + ), # The first Body start tag inside a comment: the markup it sits in is known after it, so the # Fault in the same comment is not the Body's. "body-tag-in-a-comment": ( @@ -993,6 +1014,8 @@ def test_a_fault_tag_inside_markup_does_not_decide_the_fault( monkeypatch.setattr(soap, "_FAULT_OUTSIDE_MARKUP_RE", soap._FAULT_RE) monkeypatch.setattr(soap, "_FAULT_END_OUTSIDE_MARKUP_RE", soap._FAULT_END_RE) monkeypatch.setattr(soap, "_CODE_END_OUTSIDE_MARKUP_RE", soap._CODE_END_RE) + # Head adfdcd5d31 took the first Body start tag inside markup or not (closing step 6). + monkeypatch.setattr(soap, "_BODY_OUTSIDE_MARKUP_RE", soap._BODY_RE) # Head adfdcd5d31 had no fallback to the earlier search, which may read such a shape too. monkeypatch.setattr(soap, "_searched_code", lambda body, start, end: "") assert _outcome(_classify_soap(200, body)) == unmarked diff --git a/tests/test_static_request_screen.py b/tests/test_static_request_screen.py index ebe81247e9..95213d13ee 100644 --- a/tests/test_static_request_screen.py +++ b/tests/test_static_request_screen.py @@ -119,11 +119,13 @@ def test_a_clean_token_url_passes_the_screen( assert provider._check_token_url("https://as.example.org/token", connection=None) == "https" -def test_a_refused_lookup_leaves_no_crossing_record_from_an_earlier_lookup( +def test_a_lookup_the_static_screen_refuses_runs_no_gate_for_an_earlier_lookup( monkeypatch: pytest.MonkeyPatch, ) -> None: - """Step 11: every lookup is screened before any is built, so the first lookup's hop gates - never run when the second is refused.""" + """Step 11: every lookup is screened before any is built, so the first lookup's proxy route + is never built when the second fails the static-request screen. Only that screen's refusal is + tested here; tests/test_fhir_lookup_gate_order.py covers a cleartext first lookup and the + other checks that run before any lookup is built (BACKLOG #8299 item 6).""" from messagefoundry.transports.rest import egress_route_from_settings as real built: list[str] = [] @@ -142,6 +144,15 @@ def _spy(*args: Any, **kwargs: Any) -> Any: egress=_OPEN, ) assert built == [] + # The control: with a second lookup the screen passes, both proxy routes are built. + FhirLookupExecutor( + { + "first": {"url": "https://fhir.example.org/fhir"}, + "second": {"url": "https://fhir.example.org/fhir/x"}, + }, + egress=_OPEN, + ) + assert built == ["fhir_lookup:first", "fhir_lookup:second"] @pytest.mark.parametrize("kind", [ConnectorType.REST, ConnectorType.SOAP]) diff --git a/tests/test_store_privilege_preflight.py b/tests/test_store_privilege_preflight.py index d3d4a6815b..161f5091a4 100644 --- a/tests/test_store_privilege_preflight.py +++ b/tests/test_store_privilege_preflight.py @@ -739,11 +739,16 @@ async def test_one_null_role_column_is_enough_to_stop_the_observation( store = _sqlserver_probe( monkeypatch, _probe_row(database_roles=_DOCUMENTED_SQLSERVER, unread=("db_owner",)), + # auto, where these three roles are the documented grant: nothing over-granted is read, so + # the report stays unobserved (owner ruling 2026-11-23 on #6015 item 1 keeps a READ + # over-grant, such as db_ddladmin under external, OBSERVED). + schema_management=SchemaManagement.AUTO, ) report = await store.probe_principal_privileges() assert report.status is StorePrivilegeStatus.UNOBSERVABLE assert "database role db_owner" in report.detail - assert "1 of 19 probed grant(s)" in report.detail + # BACKLOG #6015 item 6: the denominator says what it counts, since the probe reads more grants. + assert "1 of the 19 role and CONTROL grant(s) probed" in report.detail # What DID read is still reported: a partial read can only understate an over-grant, never invent one. assert set(_DOCUMENTED_SQLSERVER) <= set(report.database_roles) @@ -757,6 +762,7 @@ async def test_a_null_direct_permission_column_is_not_read_either( store = _sqlserver_probe( monkeypatch, _probe_row(database_roles=_DOCUMENTED_SQLSERVER, control_server=None), + schema_management=SchemaManagement.AUTO, # the documented grant: no over-grant read ) report = await store.probe_principal_privileges() assert report.status is StorePrivilegeStatus.UNOBSERVABLE @@ -767,15 +773,110 @@ async def test_a_partial_read_still_names_the_over_grant_it_did_see( monkeypatch: pytest.MonkeyPatch, ) -> None: """Losing a confirmed ``sysadmin`` because a NEIGHBOURING column was unreadable would trade one - false-clean for another. The read is incomplete AND the principal is a superuser; say both.""" + false-clean for another. The read is incomplete AND the principal is a superuser; say both. + + Owner ruling 2026-11-23 on BACKLOG #6015 item 1 ("Refuse when read"): this pin read + UNOBSERVABLE under #1234, which only warns under enforce. A read over-grant now keeps the + report OBSERVED with the over-grant in ``excess``, so it refuses under enforce, and the unread + column is still reported, in ``unread`` and the detail.""" store = _sqlserver_probe( monkeypatch, _probe_row(server_roles=("sysadmin",), unread=("db_owner",)), ) report = await store.probe_principal_privileges() - assert report.status is StorePrivilegeStatus.UNOBSERVABLE + assert report.status is StorePrivilegeStatus.OBSERVED assert report.server_roles == ("sysadmin",) - assert "what DID read as held: server role sysadmin" in report.detail + assert report.excess == ("server role sysadmin",) + assert report.unread == ("database role db_owner",) + assert "database role db_owner" in report.detail + assert "not read: database role db_owner" in report.summary() + + +@pytest.mark.parametrize( + ("server_roles", "database_roles", "control_db", "unread"), + [ + (("sysadmin",), (), 0, ("db_owner",)), + ((), ("db_datareader", "db_datawriter", "db_owner"), 0, ("sysadmin",)), + ((), ("db_datareader", "db_datawriter"), 1, ("sysadmin",)), + ], + ids=["sysadmin", "db_owner", "control-database"], +) +async def test_a_read_over_grant_refuses_under_enforce_beside_an_unread_role( + monkeypatch: pytest.MonkeyPatch, + server_roles: tuple[str, ...], + database_roles: tuple[str, ...], + control_db: int, + unread: tuple[str, ...], +) -> None: + """Owner ruling 2026-11-23 on BACKLOG #6015 item 1: a login READ as sysadmin or db_owner, or + holding a read CONTROL, is refused under enforce even when another role column is unread.""" + row = _probe_row( + server_roles=server_roles, + database_roles=database_roles, + control_db=control_db, + unread=unread, + ) + store = _sqlserver_probe(monkeypatch, row) + report = await store.probe_principal_privileges() + # The over-grant arm, not an unobserved one: OBSERVED, with the read over-grant in the excess. + assert report.status is StorePrivilegeStatus.OBSERVED + assert report.excess + with pytest.raises(StorePrivilegeError, match="BEYOND the documented least-privilege grant"): + await run_store_privilege_preflight(store, require_least_privilege=False, enforcing=True) + + +async def test_a_read_control_is_named_as_read_beside_an_unread_role( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A read CONTROL SERVER or database CONTROL was in the excess but missing from "what DID read + as held", so a refusing report's detail said "nothing" was read as held.""" + row = _probe_row( + database_roles=("db_datareader", "db_datawriter"), + control_server=1, + control_db=1, + unread=("sysadmin",), + ) + report = await _sqlserver_probe(monkeypatch, row).probe_principal_privileges() + assert report.status is StorePrivilegeStatus.OBSERVED + assert "control server" in report.excess + held = report.detail.split("what DID read as held:", 1)[1] + assert "nothing" not in held + assert "control server" in held + assert "CONTROL on database MessageFoundry" in held + + +def test_the_posture_keeps_the_unread_grants_of_an_over_granted_report() -> None: + """A report OBSERVED with unread grants hands them on: the registry's over-grant entry names + them, so it does not read as a complete observation.""" + report = StorePrivilegeReport( + backend=StoreBackend.SQLSERVER, + status=StorePrivilegeStatus.OBSERVED, + excess=("server role sysadmin",), + unread=("database role db_owner",), + ) + posture = report.posture() + assert posture.unread == ("database role db_owner",) + entry = _names(posture)["store_principal_over_granted"] + assert "not read" in entry + assert "database role db_owner" in entry + # The other direction: with nothing unread, the entry adds no such clause. + assert ( + "not read" + not in _names(_clean(("server role sysadmin",)).posture())["store_principal_over_granted"] + ) + + +async def test_an_unread_role_with_nothing_over_granted_read_still_only_warns( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The other direction of the ruling: with no over-grant read, the report stays UNOBSERVABLE, + which warns and starts under enforce.""" + row = _probe_row(database_roles=("db_datareader", "db_datawriter"), unread=("sysadmin",)) + store = _sqlserver_probe(monkeypatch, row) + report = await run_store_privilege_preflight( + store, require_least_privilege=False, enforcing=True + ) + assert report.status is StorePrivilegeStatus.UNOBSERVABLE async def test_a_null_read_refuses_under_a_declared_requirement( @@ -930,6 +1031,164 @@ async def test_sqlserver_an_unread_external_grant_never_softens_a_found_over_gra await run_store_privilege_preflight(store, require_least_privilege=False, enforcing=True) +async def test_an_over_grant_summary_names_the_external_grants_it_could_not_read( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """BACKLOG #6015 item 2: an unread external-only grant beside a found over-grant was named in + ``detail`` alone, so the log line and the alert, which carry the summary, said nothing of it.""" + row = _probe_row(database_roles=("db_datareader", "db_datawriter", "db_owner")) + row["create_table"] = None + store = _sqlserver_probe(monkeypatch, row) + report = await store.probe_principal_privileges() + assert report.status is StorePrivilegeStatus.OBSERVED + assert report.unread == ("create table on database MessageFoundry",) + assert "not read: create table on database MessageFoundry" in report.summary() + assert report.audit_detail()["unread"] == ["create table on database MessageFoundry"] + + +async def test_an_unobserved_report_carries_its_unread_grants_too( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An UNOBSERVABLE report names its unread grants in the structured field as well, on the + external-only path and on the fixed-role path.""" + row = _probe_row(database_roles=("db_datareader", "db_datawriter")) + row["create_table"] = None + report = await _sqlserver_probe(monkeypatch, row).probe_principal_privileges() + assert report.status is StorePrivilegeStatus.UNOBSERVABLE + assert report.unread == ("create table on database MessageFoundry",) + role_row = _probe_row(database_roles=("db_datareader", "db_datawriter"), unread=("db_owner",)) + report = await _sqlserver_probe(monkeypatch, role_row).probe_principal_privileges() + assert report.status is StorePrivilegeStatus.UNOBSERVABLE + assert report.unread == ("database role db_owner",) + + +def test_an_observed_report_cannot_be_clean_with_grants_unread() -> None: + """``finding`` reads only status and excess, so OBSERVED with nothing found and something unread + would classify as clean. The type refuses that shape rather than rely on each backend.""" + with pytest.raises(ValueError, match="unread"): + StorePrivilegeReport( + backend=StoreBackend.SQLSERVER, + status=StorePrivilegeStatus.OBSERVED, + unread=("create table on database MessageFoundry",), + ) + + +async def test_a_held_alter_on_an_unresolved_default_schema_is_still_named( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A NULL default schema beside a held ALTER gave an empty schema name, which the comparator + read as no grant: a false clean. It is named under the unresolved label instead.""" + row = _probe_row(database_roles=("db_datareader", "db_datawriter")) + row["default_schema"] = None + row["alter_schema"] = 1 + report = await _sqlserver_probe(monkeypatch, row).probe_principal_privileges() + assert report.status is StorePrivilegeStatus.OBSERVED + assert "ALTER on schema (unresolved default schema)" in report.excess + + +async def test_an_unread_alter_names_its_schema(monkeypatch: pytest.MonkeyPatch) -> None: + """The unread label names the schema, as the held label and the VIEW DEFINITION labels do.""" + row = _probe_row(database_roles=("db_datareader", "db_datawriter")) + row["alter_schema"] = None + report = await _sqlserver_probe(monkeypatch, row).probe_principal_privileges() + assert report.unread == ("ALTER on schema dbo",) + + +def test_a_report_with_nothing_unread_keeps_its_summary() -> None: + """The other direction: no unread grant adds no clause.""" + report = _clean(("database role db_owner",)) + assert report.unread == () + assert "not read" not in report.summary() + + +async def test_the_alter_schema_probe_quotes_the_default_schema( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """BACKLOG #6015 item 4: ``HAS_PERMS_BY_NAME`` parses its securable as a name, so the schema is + passed through ``QUOTENAME`` as the VIEW DEFINITION columns beside it already were.""" + store = _sqlserver_probe(monkeypatch, _probe_row(database_roles=_DOCUMENTED_SQLSERVER)) + seen: list[str] = [] + real = store._fetchone + + async def _capture(sql: str, params: tuple[Any, ...] = ()) -> dict[str, Any] | None: + seen.append(sql) + result: dict[str, Any] | None = await real(sql, params) + return result + + monkeypatch.setattr(store, "_fetchone", _capture) + await store.probe_principal_privileges() + assert ( + "HAS_PERMS_BY_NAME(QUOTENAME(SCHEMA_NAME()), N'SCHEMA', N'ALTER') AS alter_schema" + in (seen[0]) + ) + assert "HAS_PERMS_BY_NAME(SCHEMA_NAME()," not in seen[0] + + +async def test_an_incomplete_read_names_held_schema_ddl_rights_too( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """BACKLOG #6714 item 3: a held CREATE TABLE or ALTER on the schema beside an unread role is + named. Since the owner ruling of 2026-11-23 (#6015 item 1) both are read over-grants under + external, so they are named in the excess of an OBSERVED report; this asserts the excess, not + the detail's "what DID read as held" list.""" + row = _probe_row(database_roles=("db_datareader", "db_datawriter"), unread=("db_owner",)) + row["create_table"] = 1 + row["alter_schema"] = 1 + store = _sqlserver_probe(monkeypatch, row) + report = await store.probe_principal_privileges() + # Owner ruling 2026-11-23 (#6015 item 1): both rights are read over-grants under external, so + # the report is OBSERVED with them in the excess and the unread role named beside them. + assert report.status is StorePrivilegeStatus.OBSERVED + assert "create table on database MessageFoundry" in report.excess + assert "ALTER on schema dbo" in report.excess + assert report.unread == ("database role db_owner",) + + +async def test_an_incomplete_read_under_auto_does_not_list_schema_ddl_rights( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Under auto those rights are prescribed, so they are not listed as findings there.""" + row = _probe_row(database_roles=_DOCUMENTED_SQLSERVER, unread=("db_owner",)) + row["create_table"] = 1 + row["alter_schema"] = 1 + store = _sqlserver_probe(monkeypatch, row, schema_management=SchemaManagement.AUTO) + report = await store.probe_principal_privileges() + assert report.status is StorePrivilegeStatus.UNOBSERVABLE + assert "create table on database" not in report.detail + + +def test_db_securityadmin_suppresses_the_view_definition_line() -> None: + """BACKLOG #6714 item 2: ``db_securityadmin`` carries ``VIEW DEFINITION`` on the database, so + naming the role names the fix, as ``db_owner`` does; the line would restate one grant as two.""" + excess = sqlserver_excess( + server_roles=(), + database_roles=("db_datareader", "db_datawriter", "db_securityadmin"), + control_server=False, + control_database=False, + database="MessageFoundry", + external=True, + view_definition=("dbo",), + ) + assert excess == ("database role db_securityadmin",) + + +def test_probed_grant_lives_in_the_leaf_and_the_login_probe_calls_it( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """BACKLOG #6015 items 7 and 8: one rule, in the leaf both packages may import, so the store + probe and the partner-login probe cannot drift apart.""" + # This form, not `from messagefoundry import sqlserver_roles`: the server-DB path gate in + # test_serverdb_ci_coverage.py maps that form to the package root and fails. + import messagefoundry.sqlserver_roles as sqlserver_roles + from messagefoundry.transports import database + + assert probed_grant is sqlserver_roles.probed_grant + # Call-through, not a copy: a stub that reads every answer as held turns all-zero into findings. + monkeypatch.setattr(database, "probed_grant", lambda value: True) + reading = database.classify_login_roles((0,) * len(database._LOGIN_ROLE_PROBE_ROLES)) + assert reading.verdict is database.LoginRoleVerdict.OVER_GRANTED + + async def test_a_zero_read_is_a_real_negative_and_is_not_confused_with_a_null( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -1329,6 +1588,21 @@ async def test_posture_route_reports_an_observed_over_grant(engine: Engine) -> N assert "store_principal_over_granted" in switches +async def test_posture_route_reports_the_unread_grants_beside_an_over_grant(engine: Engine) -> None: + body = await _posture( + engine, + store_privilege=StorePrivilegePosture( + status=StorePrivilegeStatus.OBSERVED, + excess=("server role sysadmin",), + unread=("database role db_owner",), + ), + ) + # The view's shape is the web-console seam, so the signal rides the loosening entry's risk text. + risk = {e["switch"]: e["risk"] for e in body["loosenings"]}["store_principal_over_granted"] + assert "not read" in risk + assert "database role db_owner" in risk + + async def test_posture_route_reports_an_unobservable_probe(engine: Engine) -> None: body = await _posture( engine, diff --git a/tests/test_store_privilege_schema_split.py b/tests/test_store_privilege_schema_split.py index 2fdd625d40..5678e133ad 100644 --- a/tests/test_store_privilege_schema_split.py +++ b/tests/test_store_privilege_schema_split.py @@ -481,6 +481,8 @@ async def test_postgres_probe_with_no_current_schema_is_unobserved_under_externa report = await store.probe_principal_privileges() assert report.status is StorePrivilegeStatus.UNOBSERVABLE assert "not read" in report.detail + # BACKLOG #6015 item 2: the structured field names it as well. + assert report.unread == ("CREATE on the store's schema",) # --- the Postgres open path, through a fake connection ----------------------------------------- @@ -1246,6 +1248,11 @@ async def test_postgres_unread_audit_grants_never_soften_a_found_over_grant( assert report.status is StorePrivilegeStatus.OBSERVED assert report.excess == ("CREATE on schema mefor",) assert "audit-table grants read NULL" in report.detail + # BACKLOG #6015 item 5: probed_grant also leaves a non-boolean answer unread, and says so. + assert "or a value that is not true or false" in report.detail + # BACKLOG #6015 item 2: the unread grants reach the summary the log line and the alert carry. + assert "UPDATE on table audit_log" in report.unread + assert "not read: " in report.summary() def test_postgres_audit_probe_reads_every_assumable_role_and_column_updates() -> None: @@ -1723,21 +1730,26 @@ async def test_live_sqlserver_external_refuses_then_provisions_then_runs_row_onl "grant view definition", admin.run_in(db, f"GRANT VIEW DEFINITION ON SCHEMA::[dbo] TO [{login}]"), ) - store = await bounded( - sa, - "reopen with view definition", - SqlServerStore.open(runtime, cipher=cipher, audit_mac_key=cipher.audit_mac_key()), - ) + # BACKLOG #6714 item 5: the REVOKE runs however the reopen or the probe ends. try: - viewer = await bounded(sa, "probe with view definition", store.probe_principal_privileges()) + store = await bounded( + sa, + "reopen with view definition", + SqlServerStore.open(runtime, cipher=cipher, audit_mac_key=cipher.audit_mac_key()), + ) + try: + viewer = await bounded( + sa, "probe with view definition", store.probe_principal_privileges() + ) + finally: + await store.close() finally: - await store.close() + await bounded( + sa, + "revoke view definition", + admin.run_in(db, f"REVOKE VIEW DEFINITION ON SCHEMA::[dbo] FROM [{login}]"), + ) assert viewer.excess == (view_definition_grant("dbo"),), viewer.excess - await bounded( - sa, - "revoke view definition", - admin.run_in(db, f"REVOKE VIEW DEFINITION ON SCHEMA::[dbo] FROM [{login}]"), - ) await bounded( sa, "grant db_ddladmin", admin.run_in(db, f"ALTER ROLE db_ddladmin ADD MEMBER [{login}]") diff --git a/tests/test_transit_row_seal.py b/tests/test_transit_row_seal.py index de4768dc68..d46283d6e5 100644 --- a/tests/test_transit_row_seal.py +++ b/tests/test_transit_row_seal.py @@ -467,12 +467,13 @@ async def test_require_seal_for_write_names_each_cause() -> None: local_key, USER_KIND, unreadable, local_key.seal(USER_KIND, FIELDS), subject="u" ) - # A record's stored seal that is not text is Forged; a session's is a TypeError, as on main. + # A stored seal that is not text is Forged, a record's and a session's alike (BACKLOG #6718). blob: Any = stored.encode() with pytest.raises(RowSealError): await require_seal_for_write(sealer, USER_KIND, FIELDS, blob, subject=subject) - with pytest.raises(TypeError): + with pytest.raises(RowSealError) as blob_session: await require_seal_for_write(sealer, SESSION_KIND, FIELDS, blob, subject="s") + assert blob_session.value.args == (SESSION_KIND, "s") # A TypeError from a defect in the check itself is not a Forged row: it propagates. def broken_verify(key_name: str, digest: bytes, mac: str) -> bool: