From c1dbfb34193ef719e263cace84e9a25bd27126c7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:15:26 -0600 Subject: [PATCH 01/29] Store privilege probe: R2 added items for the shared probed_grant, unread grants in the summary, and db_securityadmin Builds the added items engine PR 2879 left on BACKLOG #6015 and #6714. - probed_grant moves to the leaf messagefoundry/sqlserver_roles.py; store/privilege.py re-exports it, sqlserver.py drops its one-line _probed_grant wrapper, and transports/database.py classify_login_roles calls it instead of repeating the rule (BACKLOG #6015 items 7, 8). - StorePrivilegeReport gains `unread`: an unread external-only grant beside a read over-grant now reaches summary() and the audit payload, not detail alone, on SQL Server and PostgreSQL (#6015 item 2). - The SQL Server alter_schema probe passes QUOTENAME(SCHEMA_NAME()), as the VIEW DEFINITION columns do (#6015 item 4). - The unread denominator says it counts role and CONTROL grants (#6015 item 6); the PostgreSQL unread wording names non-boolean answers (#6015 item 5); the probe docstrings say which unread grants stop the observation (#6015 item 3). - sqlserver_excess: db_securityadmin suppresses the VIEW DEFINITION line (#6714 item 2). - The early UNOBSERVABLE "what DID read as held" text names a held CREATE TABLE and ALTER on the schema under external (#6714 item 3). - docs/DEPLOY-SERVER-DB.md exit-3 bullet says which memberships hide the VIEW DEFINITION line (#6714 item 4); docs/CONFIGURATION.md fifo_claim_proc row scopes GRANT EXECUTE ON OBJECT:: (#6714 item 6); the live schema-split leg revokes VIEW DEFINITION in a finally (#6714 item 5). BACKLOG #6015, BACKLOG #6714, BACKLOG #6715 (not built: design). Proposed PR title: Store privilege probe: R2 added items for #6015 and #6714 (shared probed_grant, unread grants in the summary, db_securityadmin) Proposed banners: #6015 CLOSED: claim met by PR 2879; added items 2-8 built here; item 1 kept by design (the #1234 pin: an unread role or CONTROL grant makes the report UNOBSERVABLE even beside a read sysadmin). #6714 PARTIAL: added items 2-6 built here (item 1 by PR 2879); S01-68 reads met on main (owner_named counts CONTROL SERVER, and sysadmin alone among server roles). Left: a reviewed not-a-bug ruling on the headline (custom roles flagged by name, by design per DEPLOY-SERVER-DB.md 1.3, the Manager's reading). #6715 OPEN: nothing built. Left: per-process warning keys (a stable process identity for the bare `store` subject), a design item. --- docs/CONFIGURATION.md | 2 +- docs/DEPLOY-SERVER-DB.md | 7 +- messagefoundry/sqlserver_roles.py | 23 ++++- messagefoundry/store/postgres.py | 5 +- messagefoundry/store/privilege.py | 41 +++++--- messagefoundry/store/sqlserver.py | 68 ++++++------- messagefoundry/transports/database.py | 15 +-- tests/test_store_privilege_preflight.py | 107 ++++++++++++++++++++- tests/test_store_privilege_schema_split.py | 34 ++++--- 9 files changed, 228 insertions(+), 74 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5dc226a7e9..475ef53bc0 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -179,7 +179,7 @@ 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)). | diff --git a/docs/DEPLOY-SERVER-DB.md b/docs/DEPLOY-SERVER-DB.md index aa08e43ab9..63f3ba3b1f 100644 --- a/docs/DEPLOY-SERVER-DB.md +++ b/docs/DEPLOY-SERVER-DB.md @@ -178,8 +178,11 @@ 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. + schema, the database or the server, schema ownership, or a role or group membership. When it + names `db_owner`, `sysadmin`, `db_securityadmin`, database `CONTROL` or `CONTROL SERVER`, which + the gMSA must never hold either, it leaves out the `VIEW DEFINITION` line, since each of those + carries it; a `VIEW DEFINITION` held by another route as well shows on the next run. Remove + each grant it names 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. diff --git a/messagefoundry/sqlserver_roles.py b/messagefoundry/sqlserver_roles.py index b71173066b..8c3fd047bd 100644 --- a/messagefoundry/sqlserver_roles.py +++ b/messagefoundry/sqlserver_roles.py @@ -18,11 +18,13 @@ 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. """ 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 +50,22 @@ "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``. + + The store preflight (``store/privilege.py`` re-exports it) and the partner-login probe + (``transports/database.py`` ``classify_login_roles``) both call this one function.""" + if isinstance(value, int) and value in (0, 1): + return bool(value) + return None diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 979d5dc085..72500a9e55 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -3160,7 +3160,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" ) @@ -3184,6 +3185,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..29041b25fd 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,10 @@ class StorePrivilegeReport: database_roles: tuple[str, ...] = () excess: tuple[str, ...] = () detail: str = "" + #: Grants the probe could NOT read beside an OBSERVED over-grant (BACKLOG #6015 item 2). The + #: report stays OBSERVED, since what WAS read already refuses; the summary still names them, + #: so the log line and the alert do not imply the rest was read. + unread: tuple[str, ...] = () @property def finding(self) -> str | None: @@ -522,10 +518,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 +543,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 +556,18 @@ 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, three ways per grant: held, not held, + or not read (BACKLOG #6015 item 3). + + ``OBSERVED`` with an empty ``excess`` is a clean read. A grant that was not read is never + reported as not held: the report is ``UNOBSERVABLE``, or, for a grant the backend weighs + after an over-grant it did read, stays ``OBSERVED`` with that over-grant in ``excess`` and + the unread grant in ``unread``, so the start still refuses on what WAS read. + ``NOT_APPLICABLE`` is SQLite's, which has no principal. Each backend's method says which + grants it reads, which unread ones stop the observation, and which count under + ``[store].schema_management``.""" + ... class PrivilegeAlertSink(Protocol): diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index df2716391f..53cb4e557a 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -3556,21 +3556,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`.""" @@ -5192,15 +5177,22 @@ 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 makes the whole report :attr:`StorePrivilegeStatus.UNOBSERVABLE`, named grant + by grant in the detail, even beside a role read as held (#1234 pins that): 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. + + 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 start + still refuses on what was read.""" server_cols = [ f"IS_SRVROLEMEMBER(?) AS srv_{i}" for i in range(len(SQLSERVER_FIXED_SERVER_ROLES)) ] @@ -5220,7 +5212,8 @@ 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: the securable is parsed as a name, as the VIEW DEFINITION columns below say. + " 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')" @@ -5236,27 +5229,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 @@ -5264,10 +5257,10 @@ 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"]) + 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") # #6714: one column per distinct schema; when the default schema is dbo the two name one. @@ -5276,7 +5269,7 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: 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: @@ -5291,6 +5284,10 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: held_labels += [f"database role {r}" for r in database_roles] 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)) @@ -5307,7 +5304,8 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: database_roles=database_roles, 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:" @@ -5379,6 +5377,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 25634c95ae..3b2ee0a278 100644 --- a/messagefoundry/transports/database.py +++ b/messagefoundry/transports/database.py @@ -130,6 +130,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, @@ -5679,10 +5680,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 one function the + 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 @@ -5705,10 +5706,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/tests/test_store_privilege_preflight.py b/tests/test_store_privilege_preflight.py index d3d4a6815b..3edb79c544 100644 --- a/tests/test_store_privilege_preflight.py +++ b/tests/test_store_privilege_preflight.py @@ -743,7 +743,8 @@ async def test_one_null_role_column_is_enough_to_stop_the_observation( 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) @@ -930,6 +931,110 @@ 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"] + + +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: the early UNOBSERVABLE path listed held roles, audit-table rights and + VIEW DEFINITION as "what DID read as held", but not a held CREATE TABLE or ALTER on the schema.""" + 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() + assert report.status is StorePrivilegeStatus.UNOBSERVABLE + held = report.detail.split("what DID read as held:", 1)[1] + assert "create table on database MessageFoundry" in held + assert "ALTER on schema dbo" in held + + +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.""" + from messagefoundry import 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: diff --git a/tests/test_store_privilege_schema_split.py b/tests/test_store_privilege_schema_split.py index 2fdd625d40..b82bf60bda 100644 --- a/tests/test_store_privilege_schema_split.py +++ b/tests/test_store_privilege_schema_split.py @@ -1246,6 +1246,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 +1728,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}]") From b967d4fec3815d27167ef31abcd8d22a98d9cae3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:20:13 -0600 Subject: [PATCH 02/29] Row seal: Transit sealer refuses non-finite floats and reads a non-text seal as malformed The local sealer refused a NaN or an infinity at seal time and the Transit sealer sealed it; both now refuse through one in-encoder check, raising NonFiniteSealValueError (a ValueError subclass). The check runs only where a seal is made, so a check over such a row still fails rather than raises, and it no longer copies the fields or makes a second pass. TransitRowSealer._parse now reads a non-text stored seal as malformed, as RowSealer._parse does, so require_seal_for_write refuses a session row with one as Forged instead of raising TypeError. The encoded bytes are unchanged: tests/test_row_seal_followups.py pins a seal and a Transit digest read on origin/main d2ed8a8bd8. Prose: the -0.0 fact is stated once, in the module docstring; the false "keep their encodings" clause is gone. BACKLOG #6717, #6718 --- .../6717-row-seal-transit-non-finite.fixed.md | 5 + messagefoundry/store/row_seal.py | 68 +++++---- tests/test_row_seal.py | 8 +- tests/test_row_seal_followups.py | 132 ++++++++++++++++++ tests/test_transit_row_seal.py | 4 +- 5 files changed, 190 insertions(+), 27 deletions(-) create mode 100644 changelog.d/6717-row-seal-transit-non-finite.fixed.md create mode 100644 tests/test_row_seal_followups.py 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..6bb9e38b13 --- /dev/null +++ b/changelog.d/6717-row-seal-transit-non-finite.fixed.md @@ -0,0 +1,5 @@ +Row seals: the Vault Transit row sealer 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. +The Transit sealer reads a stored seal that is not text (a blob or a number) as malformed rather +than raising, so a write over such a session row is refused as a failed seal (BACKLOG #6717, +#6718). The bytes a seal covers are unchanged, so a seal written before this change still verifies. diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index 18832fb2bf..67621e4fef 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -32,7 +32,10 @@ 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. Making a seal, under either sealer, +raises :class:`NonFiniteSealValueError` for a float that is not finite, while checking a seal over +one fails rather than raises (BACKLOG #6717). """ from __future__ import annotations @@ -70,8 +73,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. @@ -119,6 +122,15 @@ _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``, 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. Its own type, so a caller can tell it from the ``ValueError`` a malformed field + pair raises when it is unpacked.""" + + class RowSealError(Exception): """Raised at least when a store write helper read a row whose seal does not verify, and refused the write. @@ -238,7 +250,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,8 +264,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. A check encodes a non-finite float as it is, so + # a row someone set to one fails its seal rather than raising from the check. out = [_part(_SCHEME), _part(kind.encode("utf-8"))] for name, value in fields: + if finite and isinstance(value, float) and not -_FLOAT_INF < value < _FLOAT_INF: + raise NonFiniteSealValueError("a row seal refuses a float that is not finite") type_byte, encoded = _encode_value(value) out.append(_part(name.encode("utf-8")) + type_byte + _part(encoded)) return b"".join(out) @@ -319,16 +339,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 +713,11 @@ 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 = False + ) -> 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 +732,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 +750,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: @@ -995,9 +1015,9 @@ 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. + if stored is not None and not isinstance(stored, str): + # A stored seal that is not text (a BLOB a writer put there) is no seal: Forged, as both + # sealers' checks read it (BACKLOG #6718). raise RowSealError(kind, subject) fields = list(fields) if kind != SESSION_KIND: diff --git a/tests/test_row_seal.py b/tests/test_row_seal.py index 92fccf6bf2..e98885d059 100644 --- a/tests/test_row_seal.py +++ b/tests/test_row_seal.py @@ -10,6 +10,7 @@ import base64 import contextlib +import math import sqlite3 from collections.abc import Callable from typing import Any @@ -181,7 +182,9 @@ def _through_sqlite_real(value: float) -> object: def test_a_negative_zero_seal_survives_a_sqlite_real_round_trip() -> None: # BACKLOG #6717. SQLite's REAL column reads -0.0 back as 0.0, so a seal over -0.0's own # encoding failed the next read as if the row had been changed. - back = _through_sqlite_real(-0.0) # 0.0 on SQLite 3.50; the check holds either way + back = _through_sqlite_real(-0.0) + # The premise: the round trip dropped the sign, so the old encoding would have failed here. + assert isinstance(back, float) and math.copysign(1.0, back) == 1.0 sealer = _sealer() stored = sealer.seal("session", (("revoked_at", -0.0),)) assert sealer.verify("session", (("revoked_at", back),), stored) @@ -200,6 +203,9 @@ def test_every_float_but_negative_zero_keeps_its_float_hex_encoding(value: float def test_negative_zero_encodes_as_zero_does() -> None: assert seal_bytes("k", [("f", -0.0)]) == seal_bytes("k", [("f", 0.0)]) + # Controls: the sign of any other float still counts, and so does the smallest step off zero. + assert seal_bytes("k", [("f", -1.5)]) != seal_bytes("k", [("f", 1.5)]) + assert seal_bytes("k", [("f", -5e-324)]) != seal_bytes("k", [("f", 0.0)]) @pytest.mark.parametrize("value", _NOT_FINITE) diff --git a/tests/test_row_seal_followups.py b/tests/test_row_seal_followups.py new file mode 100644 index 0000000000..c6402ad4ee --- /dev/null +++ b/tests/test_row_seal_followups.py @@ -0,0 +1,132 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""Row-seal follow-ups to BACKLOG #6717 and #6718: the non-finite refusal on both sealers, its own +error type, a non-text stored seal on the Transit sealer, and pins that a seal written before these +changes still verifies. Synthetic data only. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Callable +from dataclasses import asdict +from typing import Any + +import pytest + +from messagefoundry.store import row_seal +from messagefoundry.store.row_seal import SESSION_KIND, RowSealer, TransitRowSealer, seal_bytes +from messagefoundry.store.store import SessionRecord, session_seal_ok +from tests._transit_seal_fake import Clock, FakeBackend + +# Every type the encoder writes, and both zeros, so a change to any encoding moves a pin below. +_PINNED_FIELDS: tuple[tuple[str, object], ...] = ( + ("n", None), + ("b", True), + ("i", -7), + ("x", 1.5), + ("z", -0.0), + ("t", 5e-324), + ("s", "u1"), + ("y", b"\x00\xff"), +) +_PINNED_KEY = bytes(range(32)) +# Read on engine origin/main d2ed8a8bd8, before this branch: what main writes for the fields above. +_MAIN_SEAL = ( + "mfseal:v1:5bb5e8d61e093c73:9f6d72b1305e9a30042794e7ec47c723b83dc51111924ada8fe9c521738021ea" +) +_MAIN_SEAL_BYTES_SHA256 = "e7cc6743199bcdf9bb93bc39dda7971bc774de98df44307f01ef9fd4af6e2373" +_MAIN_TRANSIT_DIGEST = "27668a19875106906f750480d3be8b301fd25fad699aa7256c933e6b4e4c68a1" + +_NOT_FINITE = (float("nan"), float("inf"), float("-inf")) + + +def _transit() -> tuple[TransitRowSealer, FakeBackend]: + backend = FakeBackend() + return TransitRowSealer(backend, clock=Clock()), backend + + +def test_a_seal_main_wrote_still_verifies_and_is_written_again() -> None: + sealer = RowSealer(_PINNED_KEY) + assert sealer.verify(SESSION_KIND, _PINNED_FIELDS, _MAIN_SEAL) + assert sealer.seal(SESSION_KIND, _PINNED_FIELDS) == _MAIN_SEAL + digest = hashlib.sha256(seal_bytes(SESSION_KIND, _PINNED_FIELDS)).hexdigest() + assert digest == _MAIN_SEAL_BYTES_SHA256 + # Control: one changed field fails, so the pin is not a sealer that accepts everything. + assert not sealer.verify(SESSION_KIND, (*_PINNED_FIELDS[:-1], ("y", b"\x00")), _MAIN_SEAL) + + +def test_the_transit_digest_main_computed_is_unchanged() -> None: + sealer, _ = _transit() + assert sealer._digest(SESSION_KIND, _PINNED_FIELDS).hex() == _MAIN_TRANSIT_DIGEST + assert sealer._digest(SESSION_KIND, _PINNED_FIELDS[:-1]).hex() != _MAIN_TRANSIT_DIGEST + + +@pytest.mark.parametrize("value", _NOT_FINITE) +def test_the_non_finite_refusal_has_its_own_value_error(value: float) -> None: + # BACKLOG #6717 item 4: a malformed field tuple raises ValueError too; the refusal is told apart + # from it by type. + refused = row_seal.NonFiniteSealValueError + assert issubclass(refused, ValueError) + sealer = RowSealer(_PINNED_KEY) + with pytest.raises(refused): + sealer.seal(SESSION_KIND, (("expires_at", value),)) + malformed: Any = [("only-a-name",)] + with pytest.raises(ValueError) as unpack: + sealer.seal(SESSION_KIND, malformed) + assert not isinstance(unpack.value, refused) + + +@pytest.mark.parametrize("value", _NOT_FINITE) +async def test_the_transit_sealer_refuses_a_float_that_is_not_finite(value: float) -> None: + # BACKLOG #6717: the local sealer refused a NaN or an infinity, and the Transit sealer sealed it. + sealer, backend = _transit() + with pytest.raises(row_seal.NonFiniteSealValueError): + await sealer.seal_async(SESSION_KIND, (("expires_at", value),)) + assert backend.inputs == [] # nothing reached Transit + stored = await sealer.seal_async(SESSION_KIND, (("expires_at", 1.5),)) # control + assert await sealer.verify_async(SESSION_KIND, (("expires_at", 1.5),), stored) + # A row changed to such a value still fails rather than raises. + assert not await sealer.verify_async(SESSION_KIND, (("expires_at", value),), stored) + + +@pytest.mark.parametrize( + "as_type", + [lambda s: s.encode("ascii"), lambda s: bytearray(s, "ascii"), lambda s: 7, lambda s: 7.5], + ids=["bytes", "bytearray", "int", "float"], +) +async def test_a_transit_seal_that_is_not_text_fails_every_check_without_raising( + as_type: Callable[[str], Any], +) -> None: + # BACKLOG #6718 item 3: TransitRowSealer._parse called startswith on whatever the column held. + sealer, backend = _transit() + fields = (("token_hash", "ab" * 32), ("n", 3)) + stored = await sealer.seal_async(SESSION_KIND, fields) + assert sealer.is_active(stored) # controls: the text form holds + assert await sealer.verify_async(SESSION_KIND, fields, stored) + calls = backend.verify_calls + other = as_type(stored) + assert not sealer.is_active(other) + assert not await sealer.verify_async(SESSION_KIND, fields, other) + assert not await sealer.verify_held_async(SESSION_KIND, fields, other) + assert not await sealer.sealed_by_retired_key_async(SESSION_KIND, fields, other) + assert backend.verify_calls == calls # read as malformed, with no Transit call + + +def test_a_session_row_whose_seal_cell_is_not_text_fails_its_check() -> None: + # BACKLOG #6718 item 2: from_mapping hands a non-text seal cell through as it was read, and the + # check reads it as a malformed seal rather than raising. + sealer = RowSealer(_PINNED_KEY) + record = SessionRecord( + token_hash="ab" * 32, + user_id="u1", + created_at=1.0, + expires_at=2.0, + last_used_at=1.0, + revoked_at=None, + client=None, + ) + row = {**asdict(record), "seal": sealer.seal(SESSION_KIND, record.seal_fields())} + assert session_seal_ok(sealer, SessionRecord.from_mapping(row)) # control + for cell in (row["seal"].encode("ascii"), 7, 7.5): + assert not session_seal_ok(sealer, SessionRecord.from_mapping({**row, "seal": cell})) diff --git a/tests/test_transit_row_seal.py b/tests/test_transit_row_seal.py index de4768dc68..62c2bd1a2c 100644 --- a/tests/test_transit_row_seal.py +++ b/tests/test_transit_row_seal.py @@ -467,11 +467,11 @@ 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): await require_seal_for_write(sealer, SESSION_KIND, FIELDS, blob, subject="s") # A TypeError from a defect in the check itself is not a Forged row: it propagates. From 1cb90057b62dbf93c194ea95058b2f3786dda56d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:33:02 -0600 Subject: [PATCH 03/29] Transit key names: one read, checked at each use, refusal text kept (BACKLOG #6010, #6710) BACKLOG #6010 items 2-13 and #6710 item 3, the R2 items PR 2879 left. - keyprovider_vault: checked_transit_key_name says "ASCII letters" and scopes its redirect claim to a slash (item 5). Its refusal and the 32-byte DEK refusal are recorded (base._recorded), so the key seam's and build_store_cipher's fixed-text replacement keep them (#6010 item 3, #6710 item 3). transit_key_name_setting is the one read-then-check for the KEK and both Transit names (item 10). require_transit_key_type checks its name before read_key (item 9). _kek_name docstring and construction comment corrected (item 4). - crypto_transit: _key_names reads both names before refusing and names each bad variable in one refusal (item 7). TransitCipher checks both names (item 9). Fail-closed docstrings say "at least" and name a malformed name (item 8). - tls_policy: the twin CA comment no longer says an internal-CA Vault always fails closed; it names the ambient bundle variables (item 2). - docs/CONFIGURATION.md key_provider and cipher_provider rows: the key name shape and the 32-byte DEK rule (items 6, 11). - tests: _BAD_KEY_NAMES reuses _MALFORMED_KEK_NAMES (item 12); a test goes through build_store_cipher (item 13). Proposed PR title: Transit key names: one read, checked at each use, refusal text kept (BACKLOG #6010, #6710) Proposed banners: #6010 MET. The claim and item 1 were met by PR 2879; items 2 to 13 are met by this PR. #6710 PARTIAL. Item 3 met by this PR. Left: item 1 (cache, a decision owed; the event-loop cost is #5888), item 2 (wrapped retired DEKs, a design change), item 4 (shape check at base._checked_active_key, in store/base.py, which open PR 3164 edits). --- .../6010-transit-key-name-refusals.fixed.md | 7 +++ docs/CONFIGURATION.md | 4 +- messagefoundry/config/tls_policy.py | 10 ++- messagefoundry/store/crypto_transit.py | 63 +++++++++++++------ messagefoundry/store/keyprovider_vault.py | 56 +++++++++++++---- tests/test_crypto_transit.py | 56 ++++++++++++++++- tests/test_keyprovider_vault.py | 54 +++++++++++++++- 7 files changed, 209 insertions(+), 41 deletions(-) create mode 100644 changelog.d/6010-transit-key-name-refusals.fixed.md 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..8eb7d0cb73 --- /dev/null +++ b/changelog.d/6010-transit-key-name-refusals.fixed.md @@ -0,0 +1,7 @@ +- **A malformed Vault Transit key name is refused with its own text.** The refusals for + `MEFOR_STORE_VAULT_TRANSIT_KEY`, `MEFOR_STORE_TRANSIT_KEY` and `MEFOR_STORE_TRANSIT_AUDIT_KEY`, + the refusal of an unset `MEFOR_STORE_TRANSIT_KEY`, and the `vault` key provider's refusal of an unwrapped DEK that is not base64 of 32 bytes, 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 + and the Transit cipher itself now check the name too. (`BACKLOG #6010`, `BACKLOG #6710`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5dc226a7e9..4fee720229 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -186,8 +186,8 @@ backend-limited. | `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/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index 85236be0f0..2f7bdb26b8 100644 --- a/messagefoundry/config/tls_policy.py +++ b/messagefoundry/config/tls_policy.py @@ -3550,9 +3550,13 @@ 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, and only when it names none do they fall back to ``requests``' + PUBLIC certifi bundle, not the OS store; which variables they read is recorded once, at + ``store/keyprovider_vault.py``'s ``_ENV_CA_FILE``. So an internal-CA Vault fails closed unless + one of those variables names a bundle holding its CA, and then that bundle, whatever else it + holds, 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/store/crypto_transit.py b/messagefoundry/store/crypto_transit.py index 33cac4443a..282197f0b9 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,6 +91,7 @@ TRANSIT_KEY_TYPES_DATA, TRANSIT_MOUNT, _build_client, + _recorded_refusal, _vault_ca_kwargs, checked_transit_key_name, is_vault_bad_request, @@ -99,6 +100,7 @@ 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 +605,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 @@ -1418,20 +1426,35 @@ 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(str(exc)) + 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(str(exc)) + # Raised outside the handlers, so nothing a read held rides along on the chain (BACKLOG #2307). + # Each text is one this module or `checked_transit_key_name` built from a variable name alone, + # so it 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 +1466,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 +1565,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..de7948681c 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,49 @@ 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 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.""" + 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 _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." + 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 could change which " + f"Vault path a request reaches, and a name outside the shape Vault gives its key " + f"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/tests/test_crypto_transit.py b/tests/test_crypto_transit.py index 9d141efef9..25dd6d1b8e 100644 --- a/tests/test_crypto_transit.py +++ b/tests/test_crypto_transit.py @@ -37,6 +37,7 @@ from messagefoundry.store.keyprovider import KeyProviderError from messagefoundry.store.store import MessageStore from tests._vault_hop_env import STORE, supply_vault_hop +from tests.test_keyprovider_vault import _MALFORMED_KEK_NAMES ADT = "MSH|^~\\&|S|F|R|RF|20260101||ADT^A01|MSG1|P|2.5.1\rPID|1||100^^^H^MR||DOE^JANE\r" _KEY_NAME = "mefor-store" @@ -358,7 +359,9 @@ def read_key(self, *, name: str) -> dict[str, Any]: # --- both key names are checked before they reach a Transit path (BACKLOG #6010) ------------------ -_BAD_KEY_NAMES = ["a/../../../sys/x", "..", "mefor/store", "mefor-store/"] +#: The KEK test's cases (BACKLOG #6010 item 12): every Transit key name goes through one check, so +#: one list covers both modules, plus the two path-shaped names this module's tests began with. +_BAD_KEY_NAMES = [*_MALFORMED_KEK_NAMES, "mefor/store", "mefor-store/"] @pytest.mark.parametrize("bad", _BAD_KEY_NAMES) @@ -393,6 +396,57 @@ def test_a_dotted_hyphenated_key_name_still_builds(monkeypatch: pytest.MonkeyPat assert "transit/hmac/mefor_audit.v1" in crypto_transit.transit_cipher_required_capabilities() +@pytest.mark.parametrize("data_key", ["a/../../../sys/x", None]) +def test_one_refusal_names_every_bad_key_variable( + monkeypatch: pytest.MonkeyPatch, data_key: str | None +) -> None: + """BACKLOG #6010 item 7: both names are read before either refuses, as ``store_vault_hop`` + reads the address and token, so one refusal names each variable to fix: a malformed data key + or an unset one, beside a malformed audit key.""" + _use_fake(monkeypatch) + if data_key is None: + monkeypatch.delenv("MEFOR_STORE_TRANSIT_KEY") + else: + monkeypatch.setenv("MEFOR_STORE_TRANSIT_KEY", data_key) + monkeypatch.setenv("MEFOR_STORE_TRANSIT_AUDIT_KEY", "..") + for call in ( + lambda: build_transit_cipher(StoreSettings()), + crypto_transit.transit_cipher_required_capabilities, + ): + with pytest.raises(KeyProviderError) as excinfo: + call() + text = str(excinfo.value) + assert "MEFOR_STORE_TRANSIT_KEY " in text + assert "MEFOR_STORE_TRANSIT_AUDIT_KEY is not a Vault transit key name" in text + + +@pytest.mark.parametrize("bad", _BAD_KEY_NAMES) +@pytest.mark.parametrize("which", ["data", "audit"]) +def test_the_cipher_itself_refuses_a_malformed_key_name(which: str, bad: str) -> None: + """BACKLOG #6010 item 9: the cipher puts both names into request paths, so its constructor + checks them too, not only the environment read.""" + names = ("mefor-store", bad) if which == "audit" else (bad, None) + with pytest.raises(KeyProviderError, match="is not a Vault transit key name"): + TransitCipher(_FakeClient(_FakeTransit()), names[0], audit_key=names[1]) + + +@pytest.mark.parametrize("selector", ["MEFOR_STORE_TRANSIT_KEY", "MEFOR_STORE_TRANSIT_AUDIT_KEY"]) +def test_a_malformed_key_name_keeps_its_text_through_build_store_cipher( + monkeypatch: pytest.MonkeyPatch, selector: str +) -> None: + """BACKLOG #6010 items 3 and 13: ``build_store_cipher`` replaces a build error with fixed text + unless the engine recorded the refusal's own. The name refusal is recorded, so the text that + reaches the operator still names the variable, including ``MEFOR_STORE_TRANSIT_AUDIT_KEY``, + which the fixed text does not mention.""" + _use_fake(monkeypatch) + monkeypatch.setenv(selector, "a/../../../sys/x") + with pytest.raises(KeyProviderError) as excinfo: + build_store_cipher(StoreSettings(cipher_provider="vault_transit")) + text = str(excinfo.value) + assert f"{selector} is not a Vault transit key name" in text + assert "a/../../../sys/x" not in text + + # --- the operator-chosen key TYPE is checked at startup (BACKLOG #1166, ASVS 11.2.3) -------------- # # Owner ruling 2026-08-22: "check the type the product already fetches against what each of the three diff --git a/tests/test_keyprovider_vault.py b/tests/test_keyprovider_vault.py index 210fe3caad..c93e6a2091 100644 --- a/tests/test_keyprovider_vault.py +++ b/tests/test_keyprovider_vault.py @@ -342,6 +342,52 @@ def test_a_kek_name_changed_after_construction_is_checked_again( assert transit.read_calls == [] and transit.calls == [] +def test_the_name_refusal_says_ascii_and_scopes_its_redirect_claim( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """BACKLOG #6010 item 5: the shape is ASCII, as Go's ``\\w`` is, so the text says so; and only + a slash can move the request path, so the text does not say every refused name could.""" + monkeypatch.setenv("MEFOR_STORE_VAULT_TRANSIT_KEY", "kék") + with pytest.raises(KeyProviderError) as excinfo: + keyprovider_vault.kek_required_capabilities() + text = str(excinfo.value) + assert "ASCII letters" in text + assert "Any other name could change which Vault path" not in text + + +@pytest.mark.parametrize("name", _MALFORMED_KEK_NAMES) +def test_the_key_type_check_refuses_a_malformed_name_before_reading_it(name: str) -> None: + """BACKLOG #6010 item 9: ``require_transit_key_type`` puts its name into a request path, so it + checks the name itself rather than trust each caller to have read it through the check.""" + transit = _FakeTransit(KEY_A) + with pytest.raises(KeyProviderError, match="SOME_SELECTOR is not a Vault transit key name"): + keyprovider_vault.require_transit_key_type( + _FakeClient(transit), + name, + allowed=keyprovider_vault.TRANSIT_KEY_TYPES_KEK, + use="a test", + selector="SOME_SELECTOR", + ) + assert transit.read_calls == [] + + +def test_a_malformed_kek_name_keeps_its_text_at_the_key_seam( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """BACKLOG #6010 item 3: the key seam replaces a provider's error with fixed text unless the + engine recorded the refusal's own text. The name refusal is recorded, so the operator still + reads which variable to fix rather than "the key source failed".""" + from messagefoundry.store.base import resolve_active_key + + _configure_env(monkeypatch) + monkeypatch.setenv("MEFOR_STORE_VAULT_TRANSIT_KEY", "a/../../../sys/x") + with pytest.raises(KeyProviderError) as excinfo: + resolve_active_key(StoreSettings(key_provider="vault")) + text = str(excinfo.value) + assert "MEFOR_STORE_VAULT_TRANSIT_KEY is not a Vault transit key name" in text + assert "a/../../../sys/x" not in text + + @pytest.mark.parametrize("name", ["mefor-store-kek", "kek.v2", "K_1", "a", "a.b-c_d"]) def test_a_well_formed_kek_name_unwraps_and_names_the_probe_paths( monkeypatch: pytest.MonkeyPatch, name: str @@ -388,14 +434,16 @@ def test_a_plaintext_that_is_not_base64_of_32_bytes_refuses( def test_a_misshapen_dek_refuses_at_the_key_seam(monkeypatch: pytest.MonkeyPatch) -> None: """Before this check ``resolve_active_key`` returned a misshapen DEK unjudged, and only a later - decode refused it. Now the seam refuses it, with its fixed text for a key source that failed, - which names the setting to check and no key material.""" + decode refused it. Now the seam refuses it, with the provider's own text, which the engine + recorded when it built the refusal, so the seam's fixed-text replacement keeps it (BACKLOG + #6710 item 3). It names the variable to fix and holds no key material.""" from messagefoundry.store.base import resolve_active_key plaintext = _NOT_A_32_BYTE_KEY[0] _provider_on(monkeypatch, _FakeTransit(plaintext)) - with pytest.raises(KeyProviderError, match=r"check \[store\]\.key_provider") as excinfo: + with pytest.raises(KeyProviderError, match="not base64 of 32 bytes") as excinfo: resolve_active_key(StoreSettings(key_provider="vault")) + assert "MEFOR_STORE_VAULT_WRAPPED_DEK" in str(excinfo.value) assert plaintext not in str(excinfo.value) From ed13b4237d008ea77ee4de3ff325b092012a7f95 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:37:23 -0600 Subject: [PATCH 04/29] FhirLookup checks its pure settings before any hop gate; FHIR refuses dropped static credentials FhirLookupExecutor settles every lookup's url and header screens, length limits, timeout and hop declarations in _planned, for every lookup, before any lookup reaches a hop gate. A length refusal names the lookup. The cleartext bearer check runs before the SMART provider is built. The FHIR destination and FhirLookup refuse a non-table headers, a lone Basic half, a ':' in basic_user and bearer_token beside Basic, through REST's _refuse_unsendable_static_auth, now taking a transport label. Comments on the FHIR destination and REST that claimed no crossing for a connection that never builds now claim it for a build this check refuses. CONNECTIONS.md FHIR rows name the build-time refusals. Red first: 13 new tests fail with origin/main's fhir.py and rest.py. BACKLOG #8299 (items 1 part, 2, 3, 4, 6, 8, 9), BACKLOG #5911 (step 6). Proposed PR title: FHIR lookup gate order and static credential refusals (BACKLOG #8299, #5911) Proposed banner #8299: PARTIAL: items 2, 3, 4, 6, 8, 9 built, item 1 for fhir.py and rest.py. Left: item 1 soap.py and the refuse_http_digest_conflicts docstring; item 5 (needs http_auth.py docstring); item 7 residual; items 10-25. Proposed banner #5911: MET: step 6 settings-row text added; changelog fragment already on main; steps 3-5 and 7-11 as PR 3144 states. --- .../8299-fhir-lookup-gate-order.fixed.md | 10 + docs/CONNECTIONS.md | 8 +- messagefoundry/transports/fhir.py | 150 +++++++----- messagefoundry/transports/rest.py | 21 +- tests/test_digest_refusal_classification.py | 16 +- tests/test_fhir_lookup_gate_order.py | 216 ++++++++++++++++++ tests/test_static_request_screen.py | 17 +- 7 files changed, 364 insertions(+), 74 deletions(-) create mode 100644 changelog.d/8299-fhir-lookup-gate-order.fixed.md create mode 100644 tests/test_fhir_lookup_gate_order.py 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..b3fab6f08b --- /dev/null +++ b/changelog.d/8299-fhir-lookup-gate-order.fixed.md @@ -0,0 +1,10 @@ +- **A `FhirLookup` refused for a setting no longer leaves a crossing record from another lookup + first, in at least these cases.** Its url and header screens, its length limits, 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; each used to build and send no headers, no Basic credential, or Basic in place of the + bearer. (`BACKLOG #8299`) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 4ed3917db1..ab2f6e91c9 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -3443,18 +3443,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: 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) | diff --git a/messagefoundry/transports/fhir.py b/messagefoundry/transports/fhir.py index c7004342f9..d245652f64 100644 --- a/messagefoundry/transports/fhir.py +++ b/messagefoundry/transports/fhir.py @@ -118,6 +118,7 @@ _no_redirect_opener, _query_credentials_sent, _redact_url, + _refuse_unsendable_static_auth, _shared_no_redirect_opener, assert_probe_hop, auth_challenge_refused, @@ -858,6 +859,20 @@ 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 a static ``headers`` or credential ``_build_headers`` would drop or + replace without a word (BACKLOG #8299 item 8): a ``headers`` that is not a table, one Basic half + without the other, and ``bearer_token`` beside a Basic pair. The credential rules are REST's, + :func:`~messagefoundry.transports.rest._refuse_unsendable_static_auth`. Names settings, never a + value.""" + extra = s.get("headers") + if extra and not isinstance(extra, Mapping): + raise ValueError(f"{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). @@ -1094,13 +1109,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": @@ -1211,7 +1227,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") @@ -1394,7 +1410,7 @@ def _build_headers(self, s: dict[str, Any]) -> dict[str, str]: media = "application/fhir+json" # format is constrained to json in __init__ (XML deferred) headers: dict[str, str] = {"Content-Type": media, "Accept": media} extra = s.get("headers") or {} - if isinstance(extra, dict): + if isinstance(extra, Mapping): headers.update({str(k): str(v) for k, v in extra.items()}) token = s.get("bearer_token") if token: @@ -1989,6 +2005,18 @@ def _mint_bearer(token: Any, prefix: str) -> str: return bearer +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 + + class FhirLookupExecutor: """GET-only executor for handler-callable **live** FHIR reads (``fhir_lookup``, ADR 0043). @@ -2032,15 +2060,17 @@ 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: every check that needs no I/O and logs nothing runs + # for every lookup before any lookup is built, so a lookup one of them refuses leaves no + # hop-gate crossing record (#5529), from itself or from a lookup built before it. A refusal + # later in the loop below 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] = {} @@ -2060,33 +2090,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( @@ -2100,13 +2110,17 @@ 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: the static url and headers were bounded in _planned; the pre-emptive + # Proxy-Authorization above is bounded here, before this lookup's other gates. The + # proxy route's own gate has already run, so this refusal can follow its record. + try: + enforce_outbound_length_limits(url, headers) + except ValueError as exc: + raise ValueError(f"FhirLookup {cname!r}: {exc}") from exc # 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, @@ -2120,6 +2134,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( @@ -2130,10 +2149,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): @@ -2190,10 +2205,10 @@ 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 the lookup's checks that need no I/O and log nothing 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. #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: @@ -2208,9 +2223,38 @@ 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'") + _refuse_unsendable_static_headers(s, setting=f"FhirLookup {cname!r}", connection=None) 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}", + ) + # #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: + # 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) + 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) + _check_revocation_attestation(*revocation_attestation_from_settings(s)[:2]) + 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) @staticmethod def _build_headers(s: Mapping[str, Any]) -> dict[str, str]: @@ -2219,7 +2263,7 @@ def _build_headers(s: Mapping[str, Any]) -> dict[str, str]: media = "application/fhir+json" headers: dict[str, str] = {"Accept": media} extra = s.get("headers") or {} - if isinstance(extra, dict): + if isinstance(extra, Mapping): headers.update({str(k): str(v) for k, v in extra.items()}) token = s.get("bearer_token") if token: diff --git a/messagefoundry/transports/rest.py b/messagefoundry/transports/rest.py index 6cd79753ab..c1ad263d79 100644 --- a/messagefoundry/transports/rest.py +++ b/messagefoundry/transports/rest.py @@ -2909,9 +2909,12 @@ 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 @@ -2923,17 +2926,17 @@ def _refuse_unsendable_static_auth(s: Mapping[str, Any], *, connection: str | No 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" ) @@ -2994,8 +2997,8 @@ 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_http_digest_conflicts, @@ -3016,7 +3019,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( diff --git a/tests/test_digest_refusal_classification.py b/tests/test_digest_refusal_classification.py index 3c0c5af937..ef02b8f2b2 100644 --- a/tests/test_digest_refusal_classification.py +++ b/tests/test_digest_refusal_classification.py @@ -1036,8 +1036,10 @@ def test_an_accepted_proxy_credential_crossing_is_still_recorded( } -def _digest_proxied_lookup(**token: object) -> FhirLookupExecutor: - settings = {"url": "http://fhir.partner.invalid/fhir", **_DIGEST_PROXY_SETTINGS, **token} +def _digest_proxied_lookup( + token: dict[str, object], *, url: str = "http://fhir.partner.invalid/fhir" +) -> FhirLookupExecutor: + settings = {"url": url, **_DIGEST_PROXY_SETTINGS, **token} with active_hop_posture(_WARN_DIAL): return FhirLookupExecutor({"epic": settings}, egress=permitting(settings)) @@ -1054,7 +1056,7 @@ def _smart_settings(private_key: str) -> dict[str, object]: @pytest.mark.usefixtures("no_bypass") def test_a_fhir_lookup_with_oauth2_settings_behind_a_digest_proxy_builds() -> None: - ex = _digest_proxied_lookup(**_OAUTH2_SETTINGS) + ex = _digest_proxied_lookup(_OAUTH2_SETTINGS) assert ex._token["epic"] is None @@ -1063,11 +1065,15 @@ def test_a_fhir_lookup_with_smart_and_oauth2_settings_is_refused_by_its_smart_pr ec_pem: str, ) -> None: """THE CONTROL, as on main: a FhirLookup builds its SMART provider whatever OAuth2 settings sit - beside it, and that provider refuses the Digest proxy when it is built.""" + beside it, and that provider refuses the Digest proxy when it is built. The read hop is + loopback, because a cleartext read off this machine now refuses the SMART bearer before the + provider is built (BACKLOG #8299 item 4).""" from messagefoundry.transports.smart import SmartAuthError with pytest.raises(SmartAuthError, match=_DIGEST_PROXY_REFUSED): - _digest_proxied_lookup(**_smart_settings(ec_pem), **_OAUTH2_SETTINGS) + _digest_proxied_lookup( + {**_smart_settings(ec_pem), **_OAUTH2_SETTINGS}, url="http://127.0.0.1:9/fhir" + ) @pytest.mark.usefixtures("no_bypass") diff --git a/tests/test_fhir_lookup_gate_order.py b/tests/test_fhir_lookup_gate_order.py new file mode 100644 index 0000000000..23a5d903bc --- /dev/null +++ b/tests/test_fhir_lookup_gate_order.py @@ -0,0 +1,216 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""BACKLOG #8299 items 2, 3, 4, 6, 8 and 9: the order of the FhirLookupExecutor's checks and gates. + +A check that needs no I/O and logs nothing runs for every lookup before any lookup reaches a hop +gate, so a lookup it refuses leaves no crossing record, from itself or from a lookup built before +it. Synthetic values only. +""" + +from __future__ import annotations + +import logging +from collections.abc import Iterator +from typing import Any + +import pytest + +from messagefoundry.config.models import ConnectorType, Destination +from messagefoundry.config.settings import EgressSettings +from messagefoundry.config.tls_policy import HopPosture, active_hop_posture +from messagefoundry.transports import build_destination +from messagefoundry.transports import fhir as fhir_mod +from messagefoundry.transports import smart as smart_mod +from messagefoundry.transports.fhir import FhirLookupExecutor + +_OPEN = EgressSettings(deny_by_default=False) +_WARN_DIAL = HopPosture(enforcing=False) + +#: A cleartext lookup off this machine whose acceptance is declared: under a non-enforcing posture +#: its hop gate WARNs, naming the host, which is the crossing record these tests look for. +_FIRST = { + "url": "http://first.partner.invalid/fhir", + "cleartext_accepted": True, + "cleartext_reason": "synthetic test peer has no TLS", +} +_SECOND_OK = {"url": "https://second.partner.invalid/fhir"} + +_GATES = ( + "egress_route_from_settings", + "refuse_cleartext_credentials", + "refuse_cleartext_egress", + "refuse_verify_off", + "refuse_unrevoked_verified_hop", +) + + +@pytest.fixture +def gates(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[tuple[str, str]]]: + """Every hop-gate call the executor makes, as ``(gate, connection)``, in order.""" + calls: list[tuple[str, str]] = [] + + def spy(name: str, real: Any) -> Any: + def wrapper(*args: Any, **kwargs: Any) -> Any: + calls.append((name, str(kwargs.get("connection")))) + return real(*args, **kwargs) + + return wrapper + + for name in _GATES: + monkeypatch.setattr(fhir_mod, name, spy(name, getattr(fhir_mod, name))) + real_token = smart_mod.token_provider_from_settings + + def token_spy(s: Any, **kwargs: Any) -> Any: + calls.append(("token_provider_from_settings", "")) + return real_token(s, **kwargs) + + monkeypatch.setattr(smart_mod, "token_provider_from_settings", token_spy) + yield calls + + +def _build(connections: dict[str, dict[str, Any]]) -> FhirLookupExecutor: + with active_hop_posture(_WARN_DIAL): + return FhirLookupExecutor(connections, egress=_OPEN) + + +def _crossed(caplog: pytest.LogCaptureFixture, host: str) -> list[str]: + return [ + r.getMessage() + for r in caplog.records + if r.levelno >= logging.WARNING and host in r.getMessage() + ] + + +def test_the_control_an_accepted_cleartext_lookup_records_its_crossing( + gates: list[tuple[str, str]], caplog: pytest.LogCaptureFixture +) -> None: + """THE CONTROL for every test below: the instrument sees a crossing when one is made.""" + caplog.set_level(logging.WARNING) + ex = _build({"first": dict(_FIRST), "second": dict(_SECOND_OK)}) + assert ex.connections == {"first", "second"} + assert _crossed(caplog, "first.partner.invalid") + assert ("refuse_cleartext_egress", "fhir_lookup:first") in gates + + +@pytest.mark.parametrize( + "bad", + [ + {"url": "https://second.partner.invalid/fhir x"}, # the static-request screen + {"url": "https://second.partner.invalid/fhir", "timeout_seconds": 0}, + { + "url": "https://second.partner.invalid/fhir", + "cleartext_accepted": True, # an acceptance with no reason + }, + {"url": "https://second.partner.invalid/fhir", "headers": {"X-Pad": "a" * 9000}}, + ], + ids=["screen", "timeout", "acceptance-pair", "over-length"], +) +def test_a_lookup_refused_by_a_pure_check_leaves_no_crossing_from_an_earlier_lookup( + gates: list[tuple[str, str]], caplog: pytest.LogCaptureFixture, bad: dict[str, Any] +) -> None: + """Items 2, 3 and 6: the first lookup crosses in cleartext, the second fails a check that + needs no I/O, so no gate runs for either and nothing is recorded.""" + caplog.set_level(logging.WARNING) + with pytest.raises(ValueError, match="FhirLookup 'second'"): + _build({"first": dict(_FIRST), "second": bad}) + assert gates == [] + assert _crossed(caplog, "first.partner.invalid") == [] + + +def test_an_over_length_lookup_is_refused_before_its_own_gates_and_named( + gates: list[tuple[str, str]], +) -> None: + """Items 2 and 9: the length refusal names the lookup and runs before its hop gates.""" + with pytest.raises(ValueError, match=r"^FhirLookup 'big': outbound header 'X-Pad'"): + _build( + {"big": {"url": "https://big.partner.invalid/fhir", "headers": {"X-Pad": "a" * 9000}}} + ) + assert gates == [] + + +def test_the_static_credential_check_runs_before_the_token_provider_is_built( + gates: list[tuple[str, str]], +) -> None: + """Item 4: a SMART lookup over cleartext http is refused for its bearer before the provider + (and its token hop's gates) is built.""" + settings = { + "url": "http://fhir.partner.invalid/fhir", + "smart_token_url": "https://auth.partner.invalid/token", + "smart_client_id": "cid", + "smart_private_key": "not-a-key-and-never-read", + } + with pytest.raises(ValueError, match="cleartext"): + _build({"smart": settings}) + names = [name for name, _ in gates] + assert "token_provider_from_settings" not in names + assert "refuse_cleartext_credentials" in names + + +@pytest.mark.parametrize( + ("over", "match"), + [ + ({"headers": ["X-Site", "1"]}, "'headers' must be a table"), + ({"basic_user": "u"}, "basic_user and basic_password must be set together"), + ({"basic_password": "p"}, "basic_user and basic_password must be set together"), + ( + {"basic_user": "u", "basic_password": "p", "bearer_token": "t"}, + "both bearer_token and basic_user", + ), + ], + ids=["headers-list", "user-only", "password-only", "bearer-and-basic"], +) +def test_a_static_credential_the_lookup_would_drop_is_refused( + over: dict[str, Any], match: str +) -> None: + """Item 8: these used to build, and the lookup sent no headers, no Basic credential, or Basic + in place of the bearer, without a word.""" + with pytest.raises(ValueError, match=match) as ei: + _build({"epic": {"url": "https://fhir.partner.invalid/fhir", **over}}) + assert "FhirLookup 'epic'" in str(ei.value) or "fhir_lookup:epic" in str(ei.value) + + +@pytest.mark.parametrize( + "over", + [ + {"headers": {"X-Site": "1"}}, + {"basic_user": "u", "basic_password": "p"}, + {"bearer_token": "t"}, + ], + ids=["headers-table", "basic-pair", "bearer"], +) +def test_the_control_a_whole_static_credential_still_builds(over: dict[str, Any]) -> None: + ex = _build({"epic": {"url": "https://fhir.partner.invalid/fhir", **over}}) + assert ex.connections == {"epic"} + + +def _destination(**over: Any) -> object: + settings = {"url": "https://fhir.partner.invalid/fhir", **over} + return build_destination( + Destination(name="OB_FHIR", type=ConnectorType.FHIR, settings=settings), egress=_OPEN + ) + + +@pytest.mark.parametrize( + ("over", "match"), + [ + ({"headers": ["X-Site", "1"]}, "'headers' must be a table"), + ({"basic_user": "u"}, "basic_user and basic_password must be set together"), + ({"basic_password": "p"}, "basic_user and basic_password must be set together"), + ( + {"basic_user": "u", "basic_password": "p", "bearer_token": "t"}, + "both bearer_token and basic_user", + ), + ], + ids=["headers-list", "user-only", "password-only", "bearer-and-basic"], +) +def test_the_fhir_destination_refuses_the_same_dropped_credentials( + over: dict[str, Any], match: str +) -> None: + """Item 8, on the destination's own copy of ``_build_headers``.""" + with pytest.raises(ValueError, match=match) as ei: + _destination(**over) + assert "FHIR destination" in str(ei.value) + + +def test_the_control_the_fhir_destination_still_builds_a_whole_credential() -> None: + assert _destination(basic_user="u", basic_password="p", headers={"X-Site": "1"}) 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]) From 2768ad7cbba6f595725ab12f5c64a866060ed1bc Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:42:41 -0600 Subject: [PATCH 05/29] Store privilege probe: review round 1 on the R2 added items - StorePrivilegeReport.unread is filled on UNOBSERVABLE reports too (SQL Server's fixed-role and external-only paths, PostgreSQL's audit path), and the type refuses OBSERVED with unread grants and an empty excess, which `finding` would read as clean. - A held ALTER on a NULL default schema is named under the unresolved-schema label instead of an empty name the comparator dropped; the unread ALTER label names its schema. - The protocol docstring no longer claims every backend reads every grant three ways; it names the SQL Server enumeration that notes its failure in detail only. - probed_grant's docstrings say PostgreSQL reads with it too. - docs/DEPLOY-SERVER-DB.md exit-3 bullet says which memberships hide which lines, and that the output can list grants it could not read. BACKLOG #6015, BACKLOG #6714. Proposed PR title: Store privilege probe: R2 added items for #6015 and #6714 (shared probed_grant, unread grants in the summary, db_securityadmin) Proposed banners: #6015 CLOSED: claim met by PR 2879; added items 2-8 built on branch w10-privilege; item 1 kept by design (the #1234 pin: an unread role or CONTROL grant makes the report UNOBSERVABLE even beside a read sysadmin). #6714 PARTIAL: added items 2-6 built on branch w10-privilege (item 1 by PR 2879); S01-68 reads met on main (owner_named counts CONTROL SERVER, and sysadmin alone among server roles). Left: a reviewed not-a-bug ruling on the headline (custom roles flagged by name, by design per DEPLOY-SERVER-DB.md 1.3, the Manager's reading). #6715 OPEN: nothing built. Left: per-process warning keys (a stable process identity for the bare `store` subject), a design item. --- docs/DEPLOY-SERVER-DB.md | 11 +++--- messagefoundry/sqlserver_roles.py | 8 +++-- messagefoundry/store/postgres.py | 1 + messagefoundry/store/privilege.py | 32 ++++++++++------- messagefoundry/store/sqlserver.py | 9 +++-- tests/test_store_privilege_preflight.py | 48 +++++++++++++++++++++++++ 6 files changed, 85 insertions(+), 24 deletions(-) diff --git a/docs/DEPLOY-SERVER-DB.md b/docs/DEPLOY-SERVER-DB.md index 63f3ba3b1f..f086318478 100644 --- a/docs/DEPLOY-SERVER-DB.md +++ b/docs/DEPLOY-SERVER-DB.md @@ -178,11 +178,12 @@ 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. When it - names `db_owner`, `sysadmin`, `db_securityadmin`, database `CONTROL` or `CONTROL SERVER`, which - the gMSA must never hold either, it leaves out the `VIEW DEFINITION` line, since each of those - carries it; a `VIEW DEFINITION` held by another route as well shows on the next run. Remove - each grant it names and run the check again. + schema, the database or the server, schema ownership, or a role or group membership. A named + membership 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, until it exits 0. - 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. diff --git a/messagefoundry/sqlserver_roles.py b/messagefoundry/sqlserver_roles.py index 8c3fd047bd..f35d22b040 100644 --- a/messagefoundry/sqlserver_roles.py +++ b/messagefoundry/sqlserver_roles.py @@ -19,7 +19,8 @@ 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. +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. """ from __future__ import annotations @@ -64,8 +65,9 @@ def probed_grant(value: object) -> bool | None: 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``. - The store preflight (``store/privilege.py`` re-exports it) and the partner-login probe - (``transports/database.py`` ``classify_login_roles``) both call this one function.""" + Callers include the store preflight of both server backends (``store/privilege.py`` + re-exports it) 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/postgres.py b/messagefoundry/store/postgres.py index 72500a9e55..571cc514ec 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -3171,6 +3171,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 diff --git a/messagefoundry/store/privilege.py b/messagefoundry/store/privilege.py index 29041b25fd..3ea92abc30 100644 --- a/messagefoundry/store/privilege.py +++ b/messagefoundry/store/privilege.py @@ -481,11 +481,18 @@ class StorePrivilegeReport: database_roles: tuple[str, ...] = () excess: tuple[str, ...] = () detail: str = "" - #: Grants the probe could NOT read beside an OBSERVED over-grant (BACKLOG #6015 item 2). The - #: report stays OBSERVED, since what WAS read already refuses; the summary still names them, - #: so the log line and the alert do not imply the rest was read. + #: Grants the probe could NOT read (BACKLOG #6015 item 2), on an UNOBSERVABLE report and on an + #: OBSERVED one that already found an over-grant. There the report stays OBSERVED, since what + #: WAS read already refuses, and the summary names them, so the log line and the alert do not + #: imply the rest was read. 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: """``"over_granted"``, ``"unobservable"``, or ``None`` for a clean or NOT_APPLICABLE read — the @@ -557,16 +564,15 @@ class PrivilegeProbeStore(Protocol): could not observe, which is precisely what that status means.""" async def probe_principal_privileges(self) -> StorePrivilegeReport: - """Read this store principal's effective privileges, three ways per grant: held, not held, - or not read (BACKLOG #6015 item 3). - - ``OBSERVED`` with an empty ``excess`` is a clean read. A grant that was not read is never - reported as not held: the report is ``UNOBSERVABLE``, or, for a grant the backend weighs - after an over-grant it did read, stays ``OBSERVED`` with that over-grant in ``excess`` and - the unread grant in ``unread``, so the start still refuses on what WAS read. - ``NOT_APPLICABLE`` is SQLite's, which has no principal. Each backend's method says which - grants it reads, which unread ones stop the observation, and which count under - ``[store].schema_management``.""" + """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 backend may also leave a read out of ``unread``: + the SQL Server probe notes a failed best-effort enumeration of user-defined roles 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.""" ... diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index 53cb4e557a..dd415afa05 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -5257,14 +5257,14 @@ 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] = [] + 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"]) 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] = [] @@ -5302,6 +5302,7 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: database=database, server_roles=server_roles, database_roles=database_roles, + 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 the {probed} role and CONTROL grant(s) probed, so they were" @@ -5342,7 +5343,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), ) @@ -5363,6 +5365,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" diff --git a/tests/test_store_privilege_preflight.py b/tests/test_store_privilege_preflight.py index 3edb79c544..c3e7075b6e 100644 --- a/tests/test_store_privilege_preflight.py +++ b/tests/test_store_privilege_preflight.py @@ -946,6 +946,54 @@ async def test_an_over_grant_summary_names_the_external_grants_it_could_not_read 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: + """The structured field is not empty exactly when grants went unread: an UNOBSERVABLE report + fills it 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",)) From 33913ce31abe5c2990a4976048476f80f79ae782 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:50:04 -0600 Subject: [PATCH 06/29] SOAP fault anchor and blank code, one Authorization owner beside a signer BACKLOG #5912 closing steps 6 (Body anchor half), 9, 11, 13 (ADR half), 17, 24 (_FAULT_TAG_IN_MARKUP half) and 5: - _find_fault takes the first Body start tag outside terminated markup. - A first-child code element holding only whitespace falls back as an empty one does. - The fallback reuses the first-child Fault close-tag scan where it stepped over no markup, instead of a second plain scan. - The fallback rule is stated once, in _fault_code's docstring; the ADR 0015 amendment, CONNECTIONS.md, the changelog and the module comments point there. The ADR close-tag sentence names both exceptions. - Two rows pin "the first" of several in-markup Faults. BACKLOG #5526 items 2, 4, 5, 6, 9, 11 and 12: - SOAP refuses bearer_token beside a Basic pair; the census lists Basic. - SOAP and REST refuse a signing header named Authorization beside a configured or minted credential. - SOAP runs the Digest conflict check once and names the connection when built without the runner. - The census lists Digest for an unresolved env() http_auth. - ADR 0139 and the CONNECTIONS.md ECH row record the REST ECH+Digest refusal. --- changelog.d/5526-remainder.security.md | 10 + changelog.d/5912.security.md | 66 ++---- docs/CONNECTIONS.md | 44 ++-- .../0015-ws-soap-outbound-mtls-wssecurity.md | 15 +- ...sni-hiding-for-asvs-12-1-5-demand-gated.md | 2 +- messagefoundry/config/static_credentials.py | 28 ++- messagefoundry/transports/http_auth.py | 64 +++++- messagefoundry/transports/rest.py | 7 +- messagefoundry/transports/soap.py | 112 +++++---- tests/test_soap_5526_remainder.py | 215 ++++++++++++++++++ tests/test_soap_5912_closing_steps.py | 175 ++++++++++++++ tests/test_soap_fault_scan_linear.py | 32 ++- 12 files changed, 628 insertions(+), 142 deletions(-) create mode 100644 changelog.d/5526-remainder.security.md create mode 100644 tests/test_soap_5526_remainder.py create mode 100644 tests/test_soap_5912_closing_steps.py diff --git a/changelog.d/5526-remainder.security.md b/changelog.d/5526-remainder.security.md new file mode 100644 index 0000000000..beeba339e0 --- /dev/null +++ b/changelog.d/5526-remainder.security.md @@ -0,0 +1,10 @@ +- **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: 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 + static-credential inventory lists HTTP Basic alone where both a `bearer_token` and a Basic pair + are set, and lists HTTP Digest for an `http_auth` it reads before its `env()` value resolves. + (`BACKLOG #5526`) diff --git a/changelog.d/5912.security.md b/changelog.d/5912.security.md index 5099d184ba..e12ada1bed 100644 --- a/changelog.d/5912.security.md +++ b/changelog.d/5912.security.md @@ -1,48 +1,22 @@ - **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. Unchanged: whether a Fault counts, and that the WS-Security + check searches the reply from where the Fault search starts. (`BACKLOG #5912`) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 4ed3917db1..270f644407 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -3000,7 +3000,7 @@ 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. | | `timeout_seconds` | `30` | per-request timeout, in seconds above zero: zero or a negative is refused when the connection is built | @@ -3014,34 +3014,22 @@ 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` docstring in [`transports/soap.py`](../messagefoundry/transports/soap.py). The +Fault is the first Fault start tag after the first Body start tag, or with no Fault after it the first +in the reply, each searched for outside terminated 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 @@ -5222,7 +5210,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/adr/0015-ws-soap-outbound-mtls-wssecurity.md b/docs/adr/0015-ws-soap-outbound-mtls-wssecurity.md index 052fd34051..2db90b5e42 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/static_credentials.py b/messagefoundry/config/static_credentials.py index 5ab5fc0030..48410b3e11 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. @@ -183,25 +184,34 @@ def _oauth2(settings: Mapping[str, Any]) -> bool: def _digest(settings: Mapping[str, Any]) -> 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.""" from messagefoundry.transports.http_auth import HttpAuthError, http_digest_selected + if isinstance(settings.get("http_auth"), EnvRef): + # BACKLOG #5526 item 9: read before env() resolves, the mode is unknown, and it may resolve + # to 'digest', so it is listed, as an unresolved oauth2_enabled reads as on. + return True 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, REST, SOAP and DICOMweb refuse to build, and FHIR + sends Basic, so only Basic is listed (BACKLOG #5526 item 2).""" 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]: diff --git a/messagefoundry/transports/http_auth.py b/messagefoundry/transports/http_auth.py index 43c03fae57..bae0dbb5e9 100644 --- a/messagefoundry/transports/http_auth.py +++ b/messagefoundry/transports/http_auth.py @@ -78,10 +78,12 @@ "BearerTokenProvider", "HttpAuthError", "OAuth2ClientCredentialsProvider", + "authorization_credential", "bearer_provider_from_settings", "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", @@ -516,7 +518,8 @@ def refuse_http_digest_conflicts(s: Mapping[str, Any]) -> bool: """Whether Digest is selected, after refusing what cannot stand beside it (BACKLOG #5529). The connectors call this at the top of construction, so a connection that will not build logs - no insecure-hop crossing or warning first; :func:`digest_handler_from_settings` calls it again. + no insecure-hop crossing or warning first; :func:`digest_handler_from_settings` calls it again + unless the caller passes the answer it already holds. Refuses an unrecognised ``http_auth`` (:func:`http_digest_selected`), and with Digest selected, a static ``bearer_token``, ``basic_user``, ``basic_password`` or ``Authorization`` entry in ``headers``: beside Digest, a connection configures exactly one HTTP credential. Where such a @@ -525,7 +528,8 @@ 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). @@ -561,16 +565,55 @@ 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" + extra = s.get("headers") + if isinstance(extra, Mapping) and any(is_authorization_header_name(str(k)) for k in extra): + return "an Authorization entry in headers" + return None + + +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.""" + _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" ) def digest_handler_from_settings( - s: Mapping[str, Any], *, url: str + s: Mapping[str, Any], *, url: str, digest_selected: bool | None = None ) -> urllib.request.HTTPDigestAuthHandler | None: """An :class:`urllib.request.HTTPDigestAuthHandler` pre-loaded with the connection's credentials (BACKLOG #65, RFC 7616), or ``None`` when HTTP Digest auth is off (``http_auth`` unset, falsy @@ -583,8 +626,13 @@ def digest_handler_from_settings( through the rule the delivery cells' credentials share (``refuse_cleartext_credential_hop``): only a loopback host lifts it, never ``tls_hop_attested`` or ``cleartext_accepted`` (vault BACKLOG #3533 item 4). A missing user/password is a loud :class:`HttpAuthError` (fail-closed, never a silent - no-auth request).""" - if not refuse_http_digest_conflicts(s): + no-auth request). + + ``digest_selected`` is :func:`refuse_http_digest_conflicts`'s answer where the caller already + ran it on these settings, so it is not run twice per build (BACKLOG #5526 item 4); ``None``, the + default, runs it here.""" + selected = refuse_http_digest_conflicts(s) if digest_selected is None else digest_selected + if not selected: return None # The declarations are read strictly: a non-bool flag raises HttpAuthError naming the connection # (vault BACKLOG #2232), and the mirrored connection name heads the refusal below. diff --git a/messagefoundry/transports/rest.py b/messagefoundry/transports/rest.py index 6cd79753ab..8540885b6f 100644 --- a/messagefoundry/transports/rest.py +++ b/messagefoundry/transports/rest.py @@ -2997,7 +2997,7 @@ def __init__(self, config: Destination) -> 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. from messagefoundry.transports.http_auth import ( - refuse_authorization_signer_beside_digest, + refuse_authorization_signer_beside_credential, refuse_http_digest_conflicts, ) @@ -3098,8 +3098,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 4d1ea763a9..668b7957bb 100644 --- a/messagefoundry/transports/soap.py +++ b/messagefoundry/transports/soap.py @@ -80,6 +80,7 @@ flag_from_settings, ) from messagefoundry.config.tls_policy import ( + MIRRORED_CONNECTION_SETTING, SYSTEM_TRUST_ANCHOR, TrustAnchor, build_verifying_client_context, @@ -158,8 +159,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) @@ -174,14 +175,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) @@ -201,6 +196,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) == "" diff --git a/tests/test_soap_fault_scan_linear.py b/tests/test_soap_fault_scan_linear.py index e898b2bbb8..f63564822c 100644 --- a/tests/test_soap_fault_scan_linear.py +++ b/tests/test_soap_fault_scan_linear.py @@ -72,7 +72,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/>])" @@ -110,11 +115,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): @@ -134,7 +139,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( @@ -853,7 +858,7 @@ def test_the_fault_is_read_from_the_body( patched out the shape reads otherwise, as it did when the first Fault, and any WS-Security 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 @@ -938,6 +943,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": ( @@ -991,6 +1011,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 From dfe10cc1586c9a3567973c08fdec4ea932ab9405 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:05:52 -0600 Subject: [PATCH 07/29] FhirLookup gate order: narrow the comments to the checks _planned runs; colon and empty-table tests Review round-f83d2ad98b repairs. The lookup comment, the _planned docstring and the test docstring now claim the no-record ordering for the checks _planned runs, not every pure check. The proxy header's length check runs only when a proxy header was added, the revocation attestation is read once in _planned, and the headers refusal names the connection and refuses an empty non-table value. Tests add the ':' in basic_user case on both connectors. The changelog and CONNECTIONS.md headers row are worded to match. BACKLOG #8299, BACKLOG #5911. Proposed PR title: FHIR lookup gate order and static credential refusals (BACKLOG #8299, #5911) Proposed banner #8299: PARTIAL: items 2, 3, 4, 6 and 8 built, item 9 first half (the length refusal names the lookup), item 1 for fhir.py and rest.py. Left: item 1 soap.py and the refuse_http_digest_conflicts docstring (http_auth.py); item 5 (needs the http_auth.py docstring); item 7 residual; item 9 second half (SDS-3.5); items 10-25. Proposed banner #5911: PARTIAL to MET on step 6: settings-row text added to docs/CONNECTIONS.md; the changelog fragment is on main from PR 3144. Steps 3-5 and 7-11 as PR 3144 states. --- .../8299-fhir-lookup-gate-order.fixed.md | 21 ++++---- docs/CONNECTIONS.md | 2 +- messagefoundry/transports/fhir.py | 53 ++++++++++--------- tests/test_fhir_lookup_gate_order.py | 20 +++++-- 4 files changed, 55 insertions(+), 41 deletions(-) diff --git a/changelog.d/8299-fhir-lookup-gate-order.fixed.md b/changelog.d/8299-fhir-lookup-gate-order.fixed.md index b3fab6f08b..bf1127b851 100644 --- a/changelog.d/8299-fhir-lookup-gate-order.fixed.md +++ b/changelog.d/8299-fhir-lookup-gate-order.fixed.md @@ -1,10 +1,11 @@ -- **A `FhirLookup` refused for a setting no longer leaves a crossing record from another lookup - first, in at least these cases.** Its url and header screens, its length limits, 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; each used to build and send no headers, no Basic credential, or Basic in place of the - bearer. (`BACKLOG #8299`) +- **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/CONNECTIONS.md b/docs/CONNECTIONS.md index ab2f6e91c9..bb1d47b5f7 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -3452,7 +3452,7 @@ source (`Http()`, File, a `Loopback` re-ingress) as a `RawMessage`. | `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). Refused at construction: 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) | +| `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()`). 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 | diff --git a/messagefoundry/transports/fhir.py b/messagefoundry/transports/fhir.py index d245652f64..d66d37d19c 100644 --- a/messagefoundry/transports/fhir.py +++ b/messagefoundry/transports/fhir.py @@ -72,7 +72,7 @@ hop_attestation_from_settings, ) from messagefoundry.config.settings import EgressSettings -from messagefoundry.config.tls_policy import InsecureHopRefused, TrustAnchorPolicy +from messagefoundry.config.tls_policy import InsecureHopRefused, TrustAnchorPolicy, hop_name_prefix from messagefoundry.connection_names import fhir_lookup_record_name from messagefoundry.controlchars import has_control_char from messagefoundry.fhirsearch import FhirSearchParams, resolve_search_pairs @@ -868,8 +868,11 @@ def _refuse_unsendable_static_headers( :func:`~messagefoundry.transports.rest._refuse_unsendable_static_auth`. Names settings, never a value.""" extra = s.get("headers") - if extra and not isinstance(extra, Mapping): - raise ValueError(f"{setting} 'headers' must be a table of header names to values") + if extra is not None and not isinstance(extra, Mapping): + 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) @@ -2015,6 +2018,8 @@ class _LookupPlan(NamedTuple): attested: bool accepted: bool reason: str | None + revocation_attested: bool + revocation_reason: str | None class FhirLookupExecutor: @@ -2065,11 +2070,10 @@ def __init__( token_provider_from_settings, ) - # BACKLOG #5911, #8299 items 2, 3 and 9: every check that needs no I/O and logs nothing runs - # for every lookup before any lookup is built, so a lookup one of them refuses leaves no - # hop-gate crossing record (#5529), from itself or from a lookup built before it. A refusal - # later in the loop below still can leave one, from the failing lookup itself or from a - # lookup built before it. + # 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]] = {} @@ -2110,13 +2114,12 @@ 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: the static url and headers were bounded in _planned; the pre-emptive - # Proxy-Authorization above is bounded here, before this lookup's other gates. The - # proxy route's own gate has already run, so this refusal can follow its record. - try: - enforce_outbound_length_limits(url, headers) - except ValueError as exc: - raise ValueError(f"FhirLookup {cname!r}: {exc}") from exc + # ASVS 4.2.5: _planned bounded the static url and headers; this bounds the header + # just added, after the proxy route's gate. + try: + enforce_outbound_length_limits(url, headers) + except ValueError as exc: + raise ValueError(f"FhirLookup {cname!r}: {exc}") from exc # The read sends Authorization (static or SMART) — refuse it over cleartext http. # 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. @@ -2171,16 +2174,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 " @@ -2206,9 +2205,10 @@ def __init__( @classmethod def _planned(cls, cname: str, s: Mapping[str, Any]) -> _LookupPlan: - """What the lookup's checks that need no I/O and log nothing settle, once it passes them + """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. + 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: @@ -2250,11 +2250,14 @@ def _planned(cls, cname: str, s: Mapping[str, Any]) -> _LookupPlan: # 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) - _check_revocation_attestation(*revocation_attestation_from_settings(s)[:2]) + 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) + 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/tests/test_fhir_lookup_gate_order.py b/tests/test_fhir_lookup_gate_order.py index 23a5d903bc..289bf6da79 100644 --- a/tests/test_fhir_lookup_gate_order.py +++ b/tests/test_fhir_lookup_gate_order.py @@ -2,8 +2,8 @@ # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """BACKLOG #8299 items 2, 3, 4, 6, 8 and 9: the order of the FhirLookupExecutor's checks and gates. -A check that needs no I/O and logs nothing runs for every lookup before any lookup reaches a hop -gate, so a lookup it refuses leaves no crossing record, from itself or from a lookup built before +The checks ``_planned`` runs come for every lookup before any lookup reaches a hop gate, so a +lookup one of them refuses leaves no crossing record, from itself or from a lookup built before it. Synthetic values only. """ @@ -151,13 +151,22 @@ def test_the_static_credential_check_runs_before_the_token_provider_is_built( [ ({"headers": ["X-Site", "1"]}, "'headers' must be a table"), ({"basic_user": "u"}, "basic_user and basic_password must be set together"), + ({"headers": []}, "'headers' must be a table"), ({"basic_password": "p"}, "basic_user and basic_password must be set together"), + ({"basic_user": "a:b", "basic_password": "p"}, "basic_user must not contain ':'"), ( {"basic_user": "u", "basic_password": "p", "bearer_token": "t"}, "both bearer_token and basic_user", ), ], - ids=["headers-list", "user-only", "password-only", "bearer-and-basic"], + ids=[ + "headers-list", + "user-only", + "headers-empty-list", + "password-only", + "colon", + "bearer-and-basic", + ], ) def test_a_static_credential_the_lookup_would_drop_is_refused( over: dict[str, Any], match: str @@ -196,12 +205,13 @@ def _destination(**over: Any) -> object: ({"headers": ["X-Site", "1"]}, "'headers' must be a table"), ({"basic_user": "u"}, "basic_user and basic_password must be set together"), ({"basic_password": "p"}, "basic_user and basic_password must be set together"), + ({"basic_user": "a:b", "basic_password": "p"}, "basic_user must not contain ':'"), ( {"basic_user": "u", "basic_password": "p", "bearer_token": "t"}, "both bearer_token and basic_user", ), ], - ids=["headers-list", "user-only", "password-only", "bearer-and-basic"], + ids=["headers-list", "user-only", "password-only", "colon", "bearer-and-basic"], ) def test_the_fhir_destination_refuses_the_same_dropped_credentials( over: dict[str, Any], match: str @@ -209,7 +219,7 @@ def test_the_fhir_destination_refuses_the_same_dropped_credentials( """Item 8, on the destination's own copy of ``_build_headers``.""" with pytest.raises(ValueError, match=match) as ei: _destination(**over) - assert "FHIR destination" in str(ei.value) + assert str(ei.value).startswith("connection 'OB_FHIR'; FHIR destination") def test_the_control_the_fhir_destination_still_builds_a_whole_credential() -> None: From 64548d7a3ebc2228691b933908fbd8b85471fa8a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:06:55 -0600 Subject: [PATCH 08/29] Row seal review round 1: refusal precedes encoder errors, one non-text rule - The non-finite refusal reads the fields whole first again, so it wins over an encoder TypeError in any field order, as on main; math.isfinite. - TransitRowSealer._digest takes finite as a required keyword. - require_seal_for_write drops its own non-text guard; both sealers' _parse is the one rule. - Prose: the module docstring names which calls refuse and that seal_bytes and digests on it (passkey_digest) do not; the NOT NULL and nullable cases are stated in NonFiniteSealValueError. - Tests: positive controls on every Transit non-text check, a Transit session read with a BLOB seal, the subclass asserted in the existing test. BACKLOG #6717, #6718 Proposed PR title: Row seal: Transit sealer refuses non-finite floats and reads a non-text seal as malformed (BACKLOG #6717, #6718) Proposed banners: #6717 PARTIAL: Transit sealer now refuses NaN/inf as the local one does, NonFiniteSealValueError, items 2-8 fixed or kept. Left: item 9 (keyless store record builders write a NaN silently), store.py, outside this brief. #6718 MET: item 1 met on main (_encodes), items 2 and 3 fixed with tests. --- .../6717-row-seal-transit-non-finite.fixed.md | 2 +- messagefoundry/store/row_seal.py | 42 ++++---- tests/test_row_seal.py | 12 ++- tests/test_row_seal_followups.py | 98 ++++++++++--------- 4 files changed, 83 insertions(+), 71 deletions(-) diff --git a/changelog.d/6717-row-seal-transit-non-finite.fixed.md b/changelog.d/6717-row-seal-transit-non-finite.fixed.md index 6bb9e38b13..72cf073f64 100644 --- a/changelog.d/6717-row-seal-transit-non-finite.fixed.md +++ b/changelog.d/6717-row-seal-transit-non-finite.fixed.md @@ -2,4 +2,4 @@ Row seals: the Vault Transit row sealer now refuses to seal a float that is a Na as the local sealer already did, and both raise `NonFiniteSealValueError`, a `ValueError` subclass. The Transit sealer reads a stored seal that is not text (a blob or a number) as malformed rather than raising, so a write over such a session row is refused as a failed seal (BACKLOG #6717, -#6718). The bytes a seal covers are unchanged, so a seal written before this change still verifies. +#6718). The bytes a seal covers are unchanged. diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index 67621e4fef..1711b9793b 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -33,9 +33,11 @@ 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, 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. Making a seal, under either sealer, -raises :class:`NonFiniteSealValueError` for a float that is not finite, while checking a seal over -one fails rather than raises (BACKLOG #6717). +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, so a check over a row someone set to such +a value fails rather than raises, and so does a digest built on the encoder, such as the store's +``passkey_digest`` (BACKLOG #6717). """ from __future__ import annotations @@ -48,6 +50,7 @@ import hashlib import hmac import logging +import math import time from collections.abc import Callable, Iterable from concurrent.futures import ThreadPoolExecutor @@ -118,17 +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``, 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. Its own type, so a caller can tell it from the ``ValueError`` a malformed field - pair raises when it is unpacked.""" + 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): @@ -268,12 +270,14 @@ def seal_bytes(kind: str, fields: Iterable[tuple[str, object]]) -> bytes: def _seal_bytes(kind: str, fields: Iterable[tuple[str, object]], *, finite: bool) -> bytes: - # ``finite`` is set only where a seal is MADE. A check encodes a non-finite float as it is, so - # a row someone set to one fails its seal rather than raising from the check. + # ``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: - if finite and isinstance(value, float) and not -_FLOAT_INF < value < _FLOAT_INF: - raise NonFiniteSealValueError("a row seal refuses a float that is not finite") type_byte, encoded = _encode_value(value) out.append(_part(name.encode("utf-8")) + type_byte + _part(encoded)) return b"".join(out) @@ -713,9 +717,7 @@ def __init__( self._clock = clock self._throttle = SealFailureThrottle() - def _digest( - self, kind: str, fields: Iterable[tuple[str, object]], *, finite: bool = False - ) -> bytes: + 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() @@ -824,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() @@ -1015,10 +1017,6 @@ async def require_seal_for_write( here; a whole token hash in it would reach ``args``.""" if sealer is None: return - if stored is not None and not isinstance(stored, str): - # A stored seal that is not text (a BLOB a writer put there) is no seal: Forged, as both - # sealers' checks read it (BACKLOG #6718). - 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 diff --git a/tests/test_row_seal.py b/tests/test_row_seal.py index e98885d059..613a797efa 100644 --- a/tests/test_row_seal.py +++ b/tests/test_row_seal.py @@ -27,7 +27,12 @@ make_cipher, row_seal_key_id, ) -from messagefoundry.store.row_seal import SEAL_PREFIX, RowSealer, seal_bytes +from messagefoundry.store.row_seal import ( + SEAL_PREFIX, + NonFiniteSealValueError, + RowSealer, + seal_bytes, +) _FIELDS = (("token_hash", "a" * 64), ("user_id", "u1"), ("created_at", 1.5), ("revoked_at", None)) @@ -212,8 +217,11 @@ def test_negative_zero_encodes_as_zero_does() -> None: def test_a_seal_refuses_a_float_that_is_not_finite(value: float) -> None: # BACKLOG #6717. SQLite stores a NaN as NULL, so a seal over one could never verify again. sealer = _sealer() - with pytest.raises(ValueError): + with pytest.raises(NonFiniteSealValueError): sealer.seal("session", (("expires_at", value),)) + # The refusal precedes an encoder error in any field order. + with pytest.raises(NonFiniteSealValueError): + sealer.seal("session", (("a", object()), ("expires_at", value))) assert sealer.seal("session", (("expires_at", 1.5),)) # control: a finite value seals diff --git a/tests/test_row_seal_followups.py b/tests/test_row_seal_followups.py index c6402ad4ee..04489518ce 100644 --- a/tests/test_row_seal_followups.py +++ b/tests/test_row_seal_followups.py @@ -1,8 +1,8 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""Row-seal follow-ups to BACKLOG #6717 and #6718: the non-finite refusal on both sealers, its own -error type, a non-text stored seal on the Transit sealer, and pins that a seal written before these -changes still verifies. Synthetic data only. +"""Row-seal follow-ups to BACKLOG #6717 and #6718: the non-finite refusal on the Transit sealer and +its own error type, a non-text stored seal on the Transit sealer, and pins on the encoded bytes. +Synthetic data only. """ from __future__ import annotations @@ -14,10 +14,15 @@ import pytest -from messagefoundry.store import row_seal -from messagefoundry.store.row_seal import SESSION_KIND, RowSealer, TransitRowSealer, seal_bytes -from messagefoundry.store.store import SessionRecord, session_seal_ok -from tests._transit_seal_fake import Clock, FakeBackend +from messagefoundry.store.row_seal import ( + SESSION_KIND, + NonFiniteSealValueError, + RowSealer, + TransitRowSealer, + seal_bytes, +) +from messagefoundry.store.store import SessionRecord, session_seal_ok_async +from tests._transit_seal_fake import RETIRED, Clock, FakeBackend # Every type the encoder writes, and both zeros, so a change to any encoding moves a pin below. _PINNED_FIELDS: tuple[tuple[str, object], ...] = ( @@ -31,7 +36,8 @@ ("y", b"\x00\xff"), ) _PINNED_KEY = bytes(range(32)) -# Read on engine origin/main d2ed8a8bd8, before this branch: what main writes for the fields above. +# Read on engine origin/main d2ed8a8bd8, before this branch's refactor of the encoder, to show the +# refactor kept the bytes. A deliberate change to the v1 encoding updates these pins. _MAIN_SEAL = ( "mfseal:v1:5bb5e8d61e093c73:9f6d72b1305e9a30042794e7ec47c723b83dc51111924ada8fe9c521738021ea" ) @@ -41,12 +47,12 @@ _NOT_FINITE = (float("nan"), float("inf"), float("-inf")) -def _transit() -> tuple[TransitRowSealer, FakeBackend]: +def _transit(**kw: Any) -> tuple[TransitRowSealer, FakeBackend]: backend = FakeBackend() - return TransitRowSealer(backend, clock=Clock()), backend + return TransitRowSealer(backend, clock=Clock(), **kw), backend -def test_a_seal_main_wrote_still_verifies_and_is_written_again() -> None: +def test_the_encoded_bytes_are_the_ones_main_wrote() -> None: sealer = RowSealer(_PINNED_KEY) assert sealer.verify(SESSION_KIND, _PINNED_FIELDS, _MAIN_SEAL) assert sealer.seal(SESSION_KIND, _PINNED_FIELDS) == _MAIN_SEAL @@ -54,34 +60,30 @@ def test_a_seal_main_wrote_still_verifies_and_is_written_again() -> None: assert digest == _MAIN_SEAL_BYTES_SHA256 # Control: one changed field fails, so the pin is not a sealer that accepts everything. assert not sealer.verify(SESSION_KIND, (*_PINNED_FIELDS[:-1], ("y", b"\x00")), _MAIN_SEAL) + transit, _ = _transit() + for finite in (False, True): + assert transit._digest(SESSION_KIND, _PINNED_FIELDS, finite=finite).hex() == ( + _MAIN_TRANSIT_DIGEST + ) + assert transit._digest(SESSION_KIND, _PINNED_FIELDS[:-1], finite=False).hex() != ( + _MAIN_TRANSIT_DIGEST + ) -def test_the_transit_digest_main_computed_is_unchanged() -> None: - sealer, _ = _transit() - assert sealer._digest(SESSION_KIND, _PINNED_FIELDS).hex() == _MAIN_TRANSIT_DIGEST - assert sealer._digest(SESSION_KIND, _PINNED_FIELDS[:-1]).hex() != _MAIN_TRANSIT_DIGEST - - -@pytest.mark.parametrize("value", _NOT_FINITE) -def test_the_non_finite_refusal_has_its_own_value_error(value: float) -> None: - # BACKLOG #6717 item 4: a malformed field tuple raises ValueError too; the refusal is told apart - # from it by type. - refused = row_seal.NonFiniteSealValueError - assert issubclass(refused, ValueError) - sealer = RowSealer(_PINNED_KEY) - with pytest.raises(refused): - sealer.seal(SESSION_KIND, (("expires_at", value),)) +def test_the_non_finite_refusal_is_told_apart_from_a_malformed_field_pair() -> None: + # BACKLOG #6717 item 4: a malformed field pair raises ValueError too. + assert issubclass(NonFiniteSealValueError, ValueError) malformed: Any = [("only-a-name",)] with pytest.raises(ValueError) as unpack: - sealer.seal(SESSION_KIND, malformed) - assert not isinstance(unpack.value, refused) + RowSealer(_PINNED_KEY).seal(SESSION_KIND, malformed) + assert not isinstance(unpack.value, NonFiniteSealValueError) @pytest.mark.parametrize("value", _NOT_FINITE) async def test_the_transit_sealer_refuses_a_float_that_is_not_finite(value: float) -> None: # BACKLOG #6717: the local sealer refused a NaN or an infinity, and the Transit sealer sealed it. sealer, backend = _transit() - with pytest.raises(row_seal.NonFiniteSealValueError): + with pytest.raises(NonFiniteSealValueError): await sealer.seal_async(SESSION_KIND, (("expires_at", value),)) assert backend.inputs == [] # nothing reached Transit stored = await sealer.seal_async(SESSION_KIND, (("expires_at", 1.5),)) # control @@ -92,31 +94,35 @@ async def test_the_transit_sealer_refuses_a_float_that_is_not_finite(value: floa @pytest.mark.parametrize( "as_type", - [lambda s: s.encode("ascii"), lambda s: bytearray(s, "ascii"), lambda s: 7, lambda s: 7.5], - ids=["bytes", "bytearray", "int", "float"], + [lambda s: s.encode("ascii"), lambda s: bytearray(s, "ascii")], + ids=["bytes", "bytearray"], ) async def test_a_transit_seal_that_is_not_text_fails_every_check_without_raising( as_type: Callable[[str], Any], ) -> None: # BACKLOG #6718 item 3: TransitRowSealer._parse called startswith on whatever the column held. - sealer, backend = _transit() + # Each check has a positive control on the text form, so a False below is the parse refusing. + sealer, backend = _transit(retired_key_names=[RETIRED]) fields = (("token_hash", "ab" * 32), ("n", 3)) stored = await sealer.seal_async(SESSION_KIND, fields) - assert sealer.is_active(stored) # controls: the text form holds + old = TransitRowSealer(FakeBackend(active=RETIRED), clock=Clock()) + old_stored = await old.seal_async(SESSION_KIND, fields) + assert sealer.is_active(stored) assert await sealer.verify_async(SESSION_KIND, fields, stored) + assert await sealer.verify_held_async(SESSION_KIND, fields, stored) + assert await sealer.sealed_by_retired_key_async(SESSION_KIND, fields, old_stored) calls = backend.verify_calls - other = as_type(stored) - assert not sealer.is_active(other) - assert not await sealer.verify_async(SESSION_KIND, fields, other) - assert not await sealer.verify_held_async(SESSION_KIND, fields, other) - assert not await sealer.sealed_by_retired_key_async(SESSION_KIND, fields, other) + assert not sealer.is_active(as_type(stored)) + assert not await sealer.verify_async(SESSION_KIND, fields, as_type(stored)) + assert not await sealer.verify_held_async(SESSION_KIND, fields, as_type(stored)) + assert not await sealer.sealed_by_retired_key_async(SESSION_KIND, fields, as_type(old_stored)) assert backend.verify_calls == calls # read as malformed, with no Transit call -def test_a_session_row_whose_seal_cell_is_not_text_fails_its_check() -> None: - # BACKLOG #6718 item 2: from_mapping hands a non-text seal cell through as it was read, and the - # check reads it as a malformed seal rather than raising. - sealer = RowSealer(_PINNED_KEY) +async def test_a_session_row_whose_seal_cell_is_a_blob_fails_its_check_on_transit() -> None: + # BACKLOG #6718 items 2 and 3: from_mapping hands a BLOB seal cell through as it was read, and + # the session read check under the Transit sealer reads it as malformed rather than raising. + sealer, _ = _transit() record = SessionRecord( token_hash="ab" * 32, user_id="u1", @@ -126,7 +132,7 @@ def test_a_session_row_whose_seal_cell_is_not_text_fails_its_check() -> None: revoked_at=None, client=None, ) - row = {**asdict(record), "seal": sealer.seal(SESSION_KIND, record.seal_fields())} - assert session_seal_ok(sealer, SessionRecord.from_mapping(row)) # control - for cell in (row["seal"].encode("ascii"), 7, 7.5): - assert not session_seal_ok(sealer, SessionRecord.from_mapping({**row, "seal": cell})) + row = {**asdict(record), "seal": await sealer.seal_async(SESSION_KIND, record.seal_fields())} + assert await session_seal_ok_async(sealer, SessionRecord.from_mapping(row)) # control + blob = {**row, "seal": row["seal"].encode("ascii")} + assert not await session_seal_ok_async(sealer, SessionRecord.from_mapping(blob)) From 68083494dc291d64b22be00141bfe2307725deb6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:08:17 -0600 Subject: [PATCH 09/29] Store privilege probe: review round 2 on the R2 added items - The `unread` field comment and the protocol docstring say an empty tuple does not mean every grant was read, with "at least" cases, rather than one exception read as the list. - The PostgreSQL NULL current_schema report names its unread grant in `unread`. - The probed_grant docstrings scope the PostgreSQL caller to its audit-table columns, and classify_login_roles' docstring names the SQL Server store preflight. - The alter_schema QUOTENAME comment cites what it matches, not a comment that is not there. - docs/DEPLOY-SERVER-DB.md exit-3 bullet: a role or CONTROL grant hides lines, and an unread grant left after the over-grants are gone exits 4. BACKLOG #6015, BACKLOG #6714. Proposed PR title: Store privilege probe: R2 added items for #6015 and #6714 (shared probed_grant, unread grants in the summary, db_securityadmin) Proposed banners: #6015 CLOSED: claim met by PR 2879; added items 2-8 built on branch w10-privilege; item 1 kept by design (the #1234 pin: an unread role or CONTROL grant makes the report UNOBSERVABLE even beside a read sysadmin). #6714 PARTIAL: added items 2-6 built on branch w10-privilege (item 1 by PR 2879); S01-68 reads met on main (owner_named counts CONTROL SERVER, and sysadmin alone among server roles). Left: a reviewed not-a-bug ruling on the headline (custom roles flagged by name, by design per DEPLOY-SERVER-DB.md 1.3, the Manager's reading). #6715 OPEN: nothing built. Left: per-process warning keys (a stable process identity for the bare `store` subject), a design item. --- docs/DEPLOY-SERVER-DB.md | 11 ++++++----- messagefoundry/sqlserver_roles.py | 10 ++++++---- messagefoundry/store/postgres.py | 1 + messagefoundry/store/privilege.py | 15 ++++++++------- messagefoundry/store/sqlserver.py | 3 ++- messagefoundry/transports/database.py | 4 ++-- tests/test_store_privilege_preflight.py | 4 ++-- tests/test_store_privilege_schema_split.py | 2 ++ 8 files changed, 29 insertions(+), 21 deletions(-) diff --git a/docs/DEPLOY-SERVER-DB.md b/docs/DEPLOY-SERVER-DB.md index f086318478..4cd715cfc2 100644 --- a/docs/DEPLOY-SERVER-DB.md +++ b/docs/DEPLOY-SERVER-DB.md @@ -179,11 +179,12 @@ messagefoundry check-privileges --service-config \messagefoundry.t 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. A named - membership 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, until it exits 0. + 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 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. diff --git a/messagefoundry/sqlserver_roles.py b/messagefoundry/sqlserver_roles.py index f35d22b040..928999ffe0 100644 --- a/messagefoundry/sqlserver_roles.py +++ b/messagefoundry/sqlserver_roles.py @@ -20,7 +20,8 @@ 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. +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 @@ -65,9 +66,10 @@ def probed_grant(value: object) -> bool | None: 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 store preflight of both server backends (``store/privilege.py`` - re-exports it) and the partner-login probe (``transports/database.py`` - ``classify_login_roles``), so a change here changes how each of them reads.""" + 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/postgres.py b/messagefoundry/store/postgres.py index 571cc514ec..782baf4a6d 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -3134,6 +3134,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 " diff --git a/messagefoundry/store/privilege.py b/messagefoundry/store/privilege.py index 3ea92abc30..d3a20c059a 100644 --- a/messagefoundry/store/privilege.py +++ b/messagefoundry/store/privilege.py @@ -481,10 +481,11 @@ class StorePrivilegeReport: database_roles: tuple[str, ...] = () excess: tuple[str, ...] = () detail: str = "" - #: Grants the probe could NOT read (BACKLOG #6015 item 2), on an UNOBSERVABLE report and on an - #: OBSERVED one that already found an over-grant. There the report stays OBSERVED, since what - #: WAS read already refuses, and the summary names them, so the log line and the alert do not - #: imply the rest was read. + #: Grants the probe could NOT read and named (BACKLOG #6015 item 2). An OBSERVED report carries + #: them only beside an over-grant it found, since what WAS read already 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: @@ -569,9 +570,9 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: ``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 backend may also leave a read out of ``unread``: - the SQL Server probe notes a failed best-effort enumeration of user-defined roles in - ``detail`` only. Which grants a backend reads, how it reads each, and what it does with one + 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.""" ... diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index dd415afa05..c96ebd043b 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -5212,7 +5212,8 @@ 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," - # QUOTENAME: the securable is parsed as a name, as the VIEW DEFINITION columns below say. + # 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. diff --git a/messagefoundry/transports/database.py b/messagefoundry/transports/database.py index 3b2ee0a278..16c1d3a2c3 100644 --- a/messagefoundry/transports/database.py +++ b/messagefoundry/transports/database.py @@ -5680,8 +5680,8 @@ 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 by :func:`~messagefoundry.sqlserver_roles.probed_grant`, the one function the - store preflight reads its own login with (BACKLOG #6015): ``1`` held, ``0`` not held, NULL + 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. diff --git a/tests/test_store_privilege_preflight.py b/tests/test_store_privilege_preflight.py index c3e7075b6e..ab63c0f0bc 100644 --- a/tests/test_store_privilege_preflight.py +++ b/tests/test_store_privilege_preflight.py @@ -949,8 +949,8 @@ async def test_an_over_grant_summary_names_the_external_grants_it_could_not_read async def test_an_unobserved_report_carries_its_unread_grants_too( monkeypatch: pytest.MonkeyPatch, ) -> None: - """The structured field is not empty exactly when grants went unread: an UNOBSERVABLE report - fills it as well, on the external-only path and on the fixed-role path.""" + """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() diff --git a/tests/test_store_privilege_schema_split.py b/tests/test_store_privilege_schema_split.py index b82bf60bda..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 ----------------------------------------- From 555fa5e6badac20d7ddecb9038b7a8b203782757 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:17:49 -0600 Subject: [PATCH 10/29] Transit key names: review round-b0ed9d0765 repairs (BACKLOG #6010, #6710) - The refusal text names a name of dots alone beside a slash as what can move the request path; ".." does. - _key_names reads each refusal's text from the engine's record, never the instance, with a fixed fallback naming the variable. - The unset KEK / wrapped DEK refusal is recorded too, so the key seam keeps it. - verify_seal_hmac checks its key name before any request. - tls_policy CA paragraph lists the variables instead of claiming one record, and allows a directory (VAULT_CAPATH). - tests: test_keyless_chain_every_command pins the recorded text for an unset MEFOR_STORE_TRANSIT_KEY; the seam test stubs the client. Proposed PR title: Transit key names: one read, checked at each use, refusal text kept (BACKLOG #6010, #6710) Proposed banners: #6010 MET. The claim and item 1 were met by PR 2879; items 2 to 13 are met by this PR. #6710 PARTIAL. Item 3 met by this PR. Left: item 1 (cache, a decision owed; the event-loop cost is #5888), item 2 (wrapped retired DEKs, a design change), item 4 (shape check at base._checked_active_key, in store/base.py, which open PR 3164 edits). --- .../6010-transit-key-name-refusals.fixed.md | 16 ++++++---- messagefoundry/config/tls_policy.py | 10 +++--- messagefoundry/store/crypto_transit.py | 32 ++++++++++++++++--- messagefoundry/store/keyprovider_vault.py | 9 +++--- tests/test_crypto_transit.py | 22 +++++++++++-- tests/test_keyless_chain_every_command.py | 7 ++-- tests/test_keyprovider_vault.py | 29 ++++++++++++++++- 7 files changed, 97 insertions(+), 28 deletions(-) diff --git a/changelog.d/6010-transit-key-name-refusals.fixed.md b/changelog.d/6010-transit-key-name-refusals.fixed.md index 8eb7d0cb73..f7d0d3a8ee 100644 --- a/changelog.d/6010-transit-key-name-refusals.fixed.md +++ b/changelog.d/6010-transit-key-name-refusals.fixed.md @@ -1,7 +1,9 @@ -- **A malformed Vault Transit key name is refused with its own text.** The refusals for - `MEFOR_STORE_VAULT_TRANSIT_KEY`, `MEFOR_STORE_TRANSIT_KEY` and `MEFOR_STORE_TRANSIT_AUDIT_KEY`, - the refusal of an unset `MEFOR_STORE_TRANSIT_KEY`, and the `vault` key provider's refusal of an unwrapped DEK that is not base64 of 32 bytes, 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 - and the Transit cipher itself now check the name too. (`BACKLOG #6010`, `BACKLOG #6710`) +- **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`, of an unset KEK name or + wrapped DEK under `key_provider = "vault"`, and of an unwrapped DEK that is not base64 of 32 + bytes 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/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index 2f7bdb26b8..81bf0cc452 100644 --- a/messagefoundry/config/tls_policy.py +++ b/messagefoundry/config/tls_policy.py @@ -3551,11 +3551,11 @@ def requests_verify_from_anchor(anchor: TrustAnchor, *, cell: str) -> str | None Worth stating plainly, because the direction is counter-intuitive: this hop is not one of the broadly-trusting ones by default. With no anchor passed, hvac and ``requests`` choose the CA - from the process environment, and only when it names none do they fall back to ``requests``' - PUBLIC certifi bundle, not the OS store; which variables they read is recorded once, at - ``store/keyprovider_vault.py``'s ``_ENV_CA_FILE``. So an internal-CA Vault fails closed unless - one of those variables names a bundle holding its CA, and then that bundle, whatever else it - holds, is what the hop trusts. What was missing here is the ability to name this hop's CA in + from the process environment, at least hvac's ``VAULT_CACERT`` or ``VAULT_CAPATH``, then + ``requests``' ``REQUESTS_CA_BUNDLE`` or ``CURL_CA_BUNDLE``, and only when none is set do they + fall back to ``requests``' PUBLIC certifi bundle, not the OS store. So an internal-CA Vault + fails closed unless one of those variables names a bundle or directory holding its CA, and + then whatever that names 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): diff --git a/messagefoundry/store/crypto_transit.py b/messagefoundry/store/crypto_transit.py index 282197f0b9..66ccf692a4 100644 --- a/messagefoundry/store/crypto_transit.py +++ b/messagefoundry/store/crypto_transit.py @@ -1384,7 +1384,20 @@ 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).""" + try: + checked_transit_key_name(key_name, selector="the row seal's key name") + except KeyProviderError: + refused_name = True + else: + refused_name = False + if refused_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) @@ -1422,6 +1435,15 @@ 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 @@ -1436,7 +1458,7 @@ def _key_names() -> tuple[str, str]: try: key_name = transit_key_name_setting(_ENV_TRANSIT_KEY) except KeyProviderError as exc: - refusals.append(str(exc)) + refusals.append(_refusal_text(exc, _ENV_TRANSIT_KEY)) else: if key_name is None: refusals.append( @@ -1448,10 +1470,10 @@ def _key_names() -> tuple[str, str]: try: audit_key = transit_key_name_setting(_ENV_AUDIT_KEY) except KeyProviderError as exc: - refusals.append(str(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 this module or `checked_transit_key_name` built from a variable name alone, - # so it is recorded and the store's fixed-text seams keep it (BACKLOG #6010 item 3). + # 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 diff --git a/messagefoundry/store/keyprovider_vault.py b/messagefoundry/store/keyprovider_vault.py index de7948681c..bd99f0847d 100644 --- a/messagefoundry/store/keyprovider_vault.py +++ b/messagefoundry/store/keyprovider_vault.py @@ -591,7 +591,8 @@ def active_key(self) -> str | None: ) if not value ] - raise KeyProviderError( + # Built from variable names alone, so recorded: the key seam keeps it (BACKLOG #6010). + raise _recorded_refusal( f"[store].key_provider={_EXTRA!r} is selected but {', '.join(missing)} is not set — " f"supply the Transit KEK name and the wrapped DEK via the environment." ) @@ -751,9 +752,9 @@ def checked_transit_key_name(name: str, *, selector: str) -> str: if _TRANSIT_KEY_NAME.fullmatch(name) is None: 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 could change which " - f"Vault path a request reaches, and a name outside the shape Vault gives its key " - f"names is refused with it." + 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 diff --git a/tests/test_crypto_transit.py b/tests/test_crypto_transit.py index 25dd6d1b8e..786025c1a5 100644 --- a/tests/test_crypto_transit.py +++ b/tests/test_crypto_transit.py @@ -359,8 +359,9 @@ def read_key(self, *, name: str) -> dict[str, Any]: # --- both key names are checked before they reach a Transit path (BACKLOG #6010) ------------------ -#: The KEK test's cases (BACKLOG #6010 item 12): every Transit key name goes through one check, so -#: one list covers both modules, plus the two path-shaped names this module's tests began with. +#: The KEK test's cases (BACKLOG #6010 item 12): the KEK and both Transit key names go through +#: one check, so one list covers both modules, plus the two path-shaped names this module's tests +#: began with. _BAD_KEY_NAMES = [*_MALFORMED_KEK_NAMES, "mefor/store", "mefor-store/"] @@ -430,6 +431,23 @@ def test_the_cipher_itself_refuses_a_malformed_key_name(which: str, bad: str) -> TransitCipher(_FakeClient(_FakeTransit()), names[0], audit_key=names[1]) +@pytest.mark.parametrize("bad", _BAD_KEY_NAMES) +def test_a_row_seal_verify_refuses_a_malformed_key_name_before_any_request(bad: str) -> None: + """BACKLOG #6010 item 9: the row seal verify takes its key name from the sealer, not the + environment read, so it checks the name itself before it reaches ``transit/verify/``.""" + calls: list[str] = [] + + class _Recording(_FakeTransit): + def verify_signed_data(self, *, name: str, **kwargs: Any) -> dict[str, Any]: + calls.append(name) + return super().verify_signed_data(name=name, **kwargs) + + cipher = TransitCipher(_FakeClient(_Recording()), _KEY_NAME) + with pytest.raises(CipherError, match="not a Transit key name"): + cipher.verify_seal_hmac(bad, b"digest", "vault:v1:AAAA") + assert calls == [] + + @pytest.mark.parametrize("selector", ["MEFOR_STORE_TRANSIT_KEY", "MEFOR_STORE_TRANSIT_AUDIT_KEY"]) def test_a_malformed_key_name_keeps_its_text_through_build_store_cipher( monkeypatch: pytest.MonkeyPatch, selector: str diff --git a/tests/test_keyless_chain_every_command.py b/tests/test_keyless_chain_every_command.py index 162ee2e2ca..fdffca69b6 100644 --- a/tests/test_keyless_chain_every_command.py +++ b/tests/test_keyless_chain_every_command.py @@ -611,10 +611,9 @@ def test_a_key_that_does_not_resolve_exits_2( captured = capsys.readouterr() assert rc == 2, (captured.out, captured.err) text = _refusal_text(command, captured.out, captured.err) - from messagefoundry.store import base as store_base - - # A fixed text since the eighth hold on engine PR 2818. - assert store_base._TRANSIT_BUILD_TEXTS[4] in text, text + # The engine built this refusal from the variable's name alone and recorded it, so the + # build's fixed-text replacement keeps it, naming what to set (BACKLOG #6010 item 3). + assert "MEFOR_STORE_TRANSIT_KEY is not set" in text, text @pytest.mark.parametrize("command", [*_KEY_REFUSING_COMMANDS, "admin-reset-totp", "rotate-key"]) diff --git a/tests/test_keyprovider_vault.py b/tests/test_keyprovider_vault.py index c93e6a2091..6da3fc4c7b 100644 --- a/tests/test_keyprovider_vault.py +++ b/tests/test_keyprovider_vault.py @@ -346,7 +346,8 @@ def test_the_name_refusal_says_ascii_and_scopes_its_redirect_claim( monkeypatch: pytest.MonkeyPatch, ) -> None: """BACKLOG #6010 item 5: the shape is ASCII, as Go's ``\\w`` is, so the text says so; and only - a slash can move the request path, so the text does not say every refused name could.""" + a slash or a name of dots alone, such as ``..``, can move the request path, so the text does + not say every refused name could.""" monkeypatch.setenv("MEFOR_STORE_VAULT_TRANSIT_KEY", "kék") with pytest.raises(KeyProviderError) as excinfo: keyprovider_vault.kek_required_capabilities() @@ -371,6 +372,31 @@ def test_the_key_type_check_refuses_a_malformed_name_before_reading_it(name: str assert transit.read_calls == [] +def _no_client_built(monkeypatch: pytest.MonkeyPatch) -> None: + """A test whose refusal must come before any client fails here, not by dialling Vault.""" + + def _refuse(addr: str, token: str, **_: Any) -> _FakeClient: + raise AssertionError("a Vault client was built") + + monkeypatch.setattr(keyprovider_vault, "_build_client", _refuse) + + +def test_an_unset_kek_setting_keeps_its_text_at_the_key_seam( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The refusal of an unset KEK name or wrapped DEK is built from the variables' names alone, + so it is recorded too, and the key seam keeps it (BACKLOG #6010 item 3).""" + from messagefoundry.store.base import resolve_active_key + + _no_client_built(monkeypatch) + monkeypatch.delenv("MEFOR_STORE_VAULT_TRANSIT_KEY", raising=False) + monkeypatch.delenv("MEFOR_STORE_VAULT_WRAPPED_DEK", raising=False) + with pytest.raises(KeyProviderError) as excinfo: + resolve_active_key(StoreSettings(key_provider="vault")) + text = str(excinfo.value) + assert "MEFOR_STORE_VAULT_TRANSIT_KEY, MEFOR_STORE_VAULT_WRAPPED_DEK is not set" in text + + def test_a_malformed_kek_name_keeps_its_text_at_the_key_seam( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -380,6 +406,7 @@ def test_a_malformed_kek_name_keeps_its_text_at_the_key_seam( from messagefoundry.store.base import resolve_active_key _configure_env(monkeypatch) + _no_client_built(monkeypatch) monkeypatch.setenv("MEFOR_STORE_VAULT_TRANSIT_KEY", "a/../../../sys/x") with pytest.raises(KeyProviderError) as excinfo: resolve_active_key(StoreSettings(key_provider="vault")) From 5631e843097f1121ef90404c31458e6954a95c77 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:21:52 -0600 Subject: [PATCH 11/29] Review round 1: census env() http_auth, Body anchor fast path, keep Digest check Repairs from code-review round-5283f2a924 (BACKLOG #5912, #5526): - The census reads an env() http_auth against the guard's values, and an unresolved one as Digest only where no minted bearer stands beside it. - The Body anchor takes the plain match unless markup precedes it, so the Python-level step-over runs only then; _BODY_RE stays live. - Item 4 reverted: digest_handler_from_settings keeps its own refusal run. - Shared Authorization-header predicate; the signer refusal returns early when no signer writes Authorization. - CONNECTIONS.md OAuth2 row and Body-anchor sentence, changelog wording. Proposed PR title: SOAP fault anchor and blank code; one Authorization owner beside a signer (BACKLOG #5912, #5526) Proposed banners: #5912 PARTIAL: closing steps 5, 6 (Body-anchor half), 9, 11, 13 (ADR half), 17 and the _FAULT_TAG_IN_MARKUP half of 24 met on branch w10-soap. Left: steps 8, 18 and 22, parity-with-main trades that close on a fix or the owner's acceptance by name; step 6's second half is step 22's shape. #5526 PARTIAL: items 2, 5 (SOAP), 6 (SOAP and REST), 9, 11 and 12 built on branch w10-soap; items 7, 8, 14 to 22 met on main; item 10 kept by design (ADR 0015 amendment 2026-11-10); filing finding 2 is item 6. Left: item 1's FHIR half; item 4, kept in one line (the second Digest refusal run stays, since skipping it behind a caller flag would make a security refusal optional); item 5's REST and FHIR twins; item 6's FHIR twin; item 13 and filing finding 1 (FTPS, #5530). --- changelog.d/5526-remainder.security.md | 12 ++-- docs/CONNECTIONS.md | 6 +- messagefoundry/config/static_credentials.py | 37 ++++++++---- messagefoundry/transports/http_auth.py | 28 +++++----- messagefoundry/transports/soap.py | 13 +++-- tests/test_soap_5526_remainder.py | 62 ++++++++++++--------- tests/test_soap_fault_scan_linear.py | 1 + 7 files changed, 97 insertions(+), 62 deletions(-) diff --git a/changelog.d/5526-remainder.security.md b/changelog.d/5526-remainder.security.md index beeba339e0..01b164f2b0 100644 --- a/changelog.d/5526-remainder.security.md +++ b/changelog.d/5526-remainder.security.md @@ -2,9 +2,11 @@ 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: 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 - static-credential inventory lists HTTP Basic alone where both a `bearer_token` and a Basic pair - are set, and lists HTTP Digest for an `http_auth` it reads before its `env()` value resolves. + 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, where the build refuses Digest. (`BACKLOG #5526`) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 270f644407..bcfe82fa2c 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -3002,7 +3002,7 @@ follow-on and is **not** built. | `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()`). 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) | @@ -3024,8 +3024,8 @@ can decide the class, and a `` inside one ends its range, so `busysoap:Server` reads no code and dead-letters. The read, its fallback and the one shape read again are stated once, in the `_fault_code` docstring in [`transports/soap.py`](../messagefoundry/transports/soap.py). The -Fault is the first Fault start tag after the first Body start tag, or with no Fault after it the first -in the reply, each searched for outside terminated markup; only where every Fault start tag after that Body start tag (with none there, every +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 diff --git a/messagefoundry/config/static_credentials.py b/messagefoundry/config/static_credentials.py index 48410b3e11..9481470d8e 100644 --- a/messagefoundry/config/static_credentials.py +++ b/messagefoundry/config/static_credentials.py @@ -183,16 +183,24 @@ 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.""" + 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`` (``config.wiring._resolved_setting``). One this reading cannot resolve may + resolve to ``digest``, so it reads as Digest, as an unresolved ``oauth2_enabled`` reads as on, + except beside a minted bearer (``token``): the build refuses Digest there, so none crosses.""" from messagefoundry.transports.http_auth import HttpAuthError, http_digest_selected - if isinstance(settings.get("http_auth"), EnvRef): - # BACKLOG #5526 item 9: read before env() resolves, the mode is unknown, and it may resolve - # to 'digest', so it is listed, as an unresolved oauth2_enabled reads as on. - return True + mode = _resolved_setting(settings, "http_auth", None, env_values) + if mode is _UNRESOLVED: + return not token + if mode is not settings.get("http_auth"): + settings = {**settings, "http_auth": mode} try: return http_digest_selected(settings) except HttpAuthError as exc: @@ -205,8 +213,9 @@ def _digest(settings: Mapping[str, Any]) -> bool: def _static_authorization(settings: Mapping[str, Any]) -> list[str]: """The static credential the connector writes into its own ``Authorization`` header. With both - a ``bearer_token`` and a Basic pair set, REST, SOAP and DICOMweb refuse to build, and FHIR - sends Basic, so only Basic is listed (BACKLOG #5526 item 2).""" + a ``bearer_token`` and a Basic pair set, FHIR sends Basic, so only Basic is listed (BACKLOG + #5526 item 2). REST, SOAP and DICOMweb refuse to build on both, and Basic is listed for them + all the same: this reader does not take the connector type.""" if settings.get("basic_user") and settings.get("basic_password"): return ["HTTP Basic"] if settings.get("bearer_token"): @@ -214,7 +223,13 @@ def _static_authorization(settings: Mapping[str, Any]) -> list[str]: 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 @@ -228,7 +243,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 @@ -350,7 +365,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/transports/http_auth.py b/messagefoundry/transports/http_auth.py index bae0dbb5e9..360d5462df 100644 --- a/messagefoundry/transports/http_auth.py +++ b/messagefoundry/transports/http_auth.py @@ -518,8 +518,7 @@ def refuse_http_digest_conflicts(s: Mapping[str, Any]) -> bool: """Whether Digest is selected, after refusing what cannot stand beside it (BACKLOG #5529). The connectors call this at the top of construction, so a connection that will not build logs - no insecure-hop crossing or warning first; :func:`digest_handler_from_settings` calls it again - unless the caller passes the answer it already holds. + no insecure-hop crossing or warning first; :func:`digest_handler_from_settings` calls it again. Refuses an unrecognised ``http_auth`` (:func:`http_digest_selected`), and with Digest selected, a static ``bearer_token``, ``basic_user``, ``basic_password`` or ``Authorization`` entry in ``headers``: beside Digest, a connection configures exactly one HTTP credential. Where such a @@ -536,8 +535,7 @@ def refuse_http_digest_conflicts(s: Mapping[str, Any]) -> bool: _, (_, _, 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( @@ -583,12 +581,17 @@ def authorization_credential(s: Mapping[str, Any], *, digest: bool) -> str | Non return "HTTP Basic" if s.get("bearer_token"): return "a bearer_token" - 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): 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: @@ -597,6 +600,8 @@ def refuse_authorization_signer_beside_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 ) @@ -613,7 +618,7 @@ def _refuse_authorization_signer( def digest_handler_from_settings( - s: Mapping[str, Any], *, url: str, digest_selected: bool | None = None + s: Mapping[str, Any], *, url: str ) -> urllib.request.HTTPDigestAuthHandler | None: """An :class:`urllib.request.HTTPDigestAuthHandler` pre-loaded with the connection's credentials (BACKLOG #65, RFC 7616), or ``None`` when HTTP Digest auth is off (``http_auth`` unset, falsy @@ -626,13 +631,8 @@ def digest_handler_from_settings( through the rule the delivery cells' credentials share (``refuse_cleartext_credential_hop``): only a loopback host lifts it, never ``tls_hop_attested`` or ``cleartext_accepted`` (vault BACKLOG #3533 item 4). A missing user/password is a loud :class:`HttpAuthError` (fail-closed, never a silent - no-auth request). - - ``digest_selected`` is :func:`refuse_http_digest_conflicts`'s answer where the caller already - ran it on these settings, so it is not run twice per build (BACKLOG #5526 item 4); ``None``, the - default, runs it here.""" - selected = refuse_http_digest_conflicts(s) if digest_selected is None else digest_selected - if not selected: + no-auth request).""" + if not refuse_http_digest_conflicts(s): return None # The declarations are read strictly: a non-bool flag raises HttpAuthError naming the connection # (vault BACKLOG #2232), and the mirrored connection name heads the refusal below. diff --git a/messagefoundry/transports/soap.py b/messagefoundry/transports/soap.py index 668b7957bb..8c0d44f898 100644 --- a/messagefoundry/transports/soap.py +++ b/messagefoundry/transports/soap.py @@ -343,7 +343,11 @@ class of the Body's fault. The first Body start tag is taken even when it sits i return None, 0 # One scan from 0, so markup opened before the Body start tag is known after it. outside = _search_outside_markup(_FAULT_OUTSIDE_MARKUP_RE, body, 0, len(body)) - m = _search_outside_markup(_BODY_OUTSIDE_MARKUP_RE, body, 0, len(body)) + m = _BODY_RE.search(body) + if m is not None and (body.find("= 0 or body.find("= 0): + # Closing step 6: only markup opened ahead of the first plain Body start tag can hide it, + # so the Python-level step-over runs only then. + m = _search_outside_markup(_BODY_OUTSIDE_MARKUP_RE, body, 0, len(body)) if m is None: return outside or plain, 0 after = outside @@ -962,7 +966,7 @@ def __init__(self, config: Destination) -> None: # #65: or HTTP Digest folded into the opener. None (default) -> byte-identical. from messagefoundry.transports.http_auth import digest_handler_from_settings - digest = digest_handler_from_settings(s, url=self.url, digest_selected=digest_selected) + digest = digest_handler_from_settings(s, url=self.url) if digest is not None: # A bearer provider beside Digest was refused in refuse_http_digest_conflicts (#5529). if _is_shared_no_redirect_opener(self._opener): @@ -1426,8 +1430,9 @@ def _post_and_classify( Code close-tag search. The name scans still run, in :func:`_searched_code`, wherever that first-child read yields no code, as it does on a ```` followed by a run of ``<``; the PR 2936 repair moved the Fault start-tag search and the Fault and Code close-tag searches into :func:`_search_outside_markup`'s Python-level loop, which - a reply of many markup runs makes several times slower. So they are not a reading of this - code.""" + a reply of many markup runs makes several times slower, and BACKLOG #5912 closing step 6 + moved the Body start-tag search there too wherever a `` fragment; wrap + stamp here (post-queue # boundary), so the per-call MessageID and Timestamp never live in a pure transform. if self._ws_mode: diff --git a/tests/test_soap_5526_remainder.py b/tests/test_soap_5526_remainder.py index 3df0b26fc6..29720c8386 100644 --- a/tests/test_soap_5526_remainder.py +++ b/tests/test_soap_5526_remainder.py @@ -2,10 +2,10 @@ # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """BACKLOG #5526, the items left after engine PRs 2883 and 3144: one credential owns the ``Authorization`` header on SOAP, and a signing header does not replace it on SOAP or REST; the -static-credential census lists what is sent; and the Digest refusal runs once per SOAP build and -names the connection. Synthetic credentials only. +static-credential census lists what is sent; and the SOAP Digest refusal names the connection. +Synthetic credentials only. -Items 2, 4, 5, 6 and 9 are pinned here; each test names its item.""" +Items 2, 5, 6 and 9 are pinned here; each test names its item.""" from __future__ import annotations @@ -17,10 +17,10 @@ from messagefoundry.config.models import ConnectorType, Destination from messagefoundry.config.settings import EgressSettings -from messagefoundry.config.static_credentials import http_hop_credentials +from messagefoundry.config.static_credentials import _http_hop, http_hop_credentials from messagefoundry.config.tls_policy import MIRRORED_CONNECTION_SETTING from messagefoundry.config.wiring import EnvRef, Rest, Soap -from messagefoundry.transports import build_destination, http_auth +from messagefoundry.transports import build_destination from messagefoundry.transports.http_auth import ( HttpAuthError, is_authorization_header_name, @@ -163,33 +163,44 @@ def test_the_census_reads_an_unresolved_env_http_auth_as_digest() -> None: assert "HTTP Digest" not in http_hop_credentials(ConnectorType.REST, {"http_auth": "digset"}) -# --- items 4 and 5: the Digest refusal runs once on SOAP and names the connection -------------- +@pytest.mark.parametrize( + ("env_values", "listed"), + [({"MF_HTTP_AUTH_SYNTHETIC": "digest"}, True), ({"MF_HTTP_AUTH_SYNTHETIC": ""}, False)], + ids=["resolves-to-digest", "resolves-empty"], +) +def test_the_census_resolves_an_env_http_auth_against_the_values( + env_values: dict[str, str], listed: bool +) -> None: + """Item 9, review round 1: with the values the serve-time guard holds, the mode is read as + the build resolves it, so an empty one lists no Digest and a SOAP mTLS hop is not listed.""" + settings = { + "url": URL, + "http_auth": EnvRef("MF_HTTP_AUTH_SYNTHETIC"), + "client_cert_file": "client.pem", + } + hop = _http_hop("OB_SOAP", ConnectorType.SOAP, settings, "peer", env_values=env_values) + assert (hop is not None and "HTTP Digest" in hop.detail) is listed + if not listed: + assert hop is None -def test_the_digest_conflict_check_runs_once_per_soap_build( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Item 4: ``SoapDestination`` refused Digest conflicts at the top of its build and - ``digest_handler_from_settings`` refused them again. Control: the handler is still built.""" - calls: list[object] = [] - original = http_auth.refuse_http_digest_conflicts +def test_the_census_reads_no_digest_beside_a_minted_bearer() -> None: + """Item 9, review round 1: Digest beside an OAuth2 or SMART provider refuses the build, so an + unresolved ``env()`` ``http_auth`` there lists no Digest and the hop is not reported.""" + settings = _oauth(Rest(url=URL)).settings + settings["http_auth"] = EnvRef("MF_HTTP_AUTH_SYNTHETIC") + assert "HTTP Digest" not in http_hop_credentials(ConnectorType.REST, settings) + assert _http_hop("OB_REST", ConnectorType.REST, settings, "peer") is None - def counting(s: Any) -> bool: - calls.append(s) - return original(s) - monkeypatch.setattr(http_auth, "refuse_http_digest_conflicts", counting) - settings = with_http_digest(Soap(url=URL), user="u", password=_PW).settings - dest = _build(ConnectorType.SOAP, settings) - assert any(type(h).__name__ == "_ApprovedDigestAuthHandler" for h in dest._opener.handlers) - assert len(calls) == 1 +# --- item 5: the SOAP Digest refusal names the connection -------------------------------------- def test_a_soap_digest_refusal_names_the_connection_built_directly() -> None: """Item 5: the Digest refusals read the connection name the runner mirrors into the settings, while the rest of the SOAP build reads ``config.name``. A destination built without the runner - had no mirror, so its Digest refusal named no connection. Control: the mirror, where set, - is what the refusal names.""" + had no mirror, so its Digest refusal named no connection. Control: a mirror the runner set + is kept, so the refusal names it and not ``config.name``.""" settings = with_http_digest(Soap(url=URL, bearer_token=_TOKEN), user="u", password=_PW).settings assert MIRRORED_CONNECTION_SETTING not in settings with pytest.raises(HttpAuthError, match="beside a static credential") as ei: @@ -198,10 +209,11 @@ def test_a_soap_digest_refusal_names_the_connection_built_directly() -> None: with pytest.raises(HttpAuthError) as mirrored: _build( ConnectorType.SOAP, - {**settings, MIRRORED_CONNECTION_SETTING: "OB_SOAP_DIRECT"}, + {**settings, MIRRORED_CONNECTION_SETTING: "OB_SOAP_MIRRORED"}, name="OB_SOAP_DIRECT", ) - assert "OB_SOAP_DIRECT" in str(mirrored.value) + assert "OB_SOAP_MIRRORED" in str(mirrored.value) + assert "OB_SOAP_DIRECT" not in str(mirrored.value) def test_control_the_soap_build_does_not_alter_its_settings() -> None: diff --git a/tests/test_soap_fault_scan_linear.py b/tests/test_soap_fault_scan_linear.py index f63564822c..52ebf88d21 100644 --- a/tests/test_soap_fault_scan_linear.py +++ b/tests/test_soap_fault_scan_linear.py @@ -858,6 +858,7 @@ def test_the_fault_is_read_from_the_body( patched out the shape reads otherwise, as it did when the first Fault, and any WS-Security 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 From a990d367f6b4b9aa52e23927095c0dad1e2e8405 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:26:12 -0600 Subject: [PATCH 12/29] Store privilege probe: say when an OBSERVED over-grant with unread grants refuses Text only. The `unread` field comment and the SQL Server probe docstring said the start "still refuses" on what was read; it refuses under enforce with no accepted opt-out, and otherwise warns. From the unrepaired review round-2b283388df, finding 1. BACKLOG #6015. Proposed PR title: Store privilege probe: R2 added items for #6015 and #6714 (shared probed_grant, unread grants in the summary, db_securityadmin) Proposed banners: #6015 CLOSED: claim met by PR 2879; added items 2-8 built on branch w10-privilege; item 1 kept by design (the #1234 pin: an unread role or CONTROL grant makes the report UNOBSERVABLE even beside a read sysadmin). #6714 PARTIAL: added items 2-6 built on branch w10-privilege (item 1 by PR 2879); S01-68 reads met on main (owner_named counts CONTROL SERVER, and sysadmin alone among server roles). Left: a reviewed not-a-bug ruling on the headline (custom roles flagged by name, by design per DEPLOY-SERVER-DB.md 1.3, the Manager's reading). #6715 OPEN: nothing built. Left: per-process warning keys (a stable process identity for the bare `store` subject), a design item. --- messagefoundry/store/privilege.py | 5 +++-- messagefoundry/store/sqlserver.py | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/messagefoundry/store/privilege.py b/messagefoundry/store/privilege.py index d3a20c059a..71ac2aade9 100644 --- a/messagefoundry/store/privilege.py +++ b/messagefoundry/store/privilege.py @@ -482,8 +482,9 @@ class StorePrivilegeReport: 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, since what WAS read already refuses, and the summary - #: names them, so the log line and the alert do not imply the rest was read. Some UNOBSERVABLE + #: 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, ...] = () diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index c96ebd043b..271b7632d9 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -5191,8 +5191,8 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: 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 start - still refuses on what was read.""" + 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)) ] From 79439ec2a6546218ebb15612e3fa6a73bc70e237 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:34:47 -0600 Subject: [PATCH 13/29] FHIR headers: keep the dict-only table the census reads; name the lookup; spy control Review round-38fd7ea9a8 repairs. Both FHIR _build_headers read a dict again, as the static-credential census and the rotation watcher do, and _refuse_unsendable_static_headers refuses any other type, a Mapping that is not a dict included, so the wire and the census cannot disagree. A lookup's credential refusal now opens "FhirLookup '': ". The token-provider spy test gains its positive control. static_credentials.py's docstring no longer says REST and FHIR send nothing on one Basic half; both refuse. BACKLOG #8299, BACKLOG #5911. Proposed PR title: FHIR lookup gate order and static credential refusals (BACKLOG #8299, #5911) Proposed banner #8299: PARTIAL: items 2, 3, 6 and 8 built; item 4 built for cleartext http (a verify_tls=false SMART lookup still builds its provider first); item 9 first half; item 1 for fhir.py and rest.py. Left: item 1 soap.py and the refuse_http_digest_conflicts docstring (http_auth.py); item 5 (needs the http_auth.py docstring); item 4 verify-off half; item 7 residual; item 9 second half (SDS-3.5); items 10-25. Proposed banner #5911: MET on step 6: settings-row text in docs/CONNECTIONS.md; the changelog fragment is on main from PR 3144. Steps 3-5 and 7-11 as PR 3144 states. --- messagefoundry/config/static_credentials.py | 4 ++-- messagefoundry/transports/fhir.py | 19 ++++++++++--------- tests/test_fhir_lookup_gate_order.py | 10 +++++++++- 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/messagefoundry/config/static_credentials.py b/messagefoundry/config/static_credentials.py index 5ab5fc0030..4f758bf846 100644 --- a/messagefoundry/config/static_credentials.py +++ b/messagefoundry/config/static_credentials.py @@ -209,8 +209,8 @@ def _http_static(ctype: ConnectorType, settings: Mapping[str, Any], token: bool) 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 diff --git a/messagefoundry/transports/fhir.py b/messagefoundry/transports/fhir.py index d66d37d19c..2c232189d0 100644 --- a/messagefoundry/transports/fhir.py +++ b/messagefoundry/transports/fhir.py @@ -862,13 +862,14 @@ def _reject_config_control_chars(value: str, setting: str, where: str = "destina def _refuse_unsendable_static_headers( s: Mapping[str, Any], *, setting: str, connection: str | None ) -> None: - """Refuse at construction a static ``headers`` or credential ``_build_headers`` would drop or - replace without a word (BACKLOG #8299 item 8): a ``headers`` that is not a table, one Basic half - without the other, and ``bearer_token`` beside a Basic pair. The credential rules are REST's, - :func:`~messagefoundry.transports.rest._refuse_unsendable_static_auth`. Names settings, never a - value.""" + """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, Mapping): + 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" @@ -1413,7 +1414,7 @@ def _build_headers(self, s: dict[str, Any]) -> dict[str, str]: media = "application/fhir+json" # format is constrained to json in __init__ (XML deferred) headers: dict[str, str] = {"Content-Type": media, "Accept": media} extra = s.get("headers") or {} - if isinstance(extra, Mapping): + if isinstance(extra, dict): headers.update({str(k): str(v) for k, v in extra.items()}) token = s.get("bearer_token") if token: @@ -2223,7 +2224,7 @@ def _planned(cls, cname: str, s: Mapping[str, Any]) -> _LookupPlan: f"FhirLookup {cname!r} 'url' must be http or https, got scheme {scheme!r}" ) refuse_url_credentials(url, f"FhirLookup {cname!r} 'url'") - _refuse_unsendable_static_headers(s, setting=f"FhirLookup {cname!r}", connection=None) + _refuse_unsendable_static_headers(s, setting=f"FhirLookup {cname!r}:", connection=None) headers = cls._build_headers(s) refuse_unsendable_static_request(url, headers, setting=f"FhirLookup {cname!r}") # BACKLOG #5959: above zero, as REST's; positive_seconds says why. @@ -2266,7 +2267,7 @@ def _build_headers(s: Mapping[str, Any]) -> dict[str, str]: media = "application/fhir+json" headers: dict[str, str] = {"Accept": media} extra = s.get("headers") or {} - if isinstance(extra, Mapping): + if isinstance(extra, dict): headers.update({str(k): str(v) for k, v in extra.items()}) token = s.get("bearer_token") if token: diff --git a/tests/test_fhir_lookup_gate_order.py b/tests/test_fhir_lookup_gate_order.py index 289bf6da79..f7a620e452 100644 --- a/tests/test_fhir_lookup_gate_order.py +++ b/tests/test_fhir_lookup_gate_order.py @@ -11,6 +11,7 @@ import logging from collections.abc import Iterator +from types import MappingProxyType from typing import Any import pytest @@ -144,6 +145,11 @@ def test_the_static_credential_check_runs_before_the_token_provider_is_built( names = [name for name, _ in gates] assert "token_provider_from_settings" not in names assert "refuse_cleartext_credentials" in names + # The control: on https the cleartext check passes, and the spy sees the provider built. + gates.clear() + with pytest.raises(ValueError, match="signing-key file"): + _build({"smart": {**settings, "url": "https://fhir.partner.invalid/fhir"}}) + assert [name for name, _ in gates][-1] == "token_provider_from_settings" @pytest.mark.parametrize( @@ -152,6 +158,7 @@ def test_the_static_credential_check_runs_before_the_token_provider_is_built( ({"headers": ["X-Site", "1"]}, "'headers' must be a table"), ({"basic_user": "u"}, "basic_user and basic_password must be set together"), ({"headers": []}, "'headers' must be a table"), + ({"headers": MappingProxyType({"X-Site": "1"})}, "'headers' must be a table"), ({"basic_password": "p"}, "basic_user and basic_password must be set together"), ({"basic_user": "a:b", "basic_password": "p"}, "basic_user must not contain ':'"), ( @@ -163,6 +170,7 @@ def test_the_static_credential_check_runs_before_the_token_provider_is_built( "headers-list", "user-only", "headers-empty-list", + "headers-mapping-proxy", "password-only", "colon", "bearer-and-basic", @@ -175,7 +183,7 @@ def test_a_static_credential_the_lookup_would_drop_is_refused( in place of the bearer, without a word.""" with pytest.raises(ValueError, match=match) as ei: _build({"epic": {"url": "https://fhir.partner.invalid/fhir", **over}}) - assert "FhirLookup 'epic'" in str(ei.value) or "fhir_lookup:epic" in str(ei.value) + assert str(ei.value).startswith("FhirLookup 'epic': ") @pytest.mark.parametrize( From ff4bba43d65c8b06ffa57345314f3acbdb134b9e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:34:47 -0600 Subject: [PATCH 14/29] Row seal: Transit sealer refuses non-finite floats and reads a non-text seal as malformed (BACKLOG #6717, #6718) Review round 2 repairs: the changelog fragment takes the bullet form the fragment check reads; the module docstring says plainly that seal_bytes callers (at least passkey_digest) encode a non-finite float without refusing it; the require_seal_for_write comment names the malformed-seal case; the Transit non-text test uses a fresh sealer so no cached answer stands in, and covers int and float cells; the session BLOB refusal asserts its args. BACKLOG #6717, #6718 Proposed PR title: Row seal: Transit sealer refuses non-finite floats and reads a non-text seal as malformed (BACKLOG #6717, #6718) Proposed banners: #6717 PARTIAL: Transit sealer refuses NaN/inf as the local one does, both through NonFiniteSealValueError; items 2-8 fixed, item 1 kept in one line (passkey_digest hashes values read back from the store). Left: item 9, a finite check in the keyless store's record builders (store.py). #6718 MET: item 1 met on main (session_seal_ok uses _encodes), items 2 and 3 fixed with tests (TransitRowSealer._parse reads non-text as malformed). --- .../6717-row-seal-transit-non-finite.fixed.md | 11 ++++++----- messagefoundry/store/row_seal.py | 9 +++++---- tests/test_row_seal_followups.py | 16 ++++++++++------ tests/test_transit_row_seal.py | 3 ++- 4 files changed, 23 insertions(+), 16 deletions(-) diff --git a/changelog.d/6717-row-seal-transit-non-finite.fixed.md b/changelog.d/6717-row-seal-transit-non-finite.fixed.md index 72cf073f64..6c50d917b8 100644 --- a/changelog.d/6717-row-seal-transit-non-finite.fixed.md +++ b/changelog.d/6717-row-seal-transit-non-finite.fixed.md @@ -1,5 +1,6 @@ -Row seals: the Vault Transit row sealer 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. -The Transit sealer reads a stored seal that is not text (a blob or a number) as malformed rather -than raising, so a write over such a session row is refused as a failed seal (BACKLOG #6717, -#6718). The bytes a seal covers are unchanged. +- **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/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index 1711b9793b..4b7dee4197 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -35,9 +35,9 @@ ``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, so a check over a row someone set to such -a value fails rather than raises, and so does a digest built on the encoder, such as the store's -``passkey_digest`` (BACKLOG #6717). +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 @@ -1021,7 +1021,8 @@ async def require_seal_for_write( 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/tests/test_row_seal_followups.py b/tests/test_row_seal_followups.py index 04489518ce..19ce1a1152 100644 --- a/tests/test_row_seal_followups.py +++ b/tests/test_row_seal_followups.py @@ -94,8 +94,8 @@ async def test_the_transit_sealer_refuses_a_float_that_is_not_finite(value: floa @pytest.mark.parametrize( "as_type", - [lambda s: s.encode("ascii"), lambda s: bytearray(s, "ascii")], - ids=["bytes", "bytearray"], + [lambda s: s.encode("ascii"), lambda s: bytearray(s, "ascii"), lambda s: 7, lambda s: 7.5], + ids=["bytes", "bytearray", "int", "float"], ) async def test_a_transit_seal_that_is_not_text_fails_every_check_without_raising( as_type: Callable[[str], Any], @@ -111,12 +111,16 @@ async def test_a_transit_seal_that_is_not_text_fails_every_check_without_raising assert await sealer.verify_async(SESSION_KIND, fields, stored) assert await sealer.verify_held_async(SESSION_KIND, fields, stored) assert await sealer.sealed_by_retired_key_async(SESSION_KIND, fields, old_stored) + # A fresh sealer on the same backend, so no answer cached by the controls can stand in. + fresh = TransitRowSealer(backend, clock=Clock(), retired_key_names=[RETIRED]) calls = backend.verify_calls - assert not sealer.is_active(as_type(stored)) - assert not await sealer.verify_async(SESSION_KIND, fields, as_type(stored)) - assert not await sealer.verify_held_async(SESSION_KIND, fields, as_type(stored)) - assert not await sealer.sealed_by_retired_key_async(SESSION_KIND, fields, as_type(old_stored)) + assert not fresh.is_active(as_type(stored)) + assert not await fresh.verify_async(SESSION_KIND, fields, as_type(stored)) + assert not await fresh.verify_held_async(SESSION_KIND, fields, as_type(stored)) + assert not await fresh.sealed_by_retired_key_async(SESSION_KIND, fields, as_type(old_stored)) assert backend.verify_calls == calls # read as malformed, with no Transit call + assert await fresh.verify_async(SESSION_KIND, fields, stored) # control: fresh does call + assert backend.verify_calls == calls + 1 async def test_a_session_row_whose_seal_cell_is_a_blob_fails_its_check_on_transit() -> None: diff --git a/tests/test_transit_row_seal.py b/tests/test_transit_row_seal.py index 62c2bd1a2c..d46283d6e5 100644 --- a/tests/test_transit_row_seal.py +++ b/tests/test_transit_row_seal.py @@ -471,8 +471,9 @@ async def test_require_seal_for_write_names_each_cause() -> None: blob: Any = stored.encode() with pytest.raises(RowSealError): await require_seal_for_write(sealer, USER_KIND, FIELDS, blob, subject=subject) - with pytest.raises(RowSealError): + 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: From 6dae8c1f70b83472614cfa88caae60680b023a4a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:40:01 -0600 Subject: [PATCH 15/29] Transit key names: review round-7c12744659 repairs (BACKLOG #6010, #6710) - The unset KEK / wrapped DEK refusal is unrecorded again, as on main: recording it broke three tests that pin the key seam's fixed text for that case (test_audit_keyless_chain_flagged, test_provision_first_administrator). Its test is dropped. - verify_seal_hmac uses is_transit_key_name, a predicate beside checked_transit_key_name, rather than build and drop a refusal. - tls_policy CA paragraph links the _ENV_CA_FILE comment instead of restating the variable list (SDS-3.5). Proposed PR title: Transit key names: one read, checked at each use, refusal text kept (BACKLOG #6010, #6710) Proposed banners: #6010 MET. The claim and item 1 were met by PR 2879; items 2 to 13 are met by this PR. #6710 PARTIAL. Item 3 met by this PR. Left: item 1 (cache, a decision owed; the event-loop cost is #5888), item 2 (wrapped retired DEKs, a design change), item 4 (shape check at base._checked_active_key, in store/base.py, which open PR 3164 edits). --- .../6010-transit-key-name-refusals.fixed.md | 5 ++--- messagefoundry/config/tls_policy.py | 11 +++++------ messagefoundry/store/crypto_transit.py | 9 ++------- messagefoundry/store/keyprovider_vault.py | 11 ++++++++--- tests/test_keyprovider_vault.py | 16 ---------------- 5 files changed, 17 insertions(+), 35 deletions(-) diff --git a/changelog.d/6010-transit-key-name-refusals.fixed.md b/changelog.d/6010-transit-key-name-refusals.fixed.md index f7d0d3a8ee..0049d98be8 100644 --- a/changelog.d/6010-transit-key-name-refusals.fixed.md +++ b/changelog.d/6010-transit-key-name-refusals.fixed.md @@ -1,8 +1,7 @@ - **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`, of an unset KEK name or - wrapped DEK under `key_provider = "vault"`, and of an unwrapped DEK that is not base64 of 32 - bytes now reach the operator as written, naming the variable to fix, where a store open used to + `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. diff --git a/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index 81bf0cc452..f7fb0342c0 100644 --- a/messagefoundry/config/tls_policy.py +++ b/messagefoundry/config/tls_policy.py @@ -3551,12 +3551,11 @@ def requests_verify_from_anchor(anchor: TrustAnchor, *, cell: str) -> str | None Worth stating plainly, because the direction is counter-intuitive: this hop is not one of the broadly-trusting ones by default. With no anchor passed, hvac and ``requests`` choose the CA - from the process environment, at least hvac's ``VAULT_CACERT`` or ``VAULT_CAPATH``, then - ``requests``' ``REQUESTS_CA_BUNDLE`` or ``CURL_CA_BUNDLE``, and only when none is set do they - fall back to ``requests``' PUBLIC certifi bundle, not the OS store. So an internal-CA Vault - fails closed unless one of those variables names a bundle or directory holding its CA, and - then whatever that names is what the hop trusts. What was missing here is the ability to name this hop's CA in - the engine's own setting. + 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/store/crypto_transit.py b/messagefoundry/store/crypto_transit.py index 66ccf692a4..352a8eec2e 100644 --- a/messagefoundry/store/crypto_transit.py +++ b/messagefoundry/store/crypto_transit.py @@ -94,6 +94,7 @@ _recorded_refusal, _vault_ca_kwargs, checked_transit_key_name, + is_transit_key_name, is_vault_bad_request, is_vault_forbidden, is_vault_timeout_reply, @@ -1388,13 +1389,7 @@ def verify_seal_hmac(self, key_name: str, digest: bytes, mac: str) -> object: ``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).""" - try: - checked_transit_key_name(key_name, selector="the row seal's key name") - except KeyProviderError: - refused_name = True - else: - refused_name = False - if refused_name: + 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" ) diff --git a/messagefoundry/store/keyprovider_vault.py b/messagefoundry/store/keyprovider_vault.py index bd99f0847d..807e35fbcf 100644 --- a/messagefoundry/store/keyprovider_vault.py +++ b/messagefoundry/store/keyprovider_vault.py @@ -591,8 +591,7 @@ def active_key(self) -> str | None: ) if not value ] - # Built from variable names alone, so recorded: the key seam keeps it (BACKLOG #6010). - raise _recorded_refusal( + raise KeyProviderError( f"[store].key_provider={_EXTRA!r} is selected but {', '.join(missing)} is not set — " f"supply the Transit KEK name and the wrapped DEK via the environment." ) @@ -741,6 +740,12 @@ def _recorded_refusal(text: str) -> KeyProviderError: 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). @@ -749,7 +754,7 @@ def checked_transit_key_name(name: str, *, selector: str) -> str: 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; it is recorded, so the store's fixed-text seams keep it (BACKLOG #6010 item 3).""" - if _TRANSIT_KEY_NAME.fullmatch(name) is None: + 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 " diff --git a/tests/test_keyprovider_vault.py b/tests/test_keyprovider_vault.py index 6da3fc4c7b..a130ea0cce 100644 --- a/tests/test_keyprovider_vault.py +++ b/tests/test_keyprovider_vault.py @@ -381,22 +381,6 @@ def _refuse(addr: str, token: str, **_: Any) -> _FakeClient: monkeypatch.setattr(keyprovider_vault, "_build_client", _refuse) -def test_an_unset_kek_setting_keeps_its_text_at_the_key_seam( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """The refusal of an unset KEK name or wrapped DEK is built from the variables' names alone, - so it is recorded too, and the key seam keeps it (BACKLOG #6010 item 3).""" - from messagefoundry.store.base import resolve_active_key - - _no_client_built(monkeypatch) - monkeypatch.delenv("MEFOR_STORE_VAULT_TRANSIT_KEY", raising=False) - monkeypatch.delenv("MEFOR_STORE_VAULT_WRAPPED_DEK", raising=False) - with pytest.raises(KeyProviderError) as excinfo: - resolve_active_key(StoreSettings(key_provider="vault")) - text = str(excinfo.value) - assert "MEFOR_STORE_VAULT_TRANSIT_KEY, MEFOR_STORE_VAULT_WRAPPED_DEK is not set" in text - - def test_a_malformed_kek_name_keeps_its_text_at_the_key_seam( monkeypatch: pytest.MonkeyPatch, ) -> None: From 10fb68d98a739018dba4eb319c717a5aee08d897 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:48:11 -0600 Subject: [PATCH 16/29] Review round 2: census env() flags and defaults, XML declaration fast path Repairs from code-review round-6ccae380b2 (BACKLOG #5912, #5526): - The census reads an env() http_auth default as the headers reader does, and an unresolved one as Digest beside a bearer whose flag is itself an env() value; the docstring and changelog premise now say so. - The Body anchor fast path ignores a leading XML declaration. - The 5912 changelog states the WS-Security change of closing step 6, and both pointers name _child_code_text beside _fault_code. - The module effect list names _digest's env() cast. Proposed PR title: SOAP fault anchor and blank code; one Authorization owner beside a signer (BACKLOG #5912, #5526) Proposed banners: #5912 PARTIAL: closing steps 5, 6 (Body-anchor half), 9, 11, 13 (ADR half), 17 and the _FAULT_TAG_IN_MARKUP half of 24 met on branch w10-soap. Left: steps 8, 18 and 22, parity-with-main trades that close on a fix or the owner's acceptance by name; step 6's second half is step 22's shape. #5526 PARTIAL: items 2, 5 (SOAP), 6 (SOAP and REST), 9, 11 and 12 built on branch w10-soap; items 7, 8, 14 to 22 met on main; item 10 kept by design (ADR 0015 amendment 2026-11-10); filing finding 2 is item 6. Left: item 1's FHIR half; item 4, kept in one line (the second Digest refusal run stays, since skipping it behind a caller flag would make a security refusal optional); item 5's REST and FHIR twins; item 6's FHIR twin; item 13 and filing finding 1 (FTPS, #5530). --- changelog.d/5526-remainder.security.md | 3 +- changelog.d/5912.security.md | 9 ++++-- docs/CONNECTIONS.md | 3 +- messagefoundry/config/static_credentials.py | 20 +++++++----- messagefoundry/transports/http_auth.py | 1 - messagefoundry/transports/soap.py | 12 ++++++-- tests/test_soap_5526_remainder.py | 21 +++++++++++++ tests/test_soap_5912_closing_steps.py | 34 +++++++++++++++++++++ 8 files changed, 86 insertions(+), 17 deletions(-) diff --git a/changelog.d/5526-remainder.security.md b/changelog.d/5526-remainder.security.md index 01b164f2b0..5cc474d492 100644 --- a/changelog.d/5526-remainder.security.md +++ b/changelog.d/5526-remainder.security.md @@ -8,5 +8,6 @@ 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, where the build refuses Digest. + except beside an OAuth2 or SMART provider whose own flag is not an `env()` value, since the + build refuses Digest beside a bearer provider. (`BACKLOG #5526`) diff --git a/changelog.d/5912.security.md b/changelog.d/5912.security.md index e12ada1bed..8c19f2b41f 100644 --- a/changelog.d/5912.security.md +++ b/changelog.d/5912.security.md @@ -9,7 +9,8 @@ markup, so there a `Value` outside the Code, or inside a comment, still decides the class as in the shipped code, and a Sender fault of such a shape may still retry. A code element that holds only whitespace now falls back as an empty one does. The read, its fallback and the one shape - read again are stated once, in the `_fault_code` docstring in `messagefoundry/transports/soap.py`. + read again are stated once, in the `_fault_code` and `_child_code_text` docstrings in + `messagefoundry/transports/soap.py`. The Fault search, the Body start-tag search it starts from, and the Fault and Code close-tag searches that bound the first-child read step over terminated comments, CDATA sections and processing instructions, so a Body or Fault start tag, or a `` or ``, inside such @@ -17,6 +18,8 @@ `_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. Unchanged: whether a Fault counts, and that the WS-Security - check searches the reply from where the Fault search starts. + 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/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index bcfe82fa2c..74d853ca39 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -3023,7 +3023,8 @@ before BACKLOG #5912. That fallback steps over no markup: a `faultcode` or `Valu can decide the class, and a `` inside one ends its range, so `busysoap:Server` reads no code and dead-letters. The read, its fallback and the one shape read again are stated once, -in the `_fault_code` docstring in [`transports/soap.py`](../messagefoundry/transports/soap.py). The +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 diff --git a/messagefoundry/config/static_credentials.py b/messagefoundry/config/static_credentials.py index 9481470d8e..8884d0200e 100644 --- a/messagefoundry/config/static_credentials.py +++ b/messagefoundry/config/static_credentials.py @@ -81,9 +81,9 @@ :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 +at debug a proxy target that does not parse; and ``_http_literal_static`` (BACKLOG #5510), +``_dicomweb_build_refused`` (vault BACKLOG #5359) and ``_digest`` (BACKLOG #5526 item 9), 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()``. @@ -191,14 +191,18 @@ def _digest( 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`` (``config.wiring._resolved_setting``). One this reading cannot resolve may - resolve to ``digest``, so it reads as Digest, as an unresolved ``oauth2_enabled`` reads as on, - except beside a minted bearer (``token``): the build refuses Digest there, so none crosses.""" + ``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 are not themselves ``env()`` references: the build refuses Digest beside a + bearer provider, so none crosses there. Where such a flag is an ``env()`` reference, the + provider may resolve off, so the mode still reads as Digest.""" from messagefoundry.transports.http_auth import HttpAuthError, http_digest_selected - mode = _resolved_setting(settings, "http_auth", None, env_values) + mode = _resolved_setting(settings, "http_auth", None, env_values or {}) if mode is _UNRESOLVED: - return not token + flags = (settings.get("oauth2_enabled"), settings.get("smart_enabled")) + return not token or any(isinstance(flag, EnvRef) for flag in flags) if mode is not settings.get("http_auth"): settings = {**settings, "http_auth": mode} try: diff --git a/messagefoundry/transports/http_auth.py b/messagefoundry/transports/http_auth.py index 360d5462df..7c55b035f3 100644 --- a/messagefoundry/transports/http_auth.py +++ b/messagefoundry/transports/http_auth.py @@ -78,7 +78,6 @@ "BearerTokenProvider", "HttpAuthError", "OAuth2ClientCredentialsProvider", - "authorization_credential", "bearer_provider_from_settings", "digest_handler_from_settings", "http_digest_selected", diff --git a/messagefoundry/transports/soap.py b/messagefoundry/transports/soap.py index 8c0d44f898..4460537e75 100644 --- a/messagefoundry/transports/soap.py +++ b/messagefoundry/transports/soap.py @@ -344,10 +344,16 @@ class of the Body's fault. The first Body start tag is taken even when it sits i # One scan from 0, so markup opened before the Body start tag is known after it. outside = _search_outside_markup(_FAULT_OUTSIDE_MARKUP_RE, body, 0, len(body)) m = _BODY_RE.search(body) - if m is not None and (body.find("= 0 or body.find("= 0): + if m is not None: # Closing step 6: only markup opened ahead of the first plain Body start tag can hide it, - # so the Python-level step-over runs only then. - m = _search_outside_markup(_BODY_OUTSIDE_MARKUP_RE, body, 0, len(body)) + # so the Python-level step-over runs only then. A leading XML declaration that ends before + # that tag hides nothing, so it alone does not count (most replies open with one). + head = 0 + if body.startswith("", 0, m.start()) + head = 0 if decl_end < 0 else decl_end + 2 + if body.find("= 0 or body.find("= 0: + m = _search_outside_markup(_BODY_OUTSIDE_MARKUP_RE, body, 0, len(body)) if m is None: return outside or plain, 0 after = outside diff --git a/tests/test_soap_5526_remainder.py b/tests/test_soap_5526_remainder.py index 29720c8386..5a3bd7dc7f 100644 --- a/tests/test_soap_5526_remainder.py +++ b/tests/test_soap_5526_remainder.py @@ -193,6 +193,27 @@ def test_the_census_reads_no_digest_beside_a_minted_bearer() -> None: assert _http_hop("OB_REST", ConnectorType.REST, settings, "peer") is None +def test_the_census_reads_digest_beside_a_bearer_whose_flag_is_from_env() -> None: + """Item 9, review round 2: an ``env()`` ``oauth2_enabled`` may resolve off, so the provider + may not be built and Digest may cross; an unresolved ``http_auth`` there still reads as + Digest. Control: the literal flag in the test above lists none.""" + settings = _oauth(Rest(url=URL)).settings + settings["http_auth"] = EnvRef("MF_HTTP_AUTH_SYNTHETIC") + settings["oauth2_enabled"] = EnvRef("MF_OAUTH_ON_SYNTHETIC") + assert "HTTP Digest" in http_hop_credentials(ConnectorType.REST, settings) + + +def test_the_census_honours_an_env_default_for_http_auth() -> None: + """Item 9, review round 2: with no values, an ``env()`` ``default=`` is read, as the headers + reader reads it, so a default of no auth lists no Digest on an mTLS SOAP hop.""" + settings = { + "url": URL, + "http_auth": EnvRef("MF_HTTP_AUTH_SYNTHETIC", default=""), + "client_cert_file": "client.pem", + } + assert _http_hop("OB_SOAP", ConnectorType.SOAP, settings, "peer") is None + + # --- item 5: the SOAP Digest refusal names the connection -------------------------------------- diff --git a/tests/test_soap_5912_closing_steps.py b/tests/test_soap_5912_closing_steps.py index 7d02aa4b19..676f21dfd7 100644 --- a/tests/test_soap_5912_closing_steps.py +++ b/tests/test_soap_5912_closing_steps.py @@ -173,3 +173,37 @@ def test_a_close_tag_inside_the_fault_start_tag_still_ends_the_fallback_range() 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" From 65b3d1571916b07d701682383cb7d5e5267ea516 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 12:02:34 -0600 Subject: [PATCH 17/29] FhirLookup refusals this row added name the lookup the scrub-safe way The static-credential and length refusals a FhirLookup raises now open "connection 'fhir_lookup:'; FhirLookup ..." through hop_name_prefix, so a lookup named with a credential word (EPIC_TOKEN) no longer makes the log scrubber redact the rest of the message. The length check moves into one helper, _bounded_lookup_request, used before any gate and after the proxy header. _refuse_unsendable_static_auth's docstring now says the Digest refusal before it applies to the REST and FHIR destinations, and that FhirLookup calls no Digest check and builds no Digest handler. Red first: the 15 cases of test_a_lookup_refusal_survives_the_credential_scrubber fail on 79439ec2a65. BACKLOG #8299, BACKLOG #5911. Proposed PR title: FHIR lookup gate order and static credential refusals (BACKLOG #8299, #5911) Proposed banner #8299: PARTIAL: items 2, 3, 6 and 8 built; item 4 built for cleartext http (a verify_tls=false SMART lookup still builds its provider first); item 9 first half; item 1 for fhir.py and rest.py. Left: item 1 soap.py and the refuse_http_digest_conflicts docstring (http_auth.py); item 5 (needs the http_auth.py docstring); item 4 verify-off half; item 7 residual; item 9 second half (SDS-3.5); items 10-25. Proposed banner #5911: MET on step 6: settings-row text in docs/CONNECTIONS.md; the changelog fragment is on main from PR 3144. Steps 3-5 and 7-11 as PR 3144 states. --- messagefoundry/transports/fhir.py | 27 +++++++++++++++-------- messagefoundry/transports/rest.py | 6 +++-- tests/test_fhir_lookup_gate_order.py | 33 +++++++++++++++++++++++++--- 3 files changed, 52 insertions(+), 14 deletions(-) diff --git a/messagefoundry/transports/fhir.py b/messagefoundry/transports/fhir.py index 2c232189d0..97d559be88 100644 --- a/messagefoundry/transports/fhir.py +++ b/messagefoundry/transports/fhir.py @@ -2009,6 +2009,15 @@ 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.""" @@ -2117,10 +2126,7 @@ def __init__( 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. - try: - enforce_outbound_length_limits(url, headers) - except ValueError as exc: - raise ValueError(f"FhirLookup {cname!r}: {exc}") from exc + _bounded_lookup_request(url, headers, label) # The read sends Authorization (static or SMART) — refuse it over cleartext http. # 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. @@ -2224,7 +2230,10 @@ def _planned(cls, cname: str, s: Mapping[str, Any]) -> _LookupPlan: f"FhirLookup {cname!r} 'url' must be http or https, got scheme {scheme!r}" ) refuse_url_credentials(url, f"FhirLookup {cname!r} 'url'") - _refuse_unsendable_static_headers(s, setting=f"FhirLookup {cname!r}:", connection=None) + # 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}") # BACKLOG #5959: above zero, as REST's; positive_seconds says why. @@ -2239,12 +2248,12 @@ def _planned(cls, cname: str, s: Mapping[str, Any]) -> _LookupPlan: # 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). + # 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. + _bounded_lookup_request(url, headers, label) # Vault BACKLOG #3139: a refusal from either reader names the lookup, as the url checks do. try: - # 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) attested = hop_attestation_from_settings(s) accepted, reason, _ = cleartext_acceptance_from_settings(s) # FhirLookupSpec refuses an acceptance or a revocation attestation with no reason, diff --git a/messagefoundry/transports/rest.py b/messagefoundry/transports/rest.py index c1ad263d79..9777e8d6f2 100644 --- a/messagefoundry/transports/rest.py +++ b/messagefoundry/transports/rest.py @@ -2920,8 +2920,10 @@ def _refuse_unsendable_static_auth( 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): diff --git a/tests/test_fhir_lookup_gate_order.py b/tests/test_fhir_lookup_gate_order.py index f7a620e452..f3253fbd22 100644 --- a/tests/test_fhir_lookup_gate_order.py +++ b/tests/test_fhir_lookup_gate_order.py @@ -112,7 +112,7 @@ def test_a_lookup_refused_by_a_pure_check_leaves_no_crossing_from_an_earlier_loo """Items 2, 3 and 6: the first lookup crosses in cleartext, the second fails a check that needs no I/O, so no gate runs for either and nothing is recorded.""" caplog.set_level(logging.WARNING) - with pytest.raises(ValueError, match="FhirLookup 'second'"): + with pytest.raises(ValueError, match="FhirLookup 'second'|'fhir_lookup:second'"): _build({"first": dict(_FIRST), "second": bad}) assert gates == [] assert _crossed(caplog, "first.partner.invalid") == [] @@ -122,7 +122,9 @@ def test_an_over_length_lookup_is_refused_before_its_own_gates_and_named( gates: list[tuple[str, str]], ) -> None: """Items 2 and 9: the length refusal names the lookup and runs before its hop gates.""" - with pytest.raises(ValueError, match=r"^FhirLookup 'big': outbound header 'X-Pad'"): + with pytest.raises( + ValueError, match=r"^connection 'fhir_lookup:big'; FhirLookup outbound header 'X-Pad'" + ): _build( {"big": {"url": "https://big.partner.invalid/fhir", "headers": {"X-Pad": "a" * 9000}}} ) @@ -183,7 +185,7 @@ def test_a_static_credential_the_lookup_would_drop_is_refused( in place of the bearer, without a word.""" with pytest.raises(ValueError, match=match) as ei: _build({"epic": {"url": "https://fhir.partner.invalid/fhir", **over}}) - assert str(ei.value).startswith("FhirLookup 'epic': ") + assert str(ei.value).startswith("connection 'fhir_lookup:epic'; FhirLookup ") @pytest.mark.parametrize( @@ -232,3 +234,28 @@ def test_the_fhir_destination_refuses_the_same_dropped_credentials( def test_the_control_the_fhir_destination_still_builds_a_whole_credential() -> None: assert _destination(basic_user="u", basic_password="p", headers={"X-Site": "1"}) + + +@pytest.mark.parametrize( + "over", + [ + {"headers": ["X-Site", "1"]}, + {"basic_user": "u"}, + {"basic_user": "a:b", "basic_password": "p"}, + {"basic_user": "u", "basic_password": "p", "bearer_token": "t"}, + {"headers": {"X-Pad": "a" * 9000}}, + ], + ids=["headers-list", "user-only", "colon", "bearer-and-basic", "over-length"], +) +@pytest.mark.parametrize("name", ["EPIC_TOKEN", "epic_api_key", "PARTNER_PASSWORD"]) +def test_a_lookup_refusal_survives_the_credential_scrubber(over: dict[str, Any], name: str) -> None: + """The refusals this row added name the lookup the scrub-safe way, ``connection ''; `` + (hop_name_prefix), so a lookup named with a credential word does not redact the rest of the + message in the log.""" + from messagefoundry.secretscrub import scrub_credentials + + with pytest.raises(ValueError) as ei: + _build({name: {"url": "https://fhir.partner.invalid/fhir", **over}}) + text = str(ei.value) + assert text.startswith(f"connection 'fhir_lookup:{name}'; ") + assert scrub_credentials(text) == text From 01aa5f602bc57788dc9ea1439a1d33843d80fc97 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 12:21:01 -0600 Subject: [PATCH 18/29] FhirLookup: put the length-gate comment beside its call; scrubber test control Review round-ab481f0dfc text and test repairs. The #200 and ADR 0153 comments sit back beside the attestation readers they describe, and the ASVS 4.2.5 line no longer says the destination is fhir.py's only call site. The scrubber test now shows the old "FhirLookup '': " shape is redacted, so its pass is not vacuous. BACKLOG #8299, BACKLOG #5911. Proposed PR title: FHIR lookup gate order and static credential refusals (BACKLOG #8299, #5911) Proposed banner #8299: PARTIAL: items 2, 3, 6 and 8 built; item 4 built for cleartext http (a verify_tls=false SMART lookup still builds its provider first); item 9 first half; item 1 for fhir.py and rest.py. Left: item 1 soap.py and the refuse_http_digest_conflicts docstring (http_auth.py); item 5 (needs the http_auth.py docstring); item 4 verify-off half; item 7 residual; item 9 second half (SDS-3.5); items 10-25. Proposed banner #5911: MET on step 6: settings-row text in docs/CONNECTIONS.md; the changelog fragment is on main from PR 3144. Steps 3-5 and 7-11 as PR 3144 states. --- messagefoundry/transports/fhir.py | 7 +++---- tests/test_fhir_lookup_gate_order.py | 3 +++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/messagefoundry/transports/fhir.py b/messagefoundry/transports/fhir.py index 97d559be88..dcdd204c56 100644 --- a/messagefoundry/transports/fhir.py +++ b/messagefoundry/transports/fhir.py @@ -2242,16 +2242,15 @@ def _planned(cls, cname: str, s: Mapping[str, Any]) -> _LookupPlan: 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). - # 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. - _bounded_lookup_request(url, headers, label) # Vault BACKLOG #3139: a refusal from either reader names the lookup, as the url checks do. try: attested = hop_attestation_from_settings(s) diff --git a/tests/test_fhir_lookup_gate_order.py b/tests/test_fhir_lookup_gate_order.py index f3253fbd22..63051a3072 100644 --- a/tests/test_fhir_lookup_gate_order.py +++ b/tests/test_fhir_lookup_gate_order.py @@ -259,3 +259,6 @@ def test_a_lookup_refusal_survives_the_credential_scrubber(over: dict[str, Any], text = str(ei.value) assert text.startswith(f"connection 'fhir_lookup:{name}'; ") assert scrub_credentials(text) == text + # The control: the scrubber does redact the shape these refusals used before. + old = f"FhirLookup '{name}': basic_user and basic_password must be set together" + assert scrub_credentials(old) != old From cef0ce998ee560554a5647d981ff6bb7ed2b58b2 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 12:35:52 -0600 Subject: [PATCH 19/29] Census: an env() token URL may resolve a bearer provider off Round-3 findings 1 and 3 (BACKLOG #5526 item 9): _digest reads an unresolved env() http_auth as Digest beside a bearer provider whose token URL is an env() value too, since an empty URL leaves the provider off and Digest crosses. The changelog sentence and the module effect list now say what _digest and http_hop_credentials resolve. Proposed PR title: SOAP fault anchor and blank code; one Authorization owner beside a signer (BACKLOG #5912, #5526) Proposed banners: #5912 PARTIAL: closing steps 5, 6 (Body-anchor half), 9, 11, 13 (ADR half), 17 and the _FAULT_TAG_IN_MARKUP half of 24 met on branch w10-soap. Left: steps 8, 18 and 22, parity-with-main trades that close on a fix or the owner's acceptance by name; step 6's second half is step 22's shape. #5526 PARTIAL: items 2, 5 (SOAP), 6 (SOAP and REST), 9, 11 and 12 built on branch w10-soap; items 7, 8, 14 to 22 met on main; item 10 kept by design (ADR 0015 amendment 2026-11-10); filing finding 2 is item 6. Left: item 1's FHIR half; item 4, kept in one line (the second Digest refusal run stays, since skipping it behind a caller flag would make a security refusal optional); item 5's REST and FHIR twins; item 6's FHIR twin; item 13 and filing finding 1 (FTPS, #5530). --- changelog.d/5526-remainder.security.md | 5 ++-- messagefoundry/config/static_credentials.py | 27 ++++++++++++--------- tests/test_soap_5526_remainder.py | 18 ++++++++++++++ 3 files changed, 37 insertions(+), 13 deletions(-) diff --git a/changelog.d/5526-remainder.security.md b/changelog.d/5526-remainder.security.md index 5cc474d492..0fd7305fea 100644 --- a/changelog.d/5526-remainder.security.md +++ b/changelog.d/5526-remainder.security.md @@ -8,6 +8,7 @@ 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 own flag is not an `env()` value, since the - build refuses Digest beside a bearer provider. + except beside an OAuth2 or SMART provider whose enabled flag and token URL are both literal, + since the build refuses Digest beside a bearer provider; an `env()` flag or token URL may + resolve the provider off. (`BACKLOG #5526`) diff --git a/messagefoundry/config/static_credentials.py b/messagefoundry/config/static_credentials.py index 8884d0200e..fab92f7b47 100644 --- a/messagefoundry/config/static_credentials.py +++ b/messagefoundry/config/static_credentials.py @@ -80,12 +80,14 @@ 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), -``_dicomweb_build_refused`` (vault BACKLOG #5359) and ``_digest`` (BACKLOG #5526 item 9), 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`` against its ``default=``, which can run an +operator ``cast`` too. **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 @@ -194,15 +196,18 @@ def _digest( ``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 are not themselves ``env()`` references: the build refuses Digest beside a - bearer provider, so none crosses there. Where such a flag is an ``env()`` reference, the - provider may resolve off, so the mode still reads as Digest.""" + OAuth2 flags and token URLs are not themselves ``env()`` references: the build refuses Digest + beside a bearer provider, so none crosses there. Where such a flag or token URL is an + ``env()`` reference, the provider may resolve off (a flag off, or a token URL empty), so the + mode still reads as Digest.""" from messagefoundry.transports.http_auth import HttpAuthError, http_digest_selected mode = _resolved_setting(settings, "http_auth", None, env_values or {}) if mode is _UNRESOLVED: - flags = (settings.get("oauth2_enabled"), settings.get("smart_enabled")) - return not token or any(isinstance(flag, EnvRef) for flag in flags) + # Round 3 finding 1: a token URL from env() may resolve empty, which also leaves the + # provider off, so it counts as an env() flag does. + keys = ("oauth2_enabled", "smart_enabled", "oauth2_token_url", "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: diff --git a/tests/test_soap_5526_remainder.py b/tests/test_soap_5526_remainder.py index 5a3bd7dc7f..18b0c26c3f 100644 --- a/tests/test_soap_5526_remainder.py +++ b/tests/test_soap_5526_remainder.py @@ -203,6 +203,24 @@ def test_the_census_reads_digest_beside_a_bearer_whose_flag_is_from_env() -> Non assert "HTTP Digest" in http_hop_credentials(ConnectorType.REST, settings) +@pytest.mark.parametrize( + "token_url_key", ["smart_token_url", "oauth2_token_url"], ids=["smart", "oauth2"] +) +def test_the_census_reads_digest_beside_a_bearer_whose_token_url_is_from_env( + token_url_key: str, +) -> None: + """Item 9, review round 3 finding 1: an ``env()`` token URL may resolve empty, which leaves + the provider off at build, so Digest crosses; an unresolved ``http_auth`` there still reads + as Digest. Control: a literal token URL with literal flags lists none (the test above).""" + settings: dict[str, Any] = { + "url": URL, + "http_auth": EnvRef("MF_HTTP_AUTH_SYNTHETIC"), + token_url_key: EnvRef("MF_TOKEN_URL_SYNTHETIC"), + } + assert "HTTP Digest" in http_hop_credentials(ConnectorType.FHIR, settings) + assert _http_hop("OB_FHIR", ConnectorType.FHIR, settings, "peer") is not None + + def test_the_census_honours_an_env_default_for_http_auth() -> None: """Item 9, review round 2: with no values, an ``env()`` ``default=`` is read, as the headers reader reads it, so a default of no auth lists no Digest on an mTLS SOAP hop.""" From 53f1fef83367a00cf8e3aa5178ea9887936ec6bc Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 12:50:14 -0600 Subject: [PATCH 20/29] Census: only an env() SMART token URL may resolve the provider off BACKLOG #5526 item 9: an env() oauth2_token_url that resolves blank refuses the build rather than turning OAuth2 off, so it no longer makes the census list Digest (as on main). The effect list no longer says an env() default can run a cast; resolve_env_settings never casts a default. Test, comment and changelog text follow. Proposed PR title: SOAP fault anchor and blank code; one Authorization owner beside a signer (BACKLOG #5912, #5526) Proposed banners: #5912 PARTIAL: closing steps 5, 6 (Body-anchor half), 9, 11, 13 (ADR half), 17 and the _FAULT_TAG_IN_MARKUP half of 24 met on branch w10-soap. Left: steps 8, 18 and 22, parity-with-main trades that close on a fix or the owner's acceptance by name; step 6's second half is step 22's shape. #5526 PARTIAL: items 2, 5 (SOAP), 6 (SOAP and REST), 9, 11 and 12 built on branch w10-soap; items 7, 8, 14 to 22 met on main; item 10 kept by design (ADR 0015 amendment 2026-11-10); filing finding 2 is item 6. Left: item 1's FHIR half; item 4, kept in one line (the second Digest refusal run stays, since skipping it behind a caller flag would make a security refusal optional); item 5's REST and FHIR twins; item 6's FHIR twin; item 13 and filing finding 1 (FTPS, #5530). --- changelog.d/5526-remainder.security.md | 5 ++-- messagefoundry/config/static_credentials.py | 16 +++++----- tests/test_soap_5526_remainder.py | 33 ++++++++++++++------- 3 files changed, 33 insertions(+), 21 deletions(-) diff --git a/changelog.d/5526-remainder.security.md b/changelog.d/5526-remainder.security.md index 0fd7305fea..3f55629007 100644 --- a/changelog.d/5526-remainder.security.md +++ b/changelog.d/5526-remainder.security.md @@ -8,7 +8,6 @@ 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 flag and token URL are both literal, - since the build refuses Digest beside a bearer provider; an `env()` flag or token URL may - resolve the provider off. + except beside an OAuth2 or SMART provider whose enabled flags, and SMART token URL, are + literal, since the build refuses Digest beside a bearer provider. (`BACKLOG #5526`) diff --git a/messagefoundry/config/static_credentials.py b/messagefoundry/config/static_credentials.py index fab92f7b47..f791aae137 100644 --- a/messagefoundry/config/static_credentials.py +++ b/messagefoundry/config/static_credentials.py @@ -86,8 +86,7 @@ ``_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`` against its ``default=``, which can run an -operator ``cast`` too. +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 @@ -196,17 +195,18 @@ def _digest( ``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 token URLs are not themselves ``env()`` references: the build refuses Digest - beside a bearer provider, so none crosses there. Where such a flag or token URL is an - ``env()`` reference, the provider may resolve off (a flag off, or a token URL empty), so the - mode still reads as Digest.""" + 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 does not count: one that resolves blank refuses the build + (``http_auth.refuse_oauth2_settings``) rather than turning the provider off.""" from messagefoundry.transports.http_auth import HttpAuthError, http_digest_selected mode = _resolved_setting(settings, "http_auth", None, env_values or {}) if mode is _UNRESOLVED: - # Round 3 finding 1: a token URL from env() may resolve empty, which also leaves the + # 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", "oauth2_token_url", "smart_token_url") + 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} diff --git a/tests/test_soap_5526_remainder.py b/tests/test_soap_5526_remainder.py index 18b0c26c3f..64cd13510d 100644 --- a/tests/test_soap_5526_remainder.py +++ b/tests/test_soap_5526_remainder.py @@ -203,24 +203,37 @@ def test_the_census_reads_digest_beside_a_bearer_whose_flag_is_from_env() -> Non assert "HTTP Digest" in http_hop_credentials(ConnectorType.REST, settings) -@pytest.mark.parametrize( - "token_url_key", ["smart_token_url", "oauth2_token_url"], ids=["smart", "oauth2"] -) -def test_the_census_reads_digest_beside_a_bearer_whose_token_url_is_from_env( - token_url_key: str, -) -> None: - """Item 9, review round 3 finding 1: an ``env()`` token URL may resolve empty, which leaves - the provider off at build, so Digest crosses; an unresolved ``http_auth`` there still reads - as Digest. Control: a literal token URL with literal flags lists none (the test above).""" +def test_the_census_reads_digest_beside_a_smart_token_url_from_env() -> None: + """Item 9: an ``env()`` SMART token URL may resolve empty, which leaves the provider off at + build, so Digest crosses; an unresolved ``http_auth`` there still reads as Digest. Control: + ``test_the_census_reads_no_digest_beside_a_literal_smart_token_url`` below.""" settings: dict[str, Any] = { "url": URL, "http_auth": EnvRef("MF_HTTP_AUTH_SYNTHETIC"), - token_url_key: EnvRef("MF_TOKEN_URL_SYNTHETIC"), + "smart_token_url": EnvRef("MF_TOKEN_URL_SYNTHETIC"), } assert "HTTP Digest" in http_hop_credentials(ConnectorType.FHIR, settings) assert _http_hop("OB_FHIR", ConnectorType.FHIR, settings, "peer") is not None +def test_the_census_reads_no_digest_beside_a_literal_smart_token_url() -> None: + settings: dict[str, Any] = { + "url": URL, + "http_auth": EnvRef("MF_HTTP_AUTH_SYNTHETIC"), + "smart_token_url": "https://auth.example.com/token", + } + assert "HTTP Digest" not in http_hop_credentials(ConnectorType.FHIR, settings) + + +def test_the_census_reads_no_digest_beside_an_oauth2_token_url_from_env() -> None: + """Item 9: an ``env()`` OAuth2 token URL that resolves blank refuses the build rather than + turning the provider off, so Digest cannot cross there and none is listed, as on main.""" + settings = _oauth(Rest(url=URL)).settings + settings["http_auth"] = EnvRef("MF_HTTP_AUTH_SYNTHETIC") + settings["oauth2_token_url"] = EnvRef("MF_TOKEN_URL_SYNTHETIC") + assert "HTTP Digest" not in http_hop_credentials(ConnectorType.REST, settings) + + def test_the_census_honours_an_env_default_for_http_auth() -> None: """Item 9, review round 2: with no values, an ``env()`` ``default=`` is read, as the headers reader reads it, so a default of no auth lists no Digest on an mTLS SOAP hop.""" From 694723042a80d3826f5f85d4bda2740816c10916 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 13:01:30 -0600 Subject: [PATCH 21/29] Census text: name the no-flag OAuth2 token URL gap Text only, from review round-117c3b9418 (BACKLOG #5526 item 9): the _digest docstring, the changelog and a test docstring claimed an env() OAuth2 token URL that resolves blank always refuses the build. That holds only beside a written oauth2_enabled; with no flag key the provider can resolve off and Digest crosses unlisted. The text now says so and names it a known gap. Proposed PR title: SOAP fault anchor and blank code; one Authorization owner beside a signer (BACKLOG #5912, #5526) Proposed banners: #5912 PARTIAL: closing steps 5, 6 (Body-anchor half), 9, 11, 13 (ADR half), 17 and the _FAULT_TAG_IN_MARKUP half of 24 met on branch w10-soap. Left: steps 8, 18 and 22, parity-with-main trades that close on a fix or the owner's acceptance by name; step 6's second half is step 22's shape. #5526 PARTIAL: items 2, 5 (SOAP), 6 (SOAP and REST), 9, 11 and 12 built on branch w10-soap; items 7, 8, 14 to 22 met on main; item 10 kept by design (ADR 0015 amendment 2026-11-10); filing finding 2 is item 6. Left: item 1's FHIR half; item 4, kept in one line (the second Digest refusal run stays, since skipping it behind a caller flag would make a security refusal optional); item 5's REST and FHIR twins; item 6's FHIR twin; item 9's census bearer reading (env() provider keys read raw); item 13 and filing finding 1 (FTPS, #5530). --- changelog.d/5526-remainder.security.md | 4 +++- messagefoundry/config/static_credentials.py | 7 +++++-- tests/test_soap_5526_remainder.py | 5 +++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/changelog.d/5526-remainder.security.md b/changelog.d/5526-remainder.security.md index 3f55629007..e0f140debf 100644 --- a/changelog.d/5526-remainder.security.md +++ b/changelog.d/5526-remainder.security.md @@ -9,5 +9,7 @@ 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, since the build refuses Digest beside a bearer provider. + 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/messagefoundry/config/static_credentials.py b/messagefoundry/config/static_credentials.py index f791aae137..415aac73d8 100644 --- a/messagefoundry/config/static_credentials.py +++ b/messagefoundry/config/static_credentials.py @@ -198,8 +198,11 @@ def _digest( 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 does not count: one that resolves blank refuses the build - (``http_auth.refuse_oauth2_settings``) rather than turning the provider off.""" + 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 {}) diff --git a/tests/test_soap_5526_remainder.py b/tests/test_soap_5526_remainder.py index 64cd13510d..d65e318681 100644 --- a/tests/test_soap_5526_remainder.py +++ b/tests/test_soap_5526_remainder.py @@ -226,8 +226,9 @@ def test_the_census_reads_no_digest_beside_a_literal_smart_token_url() -> None: def test_the_census_reads_no_digest_beside_an_oauth2_token_url_from_env() -> None: - """Item 9: an ``env()`` OAuth2 token URL that resolves blank refuses the build rather than - turning the provider off, so Digest cannot cross there and none is listed, as on main.""" + """Item 9: beside the ``oauth2_enabled`` the composer writes, an ``env()`` OAuth2 token URL + that resolves blank refuses the build rather than turning the provider off, so no Digest is + listed for it. The no-flag case is a known gap (see ``_digest``).""" settings = _oauth(Rest(url=URL)).settings settings["http_auth"] = EnvRef("MF_HTTP_AUTH_SYNTHETIC") settings["oauth2_token_url"] = EnvRef("MF_TOKEN_URL_SYNTHETIC") From 827da661938abfcfa57516b04b7770e233f946bc Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 13:41:40 -0600 Subject: [PATCH 22/29] Store privilege probe: a read over-grant refuses under enforce beside an unread role Owner ruling 2026-11-23 on BACKLOG #6015 item 1, "Refuse when read": under enforce, a login READ as sysadmin or db_owner, or holding a read CONTROL over-grant, is refused even when another fixed-role or CONTROL column is unread; the unread columns are still reported. The SQL Server early `if unread:` path now weighs what WAS read through sqlserver_excess. With an over-grant read, the report stays OBSERVED with it in the excess and the unread columns in `unread` and the detail; with none, it stays UNOBSERVABLE, which warns. The #1234 pin test is updated to the new rule and cites the ruling; two tests whose rows held db_ddladmin under the external default now run under auto, where nothing over-granted is read. BACKLOG #6015. Proposed PR title: Store privilege probe: R2 added items for #6015 and #6714 (shared probed_grant, unread grants in the summary, db_securityadmin, refuse a read over-grant) Proposed banners: #6015 CLOSED: claim met by PR 2879; added items 1-8 built on branch w10-privilege, item 1 under the owner ruling of 2026-11-23 ("Refuse when read"). #6714 PARTIAL: added items 2-6 built on branch w10-privilege (item 1 by PR 2879); S01-68 reads met on main (owner_named counts CONTROL SERVER, and sysadmin alone among server roles). Left: a reviewed not-a-bug ruling on the headline (custom roles flagged by name, by design per DEPLOY-SERVER-DB.md 1.3, the Manager's reading). #6715 OPEN: nothing built. Left: per-process warning keys (a stable process identity for the bare `store` subject), a design item. --- messagefoundry/store/sqlserver.py | 34 ++++++++++-- tests/test_store_privilege_preflight.py | 71 ++++++++++++++++++++++--- 2 files changed, 93 insertions(+), 12 deletions(-) diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index 271b7632d9..5c38131f8e 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -5182,10 +5182,13 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: 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 makes the whole report :attr:`StorePrivilegeStatus.UNOBSERVABLE`, named grant - by grant in the detail, even beside a role read as held (#1234 pins that): 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. + 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 @@ -5294,15 +5297,36 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: held_labels.append(view_definition_grant(*view_definition)) if external_unread: also_unread = f"; also not read: {', '.join(external_unread)}" + # 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 deliberately: it is additive only, and widening # a report already saying the read was incomplete buys nothing an operator can act on. 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" diff --git a/tests/test_store_privilege_preflight.py b/tests/test_store_privilege_preflight.py index ab63c0f0bc..91db9f9c9d 100644 --- a/tests/test_store_privilege_preflight.py +++ b/tests/test_store_privilege_preflight.py @@ -739,6 +739,10 @@ 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 @@ -758,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 @@ -768,15 +773,65 @@ 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) + with pytest.raises(StorePrivilegeError): + await run_store_privilege_preflight(store, require_least_privilege=False, enforcing=True) + + +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( @@ -1034,10 +1089,12 @@ async def test_an_incomplete_read_names_held_schema_ddl_rights_too( row["alter_schema"] = 1 store = _sqlserver_probe(monkeypatch, row) report = await store.probe_principal_privileges() - assert report.status is StorePrivilegeStatus.UNOBSERVABLE - held = report.detail.split("what DID read as held:", 1)[1] - assert "create table on database MessageFoundry" in held - assert "ALTER on schema dbo" in held + # 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( From 944458a5a0a5dda71ab054e3c2c13985ea2a9fc7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 13:51:12 -0600 Subject: [PATCH 23/29] Store privilege probe: text fixes from review round-0f02503340 Text only. The comment on the skipped user-defined role enumeration no longer says widening the partial report buys nothing: it says such a role is not weighed there. The docs/DEPLOY-SERVER-DB.md exit-4 bullet says a NULL read exits 4 only with nothing over-granted read, and a read over-grant beside it exits 3. The item-3 test docstring says it asserts the excess. BACKLOG #6015. Proposed PR title: Store privilege probe: R2 added items for #6015 and #6714 (shared probed_grant, unread grants in the summary, db_securityadmin, refuse a read over-grant) Proposed banners: #6015 CLOSED: claim met by PR 2879; added items 1-8 built on branch w10-privilege, item 1 under the owner ruling of 2026-11-23 ("Refuse when read"). #6714 PARTIAL: added items 2-6 built on branch w10-privilege (item 1 by PR 2879); S01-68 reads met on main (owner_named counts CONTROL SERVER, and sysadmin alone among server roles). Left: a reviewed not-a-bug ruling on the headline (custom roles flagged by name, by design per DEPLOY-SERVER-DB.md 1.3, the Manager's reading). #6715 OPEN: nothing built. Left: per-process warning keys (a stable process identity for the bare `store` subject), a design item. --- docs/DEPLOY-SERVER-DB.md | 6 +++--- messagefoundry/store/sqlserver.py | 6 ++++-- tests/test_store_privilege_preflight.py | 6 ++++-- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/DEPLOY-SERVER-DB.md b/docs/DEPLOY-SERVER-DB.md index 4cd715cfc2..62cd157b37 100644 --- a/docs/DEPLOY-SERVER-DB.md +++ b/docs/DEPLOY-SERVER-DB.md @@ -185,9 +185,9 @@ messagefoundry check-privileges --service-config \messagefoundry.t 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 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. +- 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/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index 5c38131f8e..a668bac0f3 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -5313,8 +5313,10 @@ async def probe_principal_privileges(self) -> StorePrivilegeReport: audit_writes=audit_writes, view_definition=tuple(view_definition), ) - # 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. + # 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=( diff --git a/tests/test_store_privilege_preflight.py b/tests/test_store_privilege_preflight.py index 91db9f9c9d..f02f0a40a3 100644 --- a/tests/test_store_privilege_preflight.py +++ b/tests/test_store_privilege_preflight.py @@ -1082,8 +1082,10 @@ async def _capture(sql: str, params: tuple[Any, ...] = ()) -> dict[str, Any] | N async def test_an_incomplete_read_names_held_schema_ddl_rights_too( monkeypatch: pytest.MonkeyPatch, ) -> None: - """BACKLOG #6714 item 3: the early UNOBSERVABLE path listed held roles, audit-table rights and - VIEW DEFINITION as "what DID read as held", but not a held CREATE TABLE or ALTER on the schema.""" + """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 From 42bda3d16372c377562a650f3e05024ec9840bb7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 13:57:59 -0600 Subject: [PATCH 24/29] Store privilege probe: name a read CONTROL as read, and keep unread grants in the posture - The SQL Server partial-read detail lists a read CONTROL SERVER or database CONTROL under "what DID read as held", so a report refusing on one no longer says "nothing" was read as held. - StorePrivilegePosture and the GET /security/posture store_privilege view carry `unread`; the store_principal_over_granted loosening entry names the unread grants and says the list may be incomplete. Before, a read over-grant beside an unread role read there as a complete observation (it read as unobserved on main). - The refusal test asserts OBSERVED, a non-empty excess and the over-grant wording. - docs/SECURITY-LOOSENING.md says the entry and the view carry the unread grants. BACKLOG #6015. Proposed PR title: Store privilege probe: R2 added items for #6015 and #6714 (shared probed_grant, unread grants in the summary, db_securityadmin, refuse a read over-grant) Proposed banners: #6015 CLOSED: claim met by PR 2879; added items 1-8 built on branch w10-privilege, item 1 under the owner ruling of 2026-11-23 ("Refuse when read"). #6714 PARTIAL: added items 2-6 built on branch w10-privilege (item 1 by PR 2879); S01-68 reads met on main (owner_named counts CONTROL SERVER, and sysadmin alone among server roles). Left: a reviewed not-a-bug ruling on the headline (custom roles flagged by name, by design per DEPLOY-SERVER-DB.md 1.3, the Manager's reading). #6715 OPEN: nothing built. Left: per-process warning keys (a stable process identity for the bare `store` subject), a design item. --- docs/SECURITY-LOOSENING.md | 4 +- messagefoundry/api/app.py | 1 + messagefoundry/api/models.py | 3 ++ messagefoundry/config/settings.py | 11 ++++- messagefoundry/store/privilege.py | 4 +- messagefoundry/store/sqlserver.py | 5 +++ tests/test_store_privilege_preflight.py | 60 ++++++++++++++++++++++++- 7 files changed, 84 insertions(+), 4 deletions(-) diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index 7e430bc3d6..8b25b5e3d4 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -2175,7 +2175,9 @@ 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 full observation. When the probe also named grants it could + not read, the entry lists them and `store_privilege.unread` carries them (BACKLOG #6015): the + excess list may then be incomplete. - **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/messagefoundry/api/app.py b/messagefoundry/api/app.py index d3682def7e..674aa61c02 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -5564,6 +5564,7 @@ async def security_posture( status=store_privilege.status.value, excess=list(store_privilege.excess), detail=store_privilege.detail, + unread=list(store_privilege.unread), ) ) # FIPS-provider attestation of the interpreter's ssl/_hashlib OpenSSL (report-only, #73 / ADR 0120): diff --git a/messagefoundry/api/models.py b/messagefoundry/api/models.py index 175fabb409..ea96475565 100644 --- a/messagefoundry/api/models.py +++ b/messagefoundry/api/models.py @@ -1560,6 +1560,9 @@ class StorePrivilegeView(BaseModel): excess: list[str] = Field(default_factory=list) #: Why the probe could not observe, or what it observed against. Never secret material. detail: str = "" + #: Grants the probe named as not read (BACKLOG #6015); beside an ``excess`` the list may be + #: incomplete. Grant labels only, never secret material. + unread: list[str] = Field(default_factory=list) class StartupCodeItemView(BaseModel): diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 7cfbd752f7..ce1057468a 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -291,6 +291,9 @@ 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. + unread: tuple[str, ...] = () class SchemaManagement(str, Enum): # noqa: UP042 @@ -11591,13 +11594,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/store/privilege.py b/messagefoundry/store/privilege.py index 71ac2aade9..48cfaebfa6 100644 --- a/messagefoundry/store/privilege.py +++ b/messagefoundry/store/privilege.py @@ -507,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. diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index a668bac0f3..088ce280a9 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -5286,6 +5286,11 @@ 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: diff --git a/tests/test_store_privilege_preflight.py b/tests/test_store_privilege_preflight.py index f02f0a40a3..9347091f82 100644 --- a/tests/test_store_privilege_preflight.py +++ b/tests/test_store_privilege_preflight.py @@ -817,10 +817,55 @@ async def test_a_read_over_grant_refuses_under_enforce_beside_an_unread_role( unread=unread, ) store = _sqlserver_probe(monkeypatch, row) - with pytest.raises(StorePrivilegeError): + 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: @@ -1537,10 +1582,23 @@ async def test_posture_route_reports_an_observed_over_grant(engine: Engine) -> N ) assert body["store_privilege"]["status"] == "observed" assert body["store_privilege"]["excess"] == ["server role sysadmin"] + assert body["store_privilege"]["unread"] == [] switches = [entry["switch"] for entry in body["loosenings"]] 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",), + ), + ) + assert body["store_privilege"]["unread"] == ["database role db_owner"] + + async def test_posture_route_reports_an_unobservable_probe(engine: Engine) -> None: body = await _posture( engine, From 2aab426e7c7dec4f46d63972d54d5b08c949124b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 14:19:32 -0600 Subject: [PATCH 25/29] Store privilege probe: keep the posture view's seam; unread grants ride the loosening entry Review round-79efb8acec found that adding `unread` to StorePrivilegeView moved the web-console seam digest (test_webconsole_seam_snapshot red), which needs a coordinated seam bump across both wheels. The view's field is withdrawn; the unread signal reaches GET /security/posture through the store_principal_over_granted entry's risk text, which the route test now asserts. StorePrivilegePosture keeps `unread`. Text: docs/SECURITY-LOOSENING.md and the StorePrivilegePosture.unread comment no longer imply an entry without the "may be incomplete" clause proves the excess list complete. BACKLOG #6015. Proposed PR title: Store privilege probe: R2 added items for #6015 and #6714 (shared probed_grant, unread grants in the summary, db_securityadmin, refuse a read over-grant) Proposed banners: #6015 CLOSED: claim met by PR 2879; added items 1-8 built on branch w10-privilege, item 1 under the owner ruling of 2026-11-23 ("Refuse when read"). #6714 PARTIAL: added items 2-6 built on branch w10-privilege (item 1 by PR 2879); S01-68 reads met on main (owner_named counts CONTROL SERVER, and sysadmin alone among server roles). Left: a reviewed not-a-bug ruling on the headline (custom roles flagged by name, by design per DEPLOY-SERVER-DB.md 1.3, the Manager's reading). #6715 OPEN: nothing built. Left: per-process warning keys (a stable process identity for the bare `store` subject), a design item. --- docs/SECURITY-LOOSENING.md | 5 +++-- messagefoundry/api/app.py | 1 - messagefoundry/api/models.py | 3 --- messagefoundry/config/settings.py | 4 +++- tests/test_store_privilege_preflight.py | 6 ++++-- 5 files changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index 8b25b5e3d4..03b497f5ab 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -2176,8 +2176,9 @@ count is above `0` (vault BACKLOG #2613). - **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. When the probe also named grants it could - not read, the entry lists them and `store_privilege.unread` carries them (BACKLOG #6015): the - excess list may then be incomplete. + 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 SQL Server read that + skipped or failed its user-defined role enumeration says so only in `store_privilege.detail`. - **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/messagefoundry/api/app.py b/messagefoundry/api/app.py index 674aa61c02..d3682def7e 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -5564,7 +5564,6 @@ async def security_posture( status=store_privilege.status.value, excess=list(store_privilege.excess), detail=store_privilege.detail, - unread=list(store_privilege.unread), ) ) # FIPS-provider attestation of the interpreter's ssl/_hashlib OpenSSL (report-only, #73 / ADR 0120): diff --git a/messagefoundry/api/models.py b/messagefoundry/api/models.py index ea96475565..175fabb409 100644 --- a/messagefoundry/api/models.py +++ b/messagefoundry/api/models.py @@ -1560,9 +1560,6 @@ class StorePrivilegeView(BaseModel): excess: list[str] = Field(default_factory=list) #: Why the probe could not observe, or what it observed against. Never secret material. detail: str = "" - #: Grants the probe named as not read (BACKLOG #6015); beside an ``excess`` the list may be - #: incomplete. Grant labels only, never secret material. - unread: list[str] = Field(default_factory=list) class StartupCodeItemView(BaseModel): diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index ce1057468a..23d468c3f8 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -292,7 +292,9 @@ class StorePrivilegePosture: #: 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. + #: 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 skipped or failed SQL Server user-defined role + #: enumeration is noted in ``detail`` only. unread: tuple[str, ...] = () diff --git a/tests/test_store_privilege_preflight.py b/tests/test_store_privilege_preflight.py index 9347091f82..b2df75bb20 100644 --- a/tests/test_store_privilege_preflight.py +++ b/tests/test_store_privilege_preflight.py @@ -1582,7 +1582,6 @@ async def test_posture_route_reports_an_observed_over_grant(engine: Engine) -> N ) assert body["store_privilege"]["status"] == "observed" assert body["store_privilege"]["excess"] == ["server role sysadmin"] - assert body["store_privilege"]["unread"] == [] switches = [entry["switch"] for entry in body["loosenings"]] assert "store_principal_over_granted" in switches @@ -1596,7 +1595,10 @@ async def test_posture_route_reports_the_unread_grants_beside_an_over_grant(engi unread=("database role db_owner",), ), ) - assert body["store_privilege"]["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: From 6d02f0142739e1f31dc919a8ff8f4edefe9ec96c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 14:30:50 -0600 Subject: [PATCH 26/29] Store privilege probe: correct what records a skipped or failed role enumeration Text only, from review round-ee8617cb2f. docs/SECURITY-LOOSENING.md and the StorePrivilegePosture.unread comment said a skipped user-defined role enumeration is noted in detail; it is not noted anywhere, and only a failed one is noted, in the detail and the audit row's. The doc no longer calls the store_privilege field the full observation. BACKLOG #6015. Proposed PR title: Store privilege probe: R2 added items for #6015 and #6714 (shared probed_grant, unread grants in the summary, db_securityadmin, refuse a read over-grant) Proposed banners: #6015 CLOSED: claim met by PR 2879; added items 1-8 built on branch w10-privilege, item 1 under the owner ruling of 2026-11-23 ("Refuse when read"). #6714 PARTIAL: added items 2-6 built on branch w10-privilege (item 1 by PR 2879); S01-68 reads met on main (owner_named counts CONTROL SERVER, and sysadmin alone among server roles). Left: a reviewed not-a-bug ruling on the headline (custom roles flagged by name, by design per DEPLOY-SERVER-DB.md 1.3, the Manager's reading). #6715 OPEN: nothing built. Left: per-process warning keys (a stable process identity for the bare `store` subject), a design item. --- docs/SECURITY-LOOSENING.md | 10 ++++++---- messagefoundry/config/settings.py | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index 03b497f5ab..0146eff125 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -2175,10 +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. 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 SQL Server read that - skipped or failed its user-defined role enumeration says so only in `store_privilege.detail`. + `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/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 23d468c3f8..0cbed6d789 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -293,8 +293,8 @@ class StorePrivilegePosture: 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 skipped or failed SQL Server user-defined role - #: enumeration is noted in ``detail`` only. + #: 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, ...] = () From b12762021c7c586d83939270965a69bd5d0bc656 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 15:53:04 -0600 Subject: [PATCH 27/29] Wave 10 hold fixes: shard-3 import form, FHIR census docstring, privilege changelog Answers the Lander hold on PR 3206 at head bf7893915d15. - tests/test_store_privilege_preflight.py: import the sqlserver_roles leaf as a module path, so the server-DB path gate maps it to its own source rather than the package root (test shard 3). - config/static_credentials.py: the _static_authorization docstring no longer says FHIR sends Basic beside a bearer token; the FHIR destination and FhirLookup refuse that pair at build (BACKLOG #8299 item 8). - changelog.d: fragment for BACKLOG #6015 and #6714. --- .../6015-read-over-grant-beside-unread.security.md | 10 ++++++++++ messagefoundry/config/static_credentials.py | 7 ++++--- tests/test_store_privilege_preflight.py | 2 +- 3 files changed, 15 insertions(+), 4 deletions(-) create mode 100644 changelog.d/6015-read-over-grant-beside-unread.security.md 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..4079fb4b91 --- /dev/null +++ b/changelog.d/6015-read-over-grant-beside-unread.security.md @@ -0,0 +1,10 @@ +- **A store over-grant that was read now refuses under enforce even when a neighbouring grant + could not be read.** On SQL Server, a fixed role or `CONTROL` the store privilege preflight read + as held, such as `sysadmin` or `db_owner`, used to be demoted to an unobserved warning when + another role column answered NULL. The report now stays OBSERVED with that over-grant in the + excess, so with `[store].require_least_privilege` and no accepted opt-out the start refuses, and + `check-privileges` exits 3 (over-grant) where it used to exit 4 (could not read). The 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. Under `schema_management = "external"`, `db_securityadmin` no + longer adds a separate `VIEW DEFINITION` finding, since the role carries that right. + (`BACKLOG #6015`, `BACKLOG #6714`) diff --git a/messagefoundry/config/static_credentials.py b/messagefoundry/config/static_credentials.py index 295e09bb16..ec20b05e8c 100644 --- a/messagefoundry/config/static_credentials.py +++ b/messagefoundry/config/static_credentials.py @@ -225,9 +225,10 @@ def _digest( def _static_authorization(settings: Mapping[str, Any]) -> list[str]: """The static credential the connector writes into its own ``Authorization`` header. With both - a ``bearer_token`` and a Basic pair set, FHIR sends Basic, so only Basic is listed (BACKLOG - #5526 item 2). REST, SOAP and DICOMweb refuse to build on both, and Basic is listed for them - all the same: this reader does not take the connector type.""" + 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, so this listing describes a hop that does not build: this reader does not take the + connector type.""" if settings.get("basic_user") and settings.get("basic_password"): return ["HTTP Basic"] if settings.get("bearer_token"): diff --git a/tests/test_store_privilege_preflight.py b/tests/test_store_privilege_preflight.py index b2df75bb20..3e020bcd73 100644 --- a/tests/test_store_privilege_preflight.py +++ b/tests/test_store_privilege_preflight.py @@ -1177,7 +1177,7 @@ def test_probed_grant_lives_in_the_leaf_and_the_login_probe_calls_it( ) -> 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.""" - from messagefoundry import sqlserver_roles + import messagefoundry.sqlserver_roles as sqlserver_roles from messagefoundry.transports import database assert probed_grant is sqlserver_roles.probed_grant From 3e8e1767831d4af21717b627327d57c36c9fb626 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:08:08 -0600 Subject: [PATCH 28/29] Wave 10 hold fixes: text repairs from review round-2de5d7f0ee - changelog.d 6015 fragment: the new refusal needs enforce (the default) with require_least_privilege unset; under the declared key it refused before. Name the external-only grants and the PostgreSQL unread field with an "at least". - static_credentials._static_authorization: name the env() Basic half that the census counts as set while the hop builds and sends the bearer. - test_soap_5526_remainder: drop the FHIR-sends-Basic claim from the census test docstring; FHIR now refuses the pair (BACKLOG #8299 item 8). - test_store_privilege_preflight: say why the leaf is imported by module path. --- ...-read-over-grant-beside-unread.security.md | 24 ++++++++++++------- messagefoundry/config/static_credentials.py | 6 +++-- tests/test_soap_5526_remainder.py | 5 ++-- tests/test_store_privilege_preflight.py | 2 ++ 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/changelog.d/6015-read-over-grant-beside-unread.security.md b/changelog.d/6015-read-over-grant-beside-unread.security.md index 4079fb4b91..3a2939040f 100644 --- a/changelog.d/6015-read-over-grant-beside-unread.security.md +++ b/changelog.d/6015-read-over-grant-beside-unread.security.md @@ -1,10 +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 fixed role or `CONTROL` the store privilege preflight read - as held, such as `sysadmin` or `db_owner`, used to be demoted to an unobserved warning when - another role column answered NULL. The report now stays OBSERVED with that over-grant in the - excess, so with `[store].require_least_privilege` and no accepted opt-out the start refuses, and - `check-privileges` exits 3 (over-grant) where it used to exit 4 (could not read). The 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. Under `schema_management = "external"`, `db_securityadmin` no - longer adds a separate `VIEW DEFINITION` finding, since the role carries that right. - (`BACKLOG #6015`, `BACKLOG #6714`) + 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/messagefoundry/config/static_credentials.py b/messagefoundry/config/static_credentials.py index ec20b05e8c..fb6a08e0ee 100644 --- a/messagefoundry/config/static_credentials.py +++ b/messagefoundry/config/static_credentials.py @@ -227,8 +227,10 @@ def _static_authorization(settings: Mapping[str, Any]) -> list[str]: """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, so this listing describes a hop that does not build: this reader does not take the - connector type.""" + 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"): return ["HTTP Basic"] if settings.get("bearer_token"): diff --git a/tests/test_soap_5526_remainder.py b/tests/test_soap_5526_remainder.py index d65e318681..e1bef87141 100644 --- a/tests/test_soap_5526_remainder.py +++ b/tests/test_soap_5526_remainder.py @@ -78,8 +78,9 @@ def test_control_soap_builds_on_either_credential_alone(auth: dict[str, str]) -> def test_the_census_lists_only_the_basic_pair_where_both_are_set() -> None: - """Item 2: a connector that builds with both sends Basic (FHIR assigns it last), so the census - lists HTTP Basic alone. Control: each alone is listed.""" + """Item 2: with both set the census lists HTTP Basic alone. The FHIR destination and + FhirLookup now refuse to build on both (BACKLOG #8299 item 8), so this pins the census reading, + not a credential on the wire. Control: each alone is listed.""" both = {"bearer_token": _TOKEN, "basic_user": "svc", "basic_password": _PW} assert http_hop_credentials(ConnectorType.FHIR, both) == ["HTTP Basic"] assert http_hop_credentials(ConnectorType.FHIR, {"bearer_token": _TOKEN}) == [ diff --git a/tests/test_store_privilege_preflight.py b/tests/test_store_privilege_preflight.py index 3e020bcd73..161f5091a4 100644 --- a/tests/test_store_privilege_preflight.py +++ b/tests/test_store_privilege_preflight.py @@ -1177,6 +1177,8 @@ def test_probed_grant_lives_in_the_leaf_and_the_login_probe_calls_it( ) -> 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 From 07d53348b4bcd1bb79083c76a3d23df1964fc0df Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 11:52:58 -0600 Subject: [PATCH 29/29] CONNECTIONS.md: WS-Security code search anchors outside terminated markup Main's MessageExpired bullet (BACKLOG #5798) predates this branch's #5912 closing step 6, which makes the Body anchor skip a Body start tag inside a terminated comment, CDATA section or processing instruction. Merge-review finding; the bullet now states the rule the code applies. --- docs/CONNECTIONS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 3e0ac7e74c..177b06a1cf 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -3141,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