diff --git a/changelog.d/1197-route-body-step-up-refusal.security.md b/changelog.d/1197-route-body-step-up-refusal.security.md new file mode 100644 index 0000000000..3f36b4fe15 --- /dev/null +++ b/changelog.d/1197-route-body-step-up-refusal.security.md @@ -0,0 +1,5 @@ +- **The step-up refusals of `spend_step_up_action` and `refuse_unless_step_up_window_live`, made + in a route body after its `proof_in_route` gate admitted the request, can now write an + `auth.gate_refused` row.** In the shipped code they wrote no row of their own. + `_record_route_refusal` in `messagefoundry/api/security.py` says when the row is written. No + request is allowed that was refused before. (`BACKLOG #1197`) diff --git a/changelog.d/5799-reply-replaced-event.added.md b/changelog.d/5799-reply-replaced-event.added.md new file mode 100644 index 0000000000..7c10e30138 --- /dev/null +++ b/changelog.d/5799-reply-replaced-event.added.md @@ -0,0 +1,6 @@ +- When connection events are captured, the MLLP, raw-TCP and X12 listeners send a + `reply_replaced` connection event when characters the inbound's charset cannot encode were + replaced in a reply: the first at once, then at most one a minute per listener, carrying the + count of replaced replies since the last one. The WARNING log line for a replacement is still + written once per connection per process. + [PHI.md](../docs/PHI.md) section 7 says what the event carries. (`BACKLOG #5799`) diff --git a/changelog.d/6719-6720-foreign-view-remedy.fixed.md b/changelog.d/6719-6720-foreign-view-remedy.fixed.md new file mode 100644 index 0000000000..294d9d09cc --- /dev/null +++ b/changelog.d/6719-6720-foreign-view-remedy.fixed.md @@ -0,0 +1,10 @@ +- **A SQLite store whose upgrade is stopped by a view or trigger another tool left can now name + that object.** When SQLite's re-check after a migration's `ALTER` fails on such a view or trigger + with an error that names the store's shape, such as "no such module", and the error's text fits + exactly one such object, the open refuses the store with the remedy to save that object's CREATE + statement, drop it and restart, not to recreate the store. The object is named only when that + remedy survives the 200-character cut and the redaction of a printed error whole; otherwise, + and whenever the text fits more than one object, the store gets the plain remedy. A + failure on the store's shape raised by the check's own read of the live store, after the schema + script and the migrations of a writable open, is now refused with the recreate remedy rather + than escaping as SQLite's bare error. (`BACKLOG #6719`, `BACKLOG #6720`) diff --git a/docs/PHI.md b/docs/PHI.md index 1eedd0779e..3880841c6f 100644 --- a/docs/PHI.md +++ b/docs/PHI.md @@ -2326,7 +2326,7 @@ with materially different PHI profiles, so they get their own rows; stream 4 is | **4. Off-box syslog/SIEM forwarder** — the shared **transport** for 1–3 | a copy of every record from 1–3 | `forward_format`, default **JSON** (independent of the stdout format) | the operator's collector (`forward_host`/`_port`) | off-box evidence retention / SIEM correlation | **default-on when a collector is named.** Transport: `udp` (default) / `tcp` / **`tls`** (RFC 5425, CA-anchored, verified by default). `serve` gates the hop on the shared posture gradient before the handler is installed: verified TLS ungated; otherwise loopback / attested ALLOW, non-enforcing WARN, **enforcing REFUSE (exit 2)** — there is no synthetic arm, and [ADR 0186](adr/0186-retire-the-synthetic-data-declaration-every-instance-carries-patient-data.md) left this cell with no per-hop way to accept the risk at all | the collector's, not the engine's | the identical handler filters are installed on this handler. So the forwarded copy gets the same best-effort PHI redaction and credential scrub as stdout. A single-token identifier can survive it, as it can there. The copy also carries usernames, connection names, message ids, client addresses and the audit chain. That is the engine's own stated reason for gating the hop | | **5. `audit_log` table** (SQLite, Postgres, SQL Server) | who / what / **where-from** / when of auth + PHI *access* and admin actions — plus, while `[security].audit_all_authorization_decisions` is on (**default `true`** since BACKLOG #1277, 2026-09-02, which reversed the ADR 0118 §5 `false`; the internal field it desugars to is `audit_all_authz`, whose old `[diagnostics]` TOML spelling is **refused at load** — ADR 0118), an `authz` row for **every** authorization decision including successes. That is the shipped volume of this stream, not an opt-in addition to it: one row per authenticated request on each `require()`-gated route, and this row's retention cell records that **nothing prunes the table** — `actor`, `action`, `channel_id`, `client`, `detail`, `row_hash` | JSON `detail`; **tamper-evident hash chain** over `prev_hash` + the row (the `client` address is **inside** the chained payload — ADR 0150) | the store database | HIPAA §164.312(b) audit controls; incident response; `verify_audit_chain` integrity checks | `GET /audit` requires **`audit:read`**; `GET /audit/export` requires the separate **`audit:export`** and streams CSV with formula-injection neutralisation, recording its own `audit.export` row *before* streaming; `GET /me/security-events` is a per-user view of the same table | **`[retention].audit_days` is reserved and NOT enforced — keep-forever by design** (the audit-retention requirement, ~6 years — **not** chain-breakage; [§8](#8-retention--purge) states the position and cites its source of record) | `detail` is stored **in the clear** (it is not a cipher-covered column): its protection is that writers store at least filter shapes, counts, ids, keyed digests, bounded engine-authored text and client addresses, the `audit_log.detail` row above says which — never bodies or credentials — plus the store ACL and the volume layer. *Corrected 2026-10-16 (vault BACKLOG #3145):* this said writers "only ever store filter shapes, counts and ids" | | **6. `message_events` table** | the per-message disposition timeline — the **complete** vocabulary is `received`, `routed`, `unrouted`, `filtered`, `transformed`, `delivered`, `failed`, `dead`, `error`, `replayed`, `resent`, `reingressed`, `passthrough`, `passthrough_dropped`, `cancelled`, `edit_resend`, `edit_resubmit`, `viewed`, `not_deployed`, the ADR 0154 synchronous-reply pair `reply_returned` / `reply_timeout` (names, counts and `waited_ms` only — **never** a fragment of the partner's reply body), and `reply_dropped`, a delivery whose 2xx reply body was over the byte bound and dropped (the status and the bound only, vault BACKLOG #3040) (CI asserts this list against the engine's own `MESSAGE_EVENT_KINDS`). `[diagnostics].message_events` can thin the set, but never below the compliance floor `viewed` / `dead` / `error` / `failed` / `not_deployed` / `reply_timeout` / `reply_dropped` | rows: `message_id`, `ts`, `event`, `destination`, `detail` | the store database | operator timeline on the message-detail view; the `viewed` row is the HIPAA PHI-access record | `GET /messages/{id}` under **`messages:view_raw`** + `require_phi_read`; the read itself writes a `viewed` event **and** a `message_view` audit row | no dedicated window — `purge_message_bodies` sets `message_events.detail` to `NULL` in the same transaction that blanks the body, so it inherits `[retention].messages_days` | `detail` is `safe_text()`-scrubbed **then** cipher-encrypted (AAD `("message_events","detail",message_id,ts,event)`). Verbosity gate `[diagnostics].message_events` = `all` (default) / `errors` / `off`, with a **compliance floor that can never be thinned**: `viewed`, `dead`, `error`, `failed`, `not_deployed`, `reply_timeout`, `reply_dropped` are retained at every level (`reply_timeout` is the one row that explains a "we called you and got a 504" complaint, so an instance that thinned its logs would lose exactly the record it is later asked for; `reply_dropped` is the one row that answers "you ignored our reply", for the same reason) | -| **7. `connection_event` table — DEFAULT ON** (`[diagnostics].connection_events = true`) | transport/lifecycle events per connection: `established`, `closed` (reason `eof`, `idle_timeout` or `frame_deadline` — a fixed vocabulary chosen by the listener, never free text), `idle_timeout`, `at_capacity`, `peer_not_allowlisted`, `frame_oversize`, `framing_error`, `peer_reset`, the MLLP, raw-TCP, X12 and HTTP listeners' and the DATABASE poll source's `handler_error` (BACKLOG #1619, #5022, #5680 for the HTTP listener, which answers it `503` or `500` by the exception's type, as [CONNECTIONS.md Table B](CONNECTIONS.md#table-b--per-service-resource-strategy-asvs-1313) states -- the inbound handler faulted on a frame the listener read cleanly, such as a failed ingress commit; on the X12 listener also, BACKLOG #5971, the engine's own reply to an interchange already recorded could not be encoded in the inbound's charset, so it was not sent; on the DATABASE source, BACKLOG #4921, on a polled row, which is left unmarked and, when the source has a mark statement, stops that poll; the reason is scrubbed at the source like every other), the MLLP and HTTP listeners' `tls_handshake_failed` (vault BACKLOG #2613, #3302 and #3785 -- an inbound TLS handshake failed, on any event loop. **This is the one statement of the failed-handshake throttle, and other pages link here.** The first failure is reported at once, then at most one report per listener per minute, carrying the count since the last report. The reason is a count, an exception class name and OpenSSL's reason mnemonic, never the peer's bytes or certificate. A report names a peer only for a single failure, and only where the listener runs its own handshakes or awaits each one's outcome itself, which the MLLP and HTTP listeners do on every loop (BACKLOG #1606, #2479) and the DICOM C-STORE SCP always does. Such a listener also counts a handshake that runs past its bound. Where only the loop sees them, which is at least the API listener on every loop, the report names no peer, since the loop's hook does not read it (the module docstring of `messagefoundry/tls_handshake_failures.py` says what was measured), and a handshake that only runs past its bound is not counted. A peer that closes or resets the socket mid-handshake is not counted anywhere. That is what a load balancer's TCP health check does. The past-bound and hang-up limits stand by owner ruling 2026-10-26 (vault BACKLOG #3785 items 7 and 8), and that ruling covers only those two. Whether the API's report should name the peer is still an open owner question (vault BACKLOG #3302). The item 8 decline keeps the hang-up counting that came before #3785 and adds none. So a close_notify after the ClientHello is still counted, and the DICOM C-STORE SCP counts it too. A handshake that the listener's own stop ends is not counted. At least every listener also drops a genuine failure that lands once its stop has begun. The DICOM C-STORE SCP drops them for the whole of its server shutdown. On the MLLP and HTTP listeners, a stop that is cancelled before it finishes loses the failures its trailing report still held. The DICOM C-STORE SCP still reports them when its server shutdown raises or is cancelled. The API listener and the DICOM C-STORE SCP write the same report, throttled the same way, as a WARNING log line rather than an event: the API has no connection to carry one, and the SCP emits none (vault BACKLOG #3784)), the DATABASE poll source's `row_undecodable` (BACKLOG #1662 — a polled row the source cannot turn into a body; the reason is scrubbed at the source and names the exception type or the operator's own configured column, never a row value), the FILE poll source's quarantine kinds `file_oversize` / `file_decompress_failed` / `file_content_mismatch` / `file_scan_rejected` (BACKLOG #1621 — a drop moved to `.error`; the reason is a size, a content type or a codec or scanner message, and **that message can still name the file**. The name scrub on both the FILE and REMOTEFILE sources is `safe_exc(exc, file_name=...)`. safe_exc replaces the file name and, at least, its repr, ascii, bytes-repr and JSON-escaped forms. A scanner's `ScanRejected` message that quotes the name in at least another case, without its extension, percent-encoded, in another Unicode normalization, or escaped in a spelling those forms do not produce, such as a JSON escape with uppercase hex digits, keeps that text in the reason (`tests/test_file_source_quarantine_events.py` and `tests/test_remotefile_source_quarantine_events.py` pin this on each source's scan-reject arm), so a scan hook should leave the name out of its message; the REMOTEFILE poll source records the same kinds except `file_decompress_failed`, since it does not decompress), the inbound-HTTP intake-auth refusals `intake_auth_failed` / `auth_subject_denied` / `auth_rate_limited` (ADR 0154 D6 — peer address and mode only, plus, behind a proxy the connection lists in its trusted_proxies setting, the forwarded client address as a forwarded_for suffix on the reason and the audit detail (BACKLOG #5525); **never** the credential, a prefix of it, or its length. Each of these also writes a tamper-evident audit-log row — the copy that survives an operator turning this diagnostics stream off. The MLLP listener writes `auth_subject_denied` and `auth_rate_limited` too, with the same audit rows, when its expected-sender allowlist refuses a sender, naming the peer address and never a certificate field; BACKLOG #4907), plus the runner's `connection_lost` / `connection_restored` / `config_fault`. That is the whole vocabulary, asserted in CI against the literal emit call sites in `transports/` and the pipeline runner **and** against `CONNECTION_EVENT_KINDS` (`messagefoundry/connection_events.py`), the one set the store enforces on write and the console's filter reads (BACKLOG #1624). The MLLP, raw-TCP, X12 and HTTP listeners emit these; the **DATABASE poll source** emits `row_undecodable` and `handler_error` and nothing else (it dials out, so there is no lifecycle to report and its rows carry a **NULL peer column**); the **FILE poll source** emits only its four quarantine kinds, and the **REMOTEFILE poll source** only three of them, both with a NULL peer column; the **DICOM inbound C-STORE SCP** emits none — the runner injects the sink onto **every** source (`wiring_runner.py`, over the base-class `on_connection_event` field), so that connector *has* the wiring and simply never calls it — so this stream covers those four listeners plus those poll-source events and the runner's outbound-lane transitions — not literally every connection. A DICOM association's connects and refusals are therefore **absent** from this stream. The **`ISA`/`IEA`-framed X12 inbound** was equally absent until BACKLOG #1665 and is not any more: it emits the same kinds as the raw-TCP listener | rows: `ts`, `connection`, `transport`, `direction`, `kind`, `peer_host`, `message_id` (correlation hint), `reason` | the store database, **all three backends** | Corepoint-style transport diagnostics — "did the sender connect, and why did it drop" | `GET /events` and `GET /connections/{name}/events` under **`monitoring:read`** (**not** a PHI permission) with per-channel RBAC — an out-of-scope `connection=` is 403'd *and* audited — server-clamped to ≤1000 rows. `reason` alone is gated on `messages:view_summary` and masked as `****` until the audited per-event `reveal=` act (BACKLOG #2443; the `connection_event.reason` row of §3's PL-2 block says how) | `[retention].connection_event_retention_hours` (its own **hours** window); 0 inherits `[retention].messages_days`; both 0 = keep forever. Plain age `DELETE` | **`reason` is free text that can carry sensitive fragments.** Defended twice — `safe_exc()` at the source, `safe_text(reason, limit=200)` at the store (the bound §3's PL-2 block states) — then cipher-encrypted (AAD `("connection_event","reason",connection,ts,kind)`). Every other column is engine or config metadata except `peer_host`, and `reason` is not metadata-only: the [data-at-rest inventory](#2-where-phi-lives--data-at-rest-inventory) grades `reason` and `peer_host` in rows of their own (BACKLOG #5021). Writes are a pure side observer: a bounded in-memory queue drained by a background task outside any handoff transaction, so a flood can never block a listener or pin a message disposition | +| **7. `connection_event` table — DEFAULT ON** (`[diagnostics].connection_events = true`) | transport/lifecycle events per connection: `established`, `closed` (reason `eof`, `idle_timeout` or `frame_deadline` — a fixed vocabulary chosen by the listener, never free text), `idle_timeout`, `at_capacity`, `peer_not_allowlisted`, `frame_oversize`, `framing_error`, `peer_reset`, the MLLP, raw-TCP, X12 and HTTP listeners' and the DATABASE poll source's `handler_error` (BACKLOG #1619, #5022, #5680 for the HTTP listener, which answers it `503` or `500` by the exception's type, as [CONNECTIONS.md Table B](CONNECTIONS.md#table-b--per-service-resource-strategy-asvs-1313) states -- the inbound handler faulted on a frame the listener read cleanly, such as a failed ingress commit; on the X12 listener also, BACKLOG #5971, the engine's own reply to an interchange already recorded could not be encoded in the inbound's charset, so it was not sent; on the DATABASE source, BACKLOG #4921, on a polled row, which is left unmarked and, when the source has a mark statement, stops that poll; the reason is scrubbed at the source like every other), the MLLP, raw-TCP and X12 listeners' `reply_replaced` (BACKLOG #5799 -- the engine's own reply held characters the inbound's charset cannot encode, and each was replaced before the reply was written to the connection; throttled per listener: the first such reply sends one at once, then at most one a minute, sent by the first such reply past the minute and carrying the count of such replies since the last one, with no trailing report, so replies counted after the last event are not reported if no later one comes; an event is sent whether or not the write then succeeds, while the WARNING log line is written once per connection per process; a frame byte turned into a space writes no event; the reason is a count and fixed text that names neither the charset setting nor any part of the reply), the MLLP and HTTP listeners' `tls_handshake_failed` (vault BACKLOG #2613, #3302 and #3785 -- an inbound TLS handshake failed, on any event loop. **This is the one statement of the failed-handshake throttle, and other pages link here.** The first failure is reported at once, then at most one report per listener per minute, carrying the count since the last report. The reason is a count, an exception class name and OpenSSL's reason mnemonic, never the peer's bytes or certificate. A report names a peer only for a single failure, and only where the listener runs its own handshakes or awaits each one's outcome itself, which the MLLP and HTTP listeners do on every loop (BACKLOG #1606, #2479) and the DICOM C-STORE SCP always does. Such a listener also counts a handshake that runs past its bound. Where only the loop sees them, which is at least the API listener on every loop, the report names no peer, since the loop's hook does not read it (the module docstring of `messagefoundry/tls_handshake_failures.py` says what was measured), and a handshake that only runs past its bound is not counted. A peer that closes or resets the socket mid-handshake is not counted anywhere. That is what a load balancer's TCP health check does. The past-bound and hang-up limits stand by owner ruling 2026-10-26 (vault BACKLOG #3785 items 7 and 8), and that ruling covers only those two. Whether the API's report should name the peer is still an open owner question (vault BACKLOG #3302). The item 8 decline keeps the hang-up counting that came before #3785 and adds none. So a close_notify after the ClientHello is still counted, and the DICOM C-STORE SCP counts it too. A handshake that the listener's own stop ends is not counted. At least every listener also drops a genuine failure that lands once its stop has begun. The DICOM C-STORE SCP drops them for the whole of its server shutdown. On the MLLP and HTTP listeners, a stop that is cancelled before it finishes loses the failures its trailing report still held. The DICOM C-STORE SCP still reports them when its server shutdown raises or is cancelled. The API listener and the DICOM C-STORE SCP write the same report, throttled the same way, as a WARNING log line rather than an event: the API has no connection to carry one, and the SCP emits none (vault BACKLOG #3784)), the DATABASE poll source's `row_undecodable` (BACKLOG #1662 — a polled row the source cannot turn into a body; the reason is scrubbed at the source and names the exception type or the operator's own configured column, never a row value), the FILE poll source's quarantine kinds `file_oversize` / `file_decompress_failed` / `file_content_mismatch` / `file_scan_rejected` (BACKLOG #1621 — a drop moved to `.error`; the reason is a size, a content type or a codec or scanner message, and **that message can still name the file**. The name scrub on both the FILE and REMOTEFILE sources is `safe_exc(exc, file_name=...)`. safe_exc replaces the file name and, at least, its repr, ascii, bytes-repr and JSON-escaped forms. A scanner's `ScanRejected` message that quotes the name in at least another case, without its extension, percent-encoded, in another Unicode normalization, or escaped in a spelling those forms do not produce, such as a JSON escape with uppercase hex digits, keeps that text in the reason (`tests/test_file_source_quarantine_events.py` and `tests/test_remotefile_source_quarantine_events.py` pin this on each source's scan-reject arm), so a scan hook should leave the name out of its message; the REMOTEFILE poll source records the same kinds except `file_decompress_failed`, since it does not decompress), the inbound-HTTP intake-auth refusals `intake_auth_failed` / `auth_subject_denied` / `auth_rate_limited` (ADR 0154 D6 — peer address and mode only, plus, behind a proxy the connection lists in its trusted_proxies setting, the forwarded client address as a forwarded_for suffix on the reason and the audit detail (BACKLOG #5525); **never** the credential, a prefix of it, or its length. Each of these also writes a tamper-evident audit-log row — the copy that survives an operator turning this diagnostics stream off. The MLLP listener writes `auth_subject_denied` and `auth_rate_limited` too, with the same audit rows, when its expected-sender allowlist refuses a sender, naming the peer address and never a certificate field; BACKLOG #4907), plus the runner's `connection_lost` / `connection_restored` / `config_fault`. That is the whole vocabulary, asserted in CI against the literal emit call sites in `transports/` and the pipeline runner **and** against `CONNECTION_EVENT_KINDS` (`messagefoundry/connection_events.py`), the one set the store enforces on write and the console's filter reads (BACKLOG #1624). The MLLP, raw-TCP, X12 and HTTP listeners emit these; the **DATABASE poll source** emits `row_undecodable` and `handler_error` and nothing else (it dials out, so there is no lifecycle to report and its rows carry a **NULL peer column**); the **FILE poll source** emits only its four quarantine kinds, and the **REMOTEFILE poll source** only three of them, both with a NULL peer column; the **DICOM inbound C-STORE SCP** emits none — the runner injects the sink onto **every** source (`wiring_runner.py`, over the base-class `on_connection_event` field), so that connector *has* the wiring and simply never calls it — so this stream covers those four listeners plus those poll-source events and the runner's outbound-lane transitions — not literally every connection. A DICOM association's connects and refusals are therefore **absent** from this stream. The **`ISA`/`IEA`-framed X12 inbound** was equally absent until BACKLOG #1665 and is not any more: it emits the same kinds as the raw-TCP listener | rows: `ts`, `connection`, `transport`, `direction`, `kind`, `peer_host`, `message_id` (correlation hint), `reason` | the store database, **all three backends** | Corepoint-style transport diagnostics — "did the sender connect, and why did it drop" | `GET /events` and `GET /connections/{name}/events` under **`monitoring:read`** (**not** a PHI permission) with per-channel RBAC — an out-of-scope `connection=` is 403'd *and* audited — server-clamped to ≤1000 rows. `reason` alone is gated on `messages:view_summary` and masked as `****` until the audited per-event `reveal=` act (BACKLOG #2443; the `connection_event.reason` row of §3's PL-2 block says how) | `[retention].connection_event_retention_hours` (its own **hours** window); 0 inherits `[retention].messages_days`; both 0 = keep forever. Plain age `DELETE` | **`reason` is free text that can carry sensitive fragments.** Defended twice — `safe_exc()` at the source, `safe_text(reason, limit=200)` at the store (the bound §3's PL-2 block states) — then cipher-encrypted (AAD `("connection_event","reason",connection,ts,kind)`). Every other column is engine or config metadata except `peer_host`, and `reason` is not metadata-only: the [data-at-rest inventory](#2-where-phi-lives--data-at-rest-inventory) grades `reason` and `peer_host` in rows of their own (BACKLOG #5021). Writes are a pure side observer: a bounded in-memory queue drained by a background task outside any handoff transaction, so a flood can never block a listener or pin a message disposition | | **8. `alert_instance` table — default on wherever an `[alerts]` notifier exists** | resolvable operator alerts: `connection_stopped`, `queue_buildup`, `lane_stuck`, `message_stall`, `saturation`, `connection_error`, `connection_error.config_fault`, `storage_threshold`, `cert_expiry`, `secret_rotation`, `initial_credential_expiring` (an UNCLAIMED admin-issued temporary password nearing the instant the login gate stops accepting it -- ASVS 6.4.5, BACKLOG #1141; keyed on `user:`, and the payload is the ISO deadline plus whole hours remaining, repeated in the reason column, never the password), `integrity_drift`, `update_available`, `backup_failed`, `store_privilege_warning` (the store privilege preflight found the store principal over-granted or could not read it -- BACKLOG #305; the payload is the finding, a count and the preflight's summary line, which names the login, the database and role names, never a password or message content), `vault_privilege_warning` (the Vault privilege preflight found a Vault token over-granted or could not read it -- BACKLOG #2903, ADR 0216; keyed on `vault:store` or `vault:secrets`, and the payload is the finding, a count of refusing-class grants and the hop's judgment, which names policy names, paths and capabilities, never a token, an accessor, a digest of either or message content), `leadership_acquired`, `dr_activated`, `log_write_failed` (an application-log sink was rolled after a write failure, or is UNWRITABLE and this process's connections were stopped -- BACKLOG #122, ADR 0162; the payload is the sink LABEL, the stage, a `safe_exc` reason and a count of connections stopped, never the record whose write failed), `log_forward_failed` (the off-box log forwarder is absent, losing records or not sending -- BACKLOG #2612; keyed on `forwarder:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, fixed reason words and a count, never a record, the collector's address or an error text; an unpinned cluster node's `node_id` holds this engine's own host name and process id, so the key carries them), `gcm_invocations` (the per-key AES-GCM invocation bound crossing its 2^31 soft warn — ASVS 11.3.4; its payload carries a one-way `key_id` fingerprint plus counters, never key bytes), `approval_stale_requester` (a dual-control release refused because the requester no longer holds the authority the operation needs -- ASVS 8.3.2, BACKLOG #289; keyed on the approval id, and the payload is that id, the operation key and a closed-set reason slug, never the requester's name or the captured params), `approval_too_early` (a dual-control release refused because it arrived before `[approvals].min_dwell_seconds` -- ASVS 2.4.2, BACKLOG #287; keyed on `approval:`, and the payload is that key, the operation key and a fixed reason string, never the approver's or requester's name or the captured params), `audit_write_failed` (the approval gate could not write one of its audit rows -- vault BACKLOG #2255; keyed on `approval:`, on `approval::resolve` for a resolution's lost provenance row -- vault BACKLOG #3438, on the fixed `approval:listing` for a queue listing's lost `approval.standing_shown` row -- vault BACKLOG #3747, on `config_reload:inline` when an ungated config reload could not write its `config_reload_attempted` row -- vault BACKLOG #2254, or on `step_up_return:audit_budget:` when the IdP step-up return audit budget's backstop stopped a row -- BACKLOG #3965, or on `directory-reconciler:` when a directory reconcile pass that completed could not write a row -- BACKLOG #3018 step 2, or on `directory-sign-in:` when a directory sign-in's role-sync row was refused twice -- BACKLOG #2221; the payload is that key and the lost row's audit action name, never the row's detail, a username or the captured params; the ERROR log line beside it holds the detail on some paths and only the exception on others), `audit_offbox_copy_missing` (an approval audit row whose write the gate read back as committed, whose off-box copy was never sent -- vault BACKLOG #3193; keyed on `approval:`, and the payload is that key and the row's audit action name, never the row's detail, a username or the captured params), `ad_reconcile_aborted` (a directory reconciler pass left signed-in accounts unrevoked and needs an operator: the mass-revoke breaker tripped and nothing was revoked, or one or more probes were answered with an LDAP referral and those accounts were left unjudged while the rest of the pass was applied, BACKLOG #2538, or one or more probes raised a fault the engine could not read and those accounts were left unjudged the same way, BACKLOG #3100, or the directory refused one or more probes with a result code that points at the configuration, such as a deleted search base, and those accounts were left unjudged the same way, vault BACKLOG #3010, or an account's group search was refused for the engine's own deadline or cap, so a role or scope change in the directory does not revoke that account's sessions, though a disable or deletion still does, vault BACKLOG #3696, or every lookup failed to reach the directory for `[auth].ad_reconcile_outage_passes` passes running, BACKLOG #3709; for the breaker, a referral, a probe fault, a configuration refusal and a lasting outage the payload is a fixed source label, `directory-reconciler` for the breaker, `directory-reconciler-referral` for a referral, `directory-reconciler-probe-fault` for a probe fault, `directory-reconciler-misconfigured` for a configuration refusal and `directory-reconciler-outage` for a lasting outage so each is its own instance, the closed-set reason slug `mass_revoke_breaker`, `directory_referral`, `probe_fault`, `directory_misconfigured` or `directory_unavailable`, a count (the accounts the breaker judged, or for each of the other four the lookups the pass sent, which leaves out an id-less row -- vault BACKLOG #3170) and the latched operator explanation, or for a lasting outage a fixed sentence with the run's length, never a username; a paging refusal is instead keyed on that operator account's username, as `directory-reconciler-paging:`, so each account is its own instance, raised as the account enters that state and again after a restart while it stands, and the payload is that key, the closed-set reason slug `group_search_deadline` or `group_search_cap`, the same count as the breaker's and a fixed sentence naming the cause, never anything else about the account; an account the directory keeps failing to answer for is keyed the same way, as `directory-reconciler-unreached:`, raised as it enters that state, and its payload is that key, the closed-set reason slug `account_unreachable`, the count of lookups the pass sent and a fixed sentence with two numbers, how many probes failed and the most recent probes its window can hold (faults aside), never anything else about the account -- vault BACKLOG #3100, #3709; on a rolled-up pass, those entering page as one instance under the bare `directory-reconciler-unreached` source, with no username, and the `ad_reconcile_outage_passes` row of [CONFIGURATION.md](CONFIGURATION.md) states when), `ad_reconcile_held` (the reconciler is holding accounts whose `userAccountControl` it cannot read, ADR 0195; the payload is the same fixed source label, a closed-set reason slug, the count of undetermined accounts and the latched operator explanation, never a username), `ad_session_revoked` (the reconciler revoked a directory principal's sessions; keyed on that operator account's username, with at least a `directory_absent`, `directory_disabled`, `directory_undetermined`, `directory_object_id_missing`, `roles_changed` or `scope_changed` reason), `approval_approver_provenance` (a dual-control release, or the resolution of an interrupted one, went ahead with an approver or resolver account created, re-passworded or TOTP-enrolled after the request -- BACKLOG #315, #2125; keyed on `approval:`, or `approval::resolve` for a resolution, and the payload is the operation key and the closed-set change slugs, never a username or the captured params), `administrator_granted` (the built-in Administrator role was granted by account creation, a role change, a directory group newly mapped to it -- BACKLOG #315 --, a directory sign-in whose role sync newly gave the account the role -- vault BACKLOG #2610 -- or a directory reconcile pass whose role re-diff did -- vault BACKLOG #3141; keyed on `user:` or `ad-group:`, with the grant route and the granting administrator's username, or `` for a directory sign-in or reconcile pass), `no_enabled_administrator` (a directory sign-in's role sync or the session reconciler took Administrator from its last enabled holder -- vault BACKLOG #3229; keyed on `user:`, and the payload is `via`, `ad-sync` or `ad-reconcile`, and a fixed reason sentence, never message content), `intake_paused` (the engine paused intake because the staged backlog went over `[inbound].max_staged_depth` or the SQLite volume fell below `[retention].min_free_disk_mb` -- BACKLOG #290; keyed on `intake:staged_depth` or `intake:disk_floor`, with `@node:` or `@shard:` appended when several engine processes share the store (BACKLOG #2272), and the payload is the reason, a count or a MiB figure, its limit and the store backend's name, never message content), `config_changed` (a start's config differs from the store's baseline: the bytes it loaded, or the directory just after the load -- vault BACKLOG #2597, #3765; keyed on `config:`, and the payload is the two digests, the node and engine shard labels, the action, actor username, time and node of the row the older digest came from, and the `comparison` outcome, never the config directory, a git commit or message content), `crl_reload_refused` (the CRL reload refused a replaced CRL file, so running TLS contexts keep the copy they hold -- vault BACKLOG #2904; keyed on `crl_reload:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the file's path, a short class token for the remedy, a count of contexts, the engine's own fixed remedy sentence and, when a start would refuse the file too, a `start_refuses` flag, never the refusal's reason, which quotes CRL issuer names and dates; that reason is in the application log, and in the `detail` of the CRL expiry alert once the held copy nears its `nextUpdate`), `remote_debug_refused` (the engine's remote-debugging guard refused scripts that another process injected into the engine process -- vault BACKLOG #2742; keyed on `remote_debug:refused`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the count of scripts refused since the alert was last raised, the count since the process started and a fixed sentence built from the two, never a script's file name, which the injecting process chooses; that name is in the application log, in the guard's WARNING line), `sandbox_worker_refused` (a `[sandbox].mode = "subprocess"` worker was refused because the graph it loaded differs from the engine's, most often a config file edited on disk with no reload -- vault BACKLOG #2724; keyed on the inbound's name, raised once per refusal, and the payload is that name and a fixed sentence naming the cause and the remedy, never a message body or the refusal text, which names config names and digests and is in the application log), `store_restored` (the first `serve` on a store `messagefoundry restore` placed ended every session -- BACKLOG #2614; keyed on `store:restored`, raised once per restore, and the payload is that key; a fixed sentence carrying the archive's age in days, the count of sessions ended, a pointer to `messagefoundry restore --help` and the time of the archive's newest audit row, of which the alert instance's reason column keeps the age, the count and the pointer whole and the time redacted or cut; that time again as `last_audit_at`; and the fixed notice of what a restore rolls back as `rollback_notice` (`messagefoundry/restore_notice.py`, BACKLOG #5094), fixed text the reason column never holds; never an account name or a row's content), and the seven security signals of the audit-stream rule layer -- vault BACKLOG #2613: `signin_failure_burst` (keyed on `signin:`, never the typed username), `access_denied_burst`, `body_view_burst` and `bulk_export` (each keyed on `account:`), `peer_refused_burst` (keyed on `inbound:`, never the refused peer's address), `log_level_debug` (keyed on `logging:debug`) and `posture_loosened` (keyed on `posture:start`, with `@node:` or `@shard:` appended when several engine processes share the store); the payload is a count and a fixed sentence holding a level name, switch names or a username, never a message body, a message id or an audit row's detail. The reachable **inverse** signals — `connection_restored`, `leadership_lost`, `dr_released`, `store_privilege_clean`, `vault_privilege_clean`, `intake_resumed`, `posture_restored` (it resolves `posture_loosened` under the same key, so for the same engine process, when a start records no security loosening in a row marked neither `superseded` nor `baseline_unchecked` and a live posture read then names none -- vault BACKLOG #2613; an unpinned cluster node's key changes on every start, so that node raises the inverse for its own instance as it shuts down; when that instance can still stay open is in [SECURITY.md](SECURITY.md)), `crl_reload_applied` (it resolves `crl_reload_refused` under the same key, so for the same file and the same engine identity, at least once the reload's record no longer holds the refusal, once no hop holds any CRL, and when the reload stops -- vault BACKLOG #2904; it is also raised once per held file outside a CA bundle, at the first pass that judges it with no refusal standing, whether or not an alert is open, so it can resolve nothing, and it then clears one an earlier run under that identity left open -- vault BACKLOG #3543. An alert for a file no hop holds now stays open, and so does one an unpinned cluster node raised, because that node's identity changes on every start; [CONFIGURATION.md](CONFIGURATION.md), *The alert resolves itself*, is the source of record), `ad_reconcile_breaker_cleared`, `ad_reconcile_hold_released` (the last two resolve `ad_reconcile_held` and `ad_reconcile_aborted`, the latter only under the breaker's, the referral's or the lasting outage's source: the probe fault's, the configuration refusal's, a paging refusal's and an unreached account's instances have no inverse; when they do, and where they never do, is stated once in [CONFIGURATION.md](CONFIGURATION.md#when-the-reconcilers-alerts-resolve-themselves) -- BACKLOG #2136) — are never rows here: `_record_state` routes an inverse through `_AUTO_RESOLVE` to `resolve_alert_instances_fenced` (BACKLOG #4916), or `resolve_alert_instances_for` on a store without the fence methods, never to `upsert_alert_instance`. So is `connection_started`, which resolves `connection_stopped` under the bare connection name: the runner raises it only when an operator's start or restart finds an inbound up and no cause it can see still holds the name down in either direction (BACKLOG #1741). Every other start raises nothing, at least an engine start, a committed reload, the scheduler and every alert rule's restart, so an open stop keeps its instance, ack and suspend across them. `AlertSink.connection_started` states the full contract, including the operator starts that still raise nothing. An instance raised under a prefixed stand-in such as `reference:` is never resolved by it. | rows: `event_type`, `connection`, `severity`, `status`, `first_seen`, `last_seen`, `count`, `reason`, `acked_by`, `acked_at`, `resolved_at`, `suspended_until`, `escalation_tier`, `raised_by` (a random per-process id naming the newest raise's writer, BACKLOG #4916; never a host, user or message value) | the store database, **all three backends** | the operator alert list — acknowledge / resolve / suspend. Durable state is recorded **before** any suppression or throttle return, so a muted alert still leaves a record | `GET /alerts/active` under **`monitoring:diagnose`** (**not** a PHI permission) with the same per-channel scope, and `reason` alone gated on `messages:view_summary` and masked as `****` until the audited per-alert `reveal=` act (BACKLOG #2443; the `alert_instance.reason` row of §3's PL-2 block says how); ack/resolve/suspend/**resume** are POSTs on the same tier, and the separate read-only `GET /alerts/rules` view sits on its own gate | shares the connection-event window; **only RESOLVED instances are DELETEd**, by `resolved_at` — retention never ages out an open or acknowledged condition from under an operator; a row can still close with no inverse and no operator, at least through the `intake_paused` staleness sweep (BACKLOG #3269), which resolves another engine process's open or acknowledged pause under the expiry rule in [CONFIGURATION.md](CONFIGURATION.md#alerts), after which retention treats it as any resolved row | **`reason` is free text** taken from the event's internal `_detail` (the `connection_error` reason kept off the wire, BACKLOG #5021), `detail` or `reason`: `safe_text(reason, limit=200)` (the bound §3's PL-2 block states) then cipher-encrypted (AAD `("alert_instance","reason",event_type,connection)` — the de-dup grain, so one AAD covers both the INSERT and the re-fire UPDATE). | | **9. `response` rows with `kind='ack_sent'` — DEFAULT ON** (`[diagnostics].response_sent = true`) | the ACK/NAK the engine returned to an inbound sender, under a sentinel destination `\x1fack:` | rows: `ack_code` (`AA`/`AE`/`AR`/`CA`/`CE`/`CR`), `ack_phase` (`decode`/`parse`/`strict`/`ingest`), `outcome`, `body`, `detail` | the store database | "what did we actually reply, and why" — the operator's answer to a sender disputing an ACK | `GET /messages/{id}/responses` under `messages:read` + `require_phi_read`; the `body` only for a caller who also holds `messages:view_raw` and `messages:view_summary`; every read writes a `response.read` audit row | `body`, `detail` and `resp_headers` are set to `NULL` in place by `purge_message_bodies` on the message-body window, on all three backends | **PHI fail-safe:** the ACK **body** is stored **only when the store cipher is active** — on a keyless store it is `NULL` rather than plaintext — and every NAK passes no body at all, so the offending field value is never persisted. The disposition metadata (`ack_code`/`ack_phase`/`outcome`) is non-PHI and always captured; `detail` is `safe_text`-scrubbed, held to the 200-character bound §3's PL-2 block states, and encrypted | | **10. `[alerts]` webhook transport** (off by default — `webhook_url` unset) | one HTTPS POST per alert, carrying every non-underscore event key as JSON | JSON | the operator's webhook endpoint (Slack/Teams/PagerDuty/custom) | operator notification | **`https` only** — a plaintext `http://` webhook URL is refused at construction. Redirects are refused; an optional `webhook_allowed_hosts` egress allowlist gates the host. A verifying `https` hop off this box also takes the revocation guard at build, on a host the `webhook_allowed_hosts` allowlist admits. An unset or empty allowlist admits every host, an explicit `[]` included, and so does an environment value that splits to no host, such as `""` or `","`. A host off a non-empty allowlist is refused at build, before this guard (BACKLOG #5088). A TOML list keeps its entries as written, so `[""]` or `[","]` is not empty and names no real host, and the build refuses every real host. Under an enforcing or unknown posture the guarded hop is refused unless the `[alerts].webhook_tls_revocation_attested` pair is set ([ADR 0173](adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md) states the guard and its levers) | the endpoint's | **carries the alert's `detail`/`reason` free text** for at least `connection_stopped`, `log_write_failed` and `backup_failed` (`safe_exc()`-scrubbed at the emit sites, but **not** re-run through `safe_text` on this path, and a scrubbed reason can still echo a partner's reply text). `connection_error` no longer carries its detail: in its place it sends the exception class (or the fixed token `unnamed error` for a class that is not a plain identifier), beside at least the connection and the kind, and keeps the detail under the internal `_detail` key, which the notifier pops before any transport is handed the event and which the alert instance's stored `reason` (row 8) still keeps (`NotifierAlertSink.connection_error`, BACKLOG #5021). Internal `_`-prefixed keys, at least `_detail`, `_transports`, the per-rule recipients, the rule id and the cooldown, are stripped before send, so recipient addresses never cross the wire | diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 38c53de063..2a7a7f11ed 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5333,8 +5333,10 @@ flowchart TB `auth.gate_refused`, naming the same permission and a `reason` of `throttled` or `step_up`. It writes that row only where it would have written the grant row, so a gate that writes no grant row writes no refusal row either. A refused second factor writes `auth.mfa_denied`, as the base - gate's does. A refusal a route body makes after its gate has passed, such as a step-up proof the - route spends itself, still follows a grant row. + gate's does. For the step-up refusals of `spend_step_up_action` and + `refuse_unless_step_up_window_live`, which a route body makes after its gate has passed, + `_record_route_refusal` in `messagefoundry/api/security.py` says what it records. Other refusals + a route body makes after its gate has passed write no `auth.gate_refused` row. - Routes that act on a Connection also check the identity's connection scope. That scope starts empty for every role except Administrator. - Sensitive routes add a step-up re-check on top of this flow. See diff --git a/docs/SUPPLY-CHAIN.md b/docs/SUPPLY-CHAIN.md index 092d67d6ca..96e2287d94 100644 --- a/docs/SUPPLY-CHAIN.md +++ b/docs/SUPPLY-CHAIN.md @@ -149,20 +149,22 @@ Facts the labels leave out: ([ADR 0201](adr/0201-a-messagefoundry-toolkit-distribution-carries-the-authoring-and-development-tooling-out-of-the-engine-wheel.md)). - **One approval per engine tag.** The toolkit, engine and harness uploads are steps of one `publish-pypi` job, so one approval of the `pypi` environment covers all three. The harness - upload runs only when the `PUBLISH_HARNESS` repository or organization variable is set. + upload runs only when the `PUBLISH_HARNESS` variable reads `true` twice: where its build job + reads it, outside the `pypi` environment, and where the upload reads it again, inside that + environment. - **The draft.** The engine's GitHub release stays a draft until the harness wheel is on it - too, and until every upload `publish-pypi` runs has succeeded. With `PUBLISH_HARNESS` unset, - that is the toolkit and the engine only. A separate job publishes it last, so no + too, and until every upload `publish-pypi` runs has succeeded. When the harness upload does not + run, that is the toolkit and the engine only. A separate job publishes it last, so no job adds an asset to a published release. The console's release is a draft too, at least until - its `publish-pypi-webconsole` job has succeeded. With `PUBLISH_WEBCONSOLE` set, that job uploads - the wheel first. Unset, the console upload is skipped and the console's release is still - published once the `pypi` approval is given, as the engine's is with `PUBLISH_HARNESS` unset. - With either variable set, its draft publisher reads it again when it runs and refuses to publish - the release unless that run's upload step succeeded. On an engine tag the toolkit and engine + its `publish-pypi-webconsole` job has succeeded. The console upload runs under the same two + reads of `PUBLISH_WEBCONSOLE`. Each draft publisher reads its variable again when it runs, + outside the `pypi` environment, and while that read is `true` it refuses to publish the + release unless that run's upload step succeeded. On an engine tag the toolkit and engine are on PyPI by then. The refusal's text names two causes, a remedy with the upload and one without, but not which cause fired, and points here for the routes left past GitHub's re-run window. At least these two can fire, alone or together: - - The `pypi` environment holds its own copy of the variable, with a value other than `true`. + - The `pypi` environment holds its own copy of the variable, with a value that is not `true` in + any letter case. Look at that environment's variables in the repository settings to see whether it holds one now; a copy removed since the run cannot be seen there. - The build job read the variable before it was set, or the upload read it while it was unset @@ -170,36 +172,40 @@ Facts the labels leave out: fires; the remedies below clear it either way, so it need not be told apart. To finish the release with the upload, remove any copy from the `pypi` environment, then re-run - the build job (`release-harness` on an engine tag, `release-webconsole` on a console tag), which - re-runs the jobs after it, so the upload asks for the `pypi` approval again, and reads the - variable afresh in each, so it clears both. While the variable still reads `true`, a "Re-run - failed jobs" reuses the upload's outcome and is refused again. + the build job (`release-harness` on an engine tag, `release-webconsole` on a console tag). That + re-runs the jobs after it, so the upload asks for the `pypi` approval again, and each of those + jobs reads the variable afresh, which clears both causes. On an engine tag the re-run upload + also downloads the `pypi-engine` artifact, which the `release` job uploaded and which is kept + for at most 30 days, so it fails once that artifact has expired. While the variable still reads + `true`, a "Re-run failed jobs" reuses the upload's outcome and is refused again. To finish it without the upload, first check that no other release run that reads the variable - is queued, waiting or in progress, and that none can start before the restore below. Note - whether the repository holds the variable and its value. Remove any copy from the `pypi` - environment, give the repository variable a value that is not `true` in any letter case, such - as `false`, and re-run the publisher. A repository variable takes precedence over an - organization variable of the same name, so this changes the value for this repository only. Do - not edit or delete an organization copy, which other repositories may read. Once that re-run - has finished, whatever its result, and before the next release, restore the repository variable - to the value you noted, deleting it if the repository had none, or that release skips its upload - too and still goes public. + is queued, waiting or in progress, and that none can start before the restore below. Do not edit + or delete an organization copy of the variable in any of the steps that follow, because other + repositories may read it. Note whether the repository holds the variable and its value. Remove + any copy from the `pypi` environment, give the repository variable a value that is not `true` + in any letter case, such as `false`, and re-run the publisher (`publish-github-release` on an + engine tag, `publish-github-release-webconsole` on a console tag). A repository variable takes + precedence over an organization variable of the same name, so this changes the value for this + repository only. Once that re-run has finished, whatever its result, and before the next + release, restore the repository variable to the value you noted, deleting it if the repository + had none, or that release skips its upload too and still goes public. GitHub allows a re-run only within 30 days of a run's first attempt, so past that no re-run finishes the release. When this refusal is what holds the draft, at least two routes are left: the publisher's own command run by hand, `gh release edit --draft=false --repo MEFORORG/MessageFoundry`, which publishes the draft without that upload; and a new version - under a new tag. Run by hand on a draft held for any other reason, such as a failed build job - or a refused approval, the same command publishes a release with an asset missing or a package - not on PyPI. + under a new tag. On either route, first remove any copy of the variable from the `pypi` + environment, or the next release can be refused the same way. Run by hand on a draft held for + any other reason, such as a failed build job or a refused approval, the same command publishes + a release with an asset missing or a package not on PyPI. - **The provenance gate.** The tagged commit must be on `main`, and for each required check, the latest run of every workflow and trigger that ran it on that commit must have passed. A red run after the merge blocks the tag even if the merge-queue run passed, and a green from another workflow or trigger does not clear it. To clear it, re-run the failed jobs of the workflow run the refusal names, or run that workflow on the same trigger again, then re-run the release. GitHub - re-runs a workflow run only within 30 days of it. A check still running is waited for. A check the server requires that never ran on the commit also - blocks it; tag a newer commit that ran it. + re-runs a workflow run only within 30 days of it. A check still running is waited for. A check + the server requires that never ran on the commit also blocks it; tag a newer commit that ran it. ## What we publish, per release @@ -220,9 +226,10 @@ has no SBOM of its own. Apart from that, every row but one covers the **engine** only. The exception is the PEP 740 row: every PyPI publish job in `release.yml` sets `attestations: true`. So the web console wheel (`messagefoundry-webconsole`) -and the harness wheel get a PyPI-side attestation whenever their PyPI publish runs. Both of those -publishes are gated on a repository variable. That is all they get: their release jobs have no -Sigstore, SBOM or SLSA step. +and the harness wheel get a PyPI-side attestation whenever their PyPI publish runs. Each of those +publishes runs only when its variable, `PUBLISH_WEBCONSOLE` or `PUBLISH_HARNESS`, reads `true` +both outside and inside the `pypi` environment, as *One approval per engine tag* and *The draft* +above say. That is all they get: their release jobs have no Sigstore, SBOM or SLSA step. Additional CycloneDX SBOMs — the **VS Code extension** (npm) and the **container image** (Debian base + system libs + installed Python) — are produced by the daily/​on-demand `security.yml` workflow and diff --git a/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md b/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md index b4344de942..a9ef1ed19c 100644 --- a/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md +++ b/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md @@ -661,12 +661,15 @@ lifetime is Vault's to version. The bound is a no-op there and for the identity > 2026-09-28 amendment states the deployment precondition and cites the pages read. > **Corrected 2026-10-10 (BACKLOG #1173).** The rotation precondition above still stands, and the -> engine still counts no Transit encrypts. What changed is the record. Since BACKLOG #2337, an -> operator attests to the precondition with `messagefoundry store attest-transit-bound`, and -> `Engine.start` reads that record through `enforce_transit_bound_attestation`. So "documented" -> now undersells it. The R3 ruling above judged the precondition before that record existed; -> whether the record meets R3 is a scorecard call. ADR 0138's 2026-10-07 amendment says what the -> check does under each enforcement level, and what it does not change. +> engine still counts no Transit encrypts. What changed is the record. Since BACKLOG #2337, +> `Engine.start` checks for an operator's recorded attestation to the precondition through +> `enforce_transit_bound_attestation`, so "documented" now undersells it. The R3 ruling above +> judged the precondition before that record existed. ADR 0138's 2026-10-07 amendment says how the +> attestation is recorded and what the check does under each enforcement level. It also says what +> the check does not change. Whether the record meets R3 is, in that amendment's words, "a +> scorecard call, not this amendment's". *(Corrected 2026-11-21, vault BACKLOG #1173: this note +> read "an operator attests to the precondition with `messagefoundry store attest-transit-bound`, +> and `Engine.start` reads that record", which the 2026-10-07 amendment states.)* **Status: 11.3.4 — the bound is persisted, aggregated, alarmed and enforced.** As before, this ADR records the build and does not itself re-score; ADR 0115 / the ASVS-L3 re-score governs the sweep. @@ -800,13 +803,14 @@ above. 4. **Volume wears out a key, not the generator.** The one value whose safety falls with volume is the 96-bit random AES-GCM nonce, and that is a limit on the key, not on the generator. The default path counts it: the 2026-07-22 amendment above, and `store/gcm_bound.py`. The `vault_transit` path - counts nothing. In its place, `Engine.start` calls `enforce_transit_bound_attestation` in - `store/transit_attestation.py`, which checks for a recorded operator attestation naming the - configured Transit data key (BACKLOG #2337). Without one, the engine refuses to start under - `[security].enforcement = enforce` and only logs a warning under `warn`. An attestation is still - weaker than the counted bound. [ADR 0138](0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md)'s - 2026-10-07 amendment records how that gate works and the forgery it does not catch. Its - 2026-09-28 amendment states the rotation precondition the operator attests to. + counts nothing. `Engine.start` instead checks for an operator's recorded attestation to the + bound, through `enforce_transit_bound_attestation` in `store/transit_attestation.py` (BACKLOG + #2337). An attestation is still weaker than the counted bound. [ADR 0138](0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md)'s + 2026-10-07 amendment records what that gate checks, what it does under each enforcement level, + and what it does not catch. Its 2026-09-28 amendment states the rotation precondition the + operator attests to. *(Corrected 2026-11-21, vault BACKLOG #1173: this point read "In its + place, `Engine.start` calls" and went on to say what the gate checks and what it does under + `enforce` and `warn`, which the 2026-10-07 amendment states.)* **What this statement does not cover.** How fast the operating system's generator runs is a property of Windows and Linux. The 2026-10-10 amendment below says what the platform pages state about diff --git a/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md b/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md index f47a2322d2..fd3979a9d4 100644 --- a/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md +++ b/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md @@ -1323,10 +1323,11 @@ ODBC revocation runbook that reached a result. Their contents beyond this summar here. It changes no code. For the grade, see the limit headed *What a result would mean for the grade*, under the ruling above, and its note of 2026-11-11. -- **Where it ran.** Two runs with results, dated 2026-10-16 and 2026-10-17 in Central time. In - UTC, the first run's legs ran from 02:22 to 02:25 and the second's from 05:18 to 05:19, both on - 2026-10-17. The first run's record says it ran on a disposable virtual machine built for the - test, not on the SQL Server test box, and that the runbook puts the next run there. The second +- **Where it ran.** Two runs with results. The first run's legs ran from 02:22 to 02:25 UTC and + the second's from 05:18 to 05:19 UTC, both on 2026-10-17. The records are dated in Central + time: the first 2026-10-16, the second 2026-10-17. The first run's record says it ran + on a disposable virtual machine built for the test, not on the SQL Server test box, and that the + runbook puts the next run there. The second run's record says it ran inside a virtual machine, after a revert to checkpoint `post-3009-clean-2026-10-16`, a tightening of folder permissions and a new checkpoint, `post-3009-acl-2026-10-17`. It writes the machine's name as a placeholder, so it cannot show @@ -1373,9 +1374,9 @@ grade*, under the ruling above, and its note of 2026-11-11. the pin legs mean for the pin is the amendment of 2026-10-17 below. For the strict legs that reading is the second record's own, because the runbook's table has no row for them. - **The limits.** At least these. - - Only that driver build, only Windows Server 2022, and only SQL Server 2022 RTM. Linux, macOS, - other Driver 18 builds, and other drivers, which the generic dialect and the `odbc_driver` - setting can name, were not measured. + - Only the driver, Windows and SQL Server versions above. Linux, macOS, other Driver 18 builds, + and other drivers, which the generic dialect and the `odbc_driver` setting can name, were not + measured. - Only a CRL over HTTP. No OCSP responder was offered, so this does not show that the driver never checks revocation. - Only a same-machine connection: the client ran on the machine SQL Server ran on, so no @@ -1385,6 +1386,11 @@ grade*, under the ruling above, and its note of 2026-11-11. pool, so the result says nothing about how the engine builds or sends its own strings. - Only a throwaway root, with no intermediate CA. +*(Corrected 2026-11-21, vault BACKLOG #3009: the first bullet opened "Two runs with results, +dated 2026-10-16 and 2026-10-17 in Central time. In UTC, the first run's legs ran", and the first +limit opened "Only that driver build, only Windows Server 2022, and only SQL Server 2022 RTM.", +which repeated the versions bullet.)* + *(End of the amendment of 2026-11-11. The next paragraph continues the 2026-10-04 note.)* **What is open on the three Vault hops.** *(Built on 2026-10-13, under vault BACKLOG #2983; diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index e8312ef1c7..45d12d14d6 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1479,28 +1479,80 @@ async def _recorded_decision( inside it writes ``auth.gate_refused`` instead, naming the permission the grant row would have named and why. - A refusal row is written exactly where the grant row would have been, so a request still writes - at most one decision row, and a gate that wrote no grant row writes no refusal row either. That - keeps the per-request volume where the shipped trail already put it while the audit chain has no - drain (BACKLOG #1421). The reason comes from the :class:`_GateRefusal` the check raised. Any - other exception leaves the block with no decision row from it, which is right for the - :func:`_mfa_refusal` 403: it wrote its own ``auth.mfa_denied`` row where it was raised.""" + A refusal row is written exactly where the grant row would have been, so a gate writes at most + one decision row per request, and a gate that wrote no grant row writes no refusal row either. + The audit chain has no drain (BACKLOG #1421); a refused route-body request writes at most two + decision rows. For the step-up refusals of :func:`spend_step_up_action` and + :func:`refuse_unless_step_up_window_live`, made in a route body after its gate admitted the + request, see :func:`_record_route_refusal`. Other refusals a route body makes after its gate + admitted the request write no ``auth.gate_refused`` row. The reason comes from the + :class:`_GateRefusal` the check raised. Any other exception leaves the block with no decision + row from it, which is right for the :func:`_mfa_refusal` 403: it wrote its own + ``auth.mfa_denied`` row where it was raised. A failed refusal-row write raises in place of the + refusal, so the request is still refused.""" try: yield except _GateRefusal as refusal: - audited = _audited_permission(request, permissions) - if audited is not None: - await auth.audit_gate_refused( - identity, - audited, - request.url.path, - reason=refusal.reason, - client=client_ip(request), - ) + await _record_gate_refusal(request, auth, identity, permissions, refusal) raise await _record_grant(request, auth, identity, permissions) +async def _record_gate_refusal( + request: Request, + auth: AuthService, + identity: Identity, + permissions: tuple[Permission, ...], + refusal: _GateRefusal, +) -> None: + """Write the ``auth.gate_refused`` row for ``refusal``, where a grant row would have been.""" + audited = _audited_permission(request, permissions) + if audited is not None: + await auth.audit_gate_refused( + identity, + audited, + request.url.path, + reason=refusal.reason, + client=client_ip(request), + ) + + +@dataclass(frozen=True) +class _AdmittedDecision: + """What a ``proof_in_route`` gate admitted, kept for the refusal row its route body may owe.""" + + auth: AuthService + identity: Identity + permissions: tuple[Permission, ...] + + +#: The ``request.state`` attribute a ``proof_in_route`` gate leaves its :class:`_AdmittedDecision` on. +_ADMITTED_DECISION_ATTR = "mefor_admitted_decision" + + +async def _record_route_refusal(request: Request, refusal: _GateRefusal) -> None: + """Record a step-up refusal a route body makes after its ``proof_in_route`` gate admitted it. + + BACKLOG #1197 (ASVS 16.3.2), for the refusals of :func:`spend_step_up_action` and + :func:`refuse_unless_step_up_window_live`. This is where the rule for their row is stated. It + writes ``auth.gate_refused``, through the writer the gate's own refusals use, only where the + admitting ``proof_in_route`` gate left its decision on ``request.state`` and + :func:`_audited_permission` names a permission for the request, which is where that gate wrote + its grant row. Where the gate wrote no grant row it writes none and logs nothing. With no + admitting gate it logs a WARNING and writes none. The caller raises the refusal either way.""" + admitted = getattr(request.state, _ADMITTED_DECISION_ATTR, None) + if not isinstance(admitted, _AdmittedDecision): + log.warning( + "a route-body step-up refusal has no admitting proof_in_route gate to record against:" + " path=%s", + scrub_log_argument(request.url.path), + ) + return + await _record_gate_refusal( + request, admitted.auth, admitted.identity, admitted.permissions, refusal + ) + + #: The step-up refusal's detail for a session whose step-up is a password or directory re-proof. #: Clients and tests read it, so it stays byte-for-byte what it was before BACKLOG #2158. _STEP_UP_DETAIL = "step-up re-verification required; POST /me/reauth then retry" @@ -1520,7 +1572,7 @@ async def _recorded_decision( async def _step_up_refusal( auth: AuthService, token: str | None, action: str | None = None -) -> HTTPException: +) -> _GateRefusal: """The 403 every JSON step-up gate raises, for the session that holds ``token``. One place for the step-up raise sites (BACKLOG #2158), at least the four ``require_step_up*`` @@ -2139,6 +2191,13 @@ async def dependency(request: Request) -> Identity: raise await _step_up_refusal(auth, token, action) elif new_ip or not await _action_step_up_ok(auth, token, action): raise await _step_up_refusal(auth, token, action) + if proof_in_route: + # For the refusal row the route body's spend may owe (_record_route_refusal). + setattr( + request.state, + _ADMITTED_DECISION_ATTR, + _AdmittedDecision(auth, identity, permissions), + ) return identity return _gate(dependency, _authenticate_session_before_body) @@ -2154,13 +2213,15 @@ async def spend_step_up_action(request: Request, action: str) -> None: ``AuthService.refund_action_step_up``, as edit-resend does for a refusal before its store write (owner ruling 2026-10-13, #3241 R1), other than one in ``_EDIT_RESEND_SPENDING_REFUSALS`` in ``api/app.py`` (owner ruling 2026-11-07, #3241 added item 1). With no auth service attached it - does nothing, as the dependency does.""" + does nothing, as the dependency does. :func:`_record_route_refusal` records its refusal.""" auth = get_auth(request) if auth is None: return token = bearer_token(request) if not await _action_step_up_ok(auth, token, action): - raise await _step_up_refusal(auth, token, action) + refusal = await _step_up_refusal(auth, token, action) + await _record_route_refusal(request, refusal) + raise refusal async def step_up_window_live(request: Request) -> bool: @@ -2184,11 +2245,14 @@ async def refuse_unless_step_up_window_live(request: Request) -> None: Moving a route to ``proof_in_route=True`` drops its dependency's window check, so without this call that branch would take no step-up at all. The 403 carries ``X-Step-Up-Required`` and no ``X-Step-Up-Action``, so a client refreshes the window with a plain ``POST /me/reauth``. Does - nothing with no auth service attached, as the dependency then checks nothing.""" + nothing with no auth service attached, as the dependency then checks nothing. + :func:`_record_route_refusal` records its refusal.""" auth = get_auth(request) if auth is None or await step_up_window_live(request): return - raise await _step_up_refusal(auth, bearer_token(request)) + refusal = await _step_up_refusal(auth, bearer_token(request)) + await _record_route_refusal(request, refusal) + raise refusal def require_reauth_only_action( diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 9cd7b5fbd4..e6471662ce 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -22120,8 +22120,9 @@ async def audit_gate_refused( The caller holds ``permission``, so this is not :meth:`audit_permission_denied`: that row says the permission was missing, and the denial-burst detector counts it. - ``_recorded_decision`` in ``api/security.py`` decides when this row is written. ``client`` - is required, as for :meth:`audit_self_target_refused`.""" + ``_recorded_decision`` in ``api/security.py`` decides when this row is written for a gate's + own refusals, and ``_record_route_refusal`` for the step-up refusals a ``proof_in_route`` + route body makes. ``client`` is required, as for :meth:`audit_self_target_refused`.""" await self._audit( "auth.gate_refused", actor=identity.username, diff --git a/messagefoundry/connection_events.py b/messagefoundry/connection_events.py index 05dc4ba6a4..469b0c0f22 100644 --- a/messagefoundry/connection_events.py +++ b/messagefoundry/connection_events.py @@ -63,6 +63,7 @@ "peer_reset", "framing_error", "handler_error", # BACKLOG #1619 + "reply_replaced", # BACKLOG #5799 "tls_handshake_failed", # vault BACKLOG #2613, #3302 "row_undecodable", # BACKLOG #1662 "file_oversize", # BACKLOG #1621, and the three below diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 1440d5bb69..1c948bae6b 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -34,6 +34,8 @@ import aiosqlite +from messagefoundry.redaction import safe_exc + __all__ = [ "IndexShape", "SchemaMismatchError", @@ -80,13 +82,21 @@ " so restarting under the old key would zero its AES-GCM use count, which lives in the store. If" " you set [secret_rotation].store_key_last_rotated, update it." ) +# The ALTER re-check names an object other than the altered table that fails to parse as +# "error in ", then ": " or a suffix, at least " after rename" and " after drop column" +# (measured on SQLite 3.50.4). Both start " after ", and _foreign_objects' ranks assume every +# suffix does. Only views and triggers get the drop remedy (see _ORDINARY_TABLE for why they are +# another tool's); SQLite uses the same form for a table or an index, which may be this build's own. +# Dropping a view or a trigger removes no row, so that remedy keeps the store and its key. +_FOREIGN_OBJECTS_SQL = "SELECT type, name FROM sqlite_master WHERE type IN ('view', 'trigger')" # The reads below skip a table whose stored SQL is LIKE 'CREATE VIRTUAL TABLE%', because a pragma # on a virtual table whose module is not loaded here can raise "no such module" (BACKLOG #6719). # The store builds none, and a test pins that, so an expected name held by a virtual table reads # as a missing table and is refused rather than skipped. -# THIS BUILD CREATES NO VIRTUAL TABLE AND NO VIEW, which tests/test_schema_verify_6719_6720.py -# pins; the other notes in this module rely on that and point here. +# THIS BUILD CREATES NO VIRTUAL TABLE, NO VIEW AND NO TRIGGER, which +# tests/test_schema_verify_6719_6720.py pins; the other notes in this module rely on that and point +# here. _ORDINARY_TABLE = "m.type = 'table' AND m.sql NOT LIKE 'CREATE VIRTUAL TABLE%'" # Each pragma is read through its table-valued form, so one statement reads every table, and the # table names travel as bound parameters rather than being spliced into SQL. Only tables the EXPECTED @@ -125,7 +135,8 @@ class SchemaMismatchError(sqlite3.DatabaseError): exits 2, the code it keeps apart from a negative finding (BACKLOG #1670). ``differences`` lists what the check found missing, one clause each. It is empty when the schema - script or a migration itself failed (BACKLOG #2101), and then ``cause`` holds that failure's text. + script, a migration or this check's own read failed (BACKLOG #2101, #6720), and then ``cause`` + holds that failure's text. Both are kept apart from the message so a caller whose remedy differs, such as a restore-verify of an old backup, can word its own refusal without parsing this one. """ @@ -338,8 +349,21 @@ async def verify_live_schema( holds a count but no store salt was last written under the DEK, so an operator shell without the service's key still gets the new-key remedy. A process that HAS a key is never overruled by the file, because a restored cell-bound store also has counts and no salt row until its first open. + + A read of the live store that fails on its shape is refused the same way, through + :func:`run_schema_step` (BACKLOG #6720): a virtual table whose stored SQL the + ``_ORDINARY_TABLE`` predicate does not recognise, held under an expected name, raises "no such + module" from the column read rather than reading as a difference. The expected shape is built + outside that, so a failure of this build's own script or migrations keeps its own error. """ - problems = await live_schema_differences(db, schema=schema, migrate=migrate) + expected = await _expected_shape(schema, migrate) + live = await run_schema_step( + db, + read_schema_shape(db, sorted(expected.columns)), + path=path, + counts_under_dek=counts_under_dek, + ) + problems = schema_differences(expected, live) if problems: if counts_under_dek is None: counts_under_dek = await _counts_under_a_dek(db) @@ -375,7 +399,8 @@ async def verify_live_schema( def is_schema_step_error(exc: BaseException) -> bool: - """Whether ``exc``, raised by the schema script or a migration, says the store's shape is wrong. + """Whether ``exc``, raised by the schema script, a migration or the verify's read of the live + store, says the store's shape is wrong. Two tests, both needed. The code must be SQLite's generic ``SQLITE_ERROR``: a busy or locked file, a read-only file, an I/O error, a full disk and a corrupt file each carry their own primary @@ -393,34 +418,128 @@ def is_schema_step_error(exc: BaseException) -> bool: ) -async def run_schema_step( +async def run_schema_step[T]( db: aiosqlite.Connection, - step: Awaitable[object], + step: Awaitable[T], *, path: object, counts_under_dek: bool | None, -) -> None: - """Await the schema script or the migrations, turning a shape failure into a refusal. +) -> T: + """Await the schema script, the migrations or the verify's read of the live store, turning a + shape failure into a refusal, and return what the step returned. A failure :func:`is_schema_step_error` accepts is raised as :class:`SchemaMismatchError`, from the original so the driver's text stays in the chain (BACKLOG #2101). It carries the remedy a verify refusal carries, chosen the same way: a statement that fails on an existing object's shape is the same incompatible version the verify reports, found one step earlier. Any other - failure propagates unchanged.""" + failure propagates unchanged. + + One shape failure gets another remedy: SQLite's re-check of the schema after an ``ALTER`` + names the view or trigger it could not parse, as in "error in view V: no such module". That + object is another tool's (see ``_ORDINARY_TABLE``), and dropping it lets the migration run past + it (BACKLOG #6719). The remedy names that object only where the text fits exactly one (see + :func:`_foreign_objects`) and the whole remedy survives :func:`~messagefoundry.redaction.safe_exc` + uncut and unredacted; otherwise it is the plain remedy. A view under a name this build creates + is not such an object: it holds the place of a table or index, which is the incompatible store + the plain remedy names.""" try: - await step + return await step except Exception as exc: if not is_schema_step_error(exc): raise + cause = str(exc) + foreign = await _foreign_objects(db, cause) + if len(foreign) == 1: + ((kind, name),) = foreign + remedy = ( + f"store {path}: save the CREATE statement of the {kind} {name!r} from sqlite_master," + " drop it, and restart." + ) + refusal = SchemaMismatchError( + f"{remedy} This build did not create it, and it stops the store's upgrade. The" + f" schema step failed: {cause}.", + cause=cause, + ) + # Named only where safe_exc shows the whole remedy, path and name, unchanged; any cut + # or redaction falls back to the plain remedy. + if remedy in safe_exc(refusal): + raise refusal from exc if counts_under_dek is None: counts_under_dek = await _counts_under_a_dek(db) - cause = str(exc) raise SchemaMismatchError( f"store {path} {_remedy(counts_under_dek)} The schema step failed: {cause}.", cause=cause, ) from exc +async def _foreign_objects(db: aiosqlite.Connection, cause: str) -> tuple[tuple[str, str], ...]: + """The kind and name of each of another tool's views and triggers that ``cause`` may name, + sorted, else empty. + + The name is matched against the live file's views and triggers, never cut out of the text: the + text may add a suffix after the name, and a quoted name may hold a colon. A SQLite error while + telling falls back to empty, the plain remedy. + + Several names can fit one text (the forms are in the note above ``_FOREIGN_OBJECTS_SQL``): + ``vv`` and ``vv after`` both fit "error in view vv after rename: ...". A name whose remainder + starts with ": " or with " after " ranks first, and any other name last. Every name of the first + rank is returned, and the code does not pick among them. Some pairs no rule over the text can + settle: SQLite writes "error in view vv after drop column: no such column: c" when ``vv`` breaks + under the change, and the same text when a view named ``vv after drop column`` was broken + already. Other pairs a list of SQLite's suffixes or messages could settle: ``vv`` against ``vv + after`` for "error in view vv after after drop column: ...", and, with ``vv`` and ``vv: no such + column``, ``vv``'s own "error in view vv: no such column: c", which fits the other name only if + SQLite's message were the bare "c". The code keeps no such list, because only some suffixes and + messages are measured and a list that missed one would name a healthy object alone. The + " after " rank is itself a one-entry suffix assumption, with a residual of the same kind: a + suffix SQLite writes that does not start " after " would rank the culprit last, and then at + least a healthy first-rank name could be named alone. Under a + suffix " during x", for one, which no test here has measured, a healthy ``vv during x`` beside + a broken ``vv`` would be named for "error in view vv during x: ...". So where names collide the + ambiguity remains, and more than one name is returned, which gets the plain remedy. + + The colon and " after " share a rank because a quoted name may hold either: with ``vv`` and + ``vv: x``, "error in view vv: x after rename: ..." must not name ``vv`` alone. Where any name + returned is a view under a name this build creates, the result is empty: that view holds the + place of a table or index, so the store is the incompatible one the plain remedy names, whichever + candidate stopped the change (see :func:`run_schema_step`). + + Preparing each candidate against the live file is not used to settle a tie. A view that only + the change broke prepares as cleanly as a healthy one, since the failed ``ALTER`` is rolled + back. A failed prepare could rule out only the other reading, an object broken already, and + that rests on SQLite writing no suffix for an object it found broken before the change, which + this module has not measured for every ``ALTER``; a wrong ruling-out would name a healthy object + alone. A trigger also has no read that runs its body without a write.""" + try: + async with db.execute(_FOREIGN_OBJECTS_SQL) as cur: + objects = [(str(kind), str(name)) for kind, name in await cur.fetchall()] + first: list[tuple[str, str]] = [] + for kind, name in objects: + rest = cause.removeprefix(f"error in {kind} {name}") + if rest != cause and rest.startswith((": ", " after ")): + first.append((kind, name)) + named = first + if not named: + return () + views = [name.lower() for kind, name in named if kind == "view"] + # Only a view can hold an expected name's place, so a trigger needs no scratch build. + if views and not (await _names_this_build_creates()).isdisjoint(views): + return () + except sqlite3.Error as exc: + log.warning("could not read the views and triggers to pick the schema remedy: %s", exc) + return () + return tuple(sorted(named)) + + +async def _names_this_build_creates() -> frozenset[str]: + """Every table and named index this build's SQLite schema and migrations create.""" + # Imported here, as _expected_shape imports from store.py: store.py imports this module. + from messagefoundry.store.store import _SCHEMA, MessageStore + + shape = await _expected_shape(_SCHEMA, MessageStore._migrate) + return frozenset(shape.columns) | frozenset(shape.named_indexes) + + async def _counts_under_a_dek(db: aiosqlite.Connection) -> bool: """Whether the live file records AES-GCM use but has no store salt: it was opened keyed, and only by a writer that seals under the DEK itself (ADR 0196). A cell-bound writer mints the salt diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index 056a41eabc..1d0e3e41b8 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -40,19 +40,28 @@ DDL the reader cannot place raises ``ValueError`` rather than being skipped or misread, at least: a ``CREATE ... INDEX``, ``CREATE TABLE``, ``DROP TABLE``, ``DROP INDEX`` or ``sp_rename`` its patterns do not match, an ``ALTER TABLE`` with more than one clause or an action it does not know, a table rename, -a ``USING`` access method, a key column or expression carrying a collation, an operator class or a -``NULLS`` order, a column type or clause it does not know, a SQL Server column that leaves its -nullability to the session, and a ``--`` or ``/*`` inside a quoted string, which may be dynamic SQL's -comment or a literal's text. A unit test reads each shipped batch, so a new form fails there before -it reaches an open. +an ``ALTER INDEX``, a second ``CREATE TABLE`` of a table no ``DROP`` removed, a ``USING`` access +method, a key column or expression carrying a collation, an operator class or a ``NULLS`` order, a key +that opens with a ``::`` or ``CAST`` cast of a column, a key built ``USING INDEX``, a SQL Server +inline ``INDEX``, a ``NOT NULL`` table constraint, a column type or clause it does not know, a SQL +Server column that leaves its nullability to the session, ``COLLATE CATALOG_DEFAULT``, and a ``--`` +or ``/*`` inside a quoted string, which may be dynamic SQL's comment or a literal's text. A unit test +reads each shipped batch, so a new form fails there before it reaches an open. + +Not every misread raises (BACKLOG #5062). At least: DDL text inside a string literal is read as run, +and an ``ALTER COLUMN`` is read as reaching only an older store, whether or not either holds. A +``DROP COLUMN`` raises where the reader finds the column's name among the words of an expression, +``INCLUDE`` or partial index on its table, other than as a key column, but that word search can miss +a name, so a ``DROP COLUMN`` that should raise may instead keep an index PostgreSQL drops. What is NOT compared includes at least: a column's default, other than whether PostgreSQL's is a ``nextval()`` call, which reads as numbering; a PostgreSQL column's collation; constraint indexes (a ``PRIMARY KEY`` or ``UNIQUE`` declared on the table); ``CHECK`` and foreign keys; an index's ``INCLUDE`` list and storage options; and a partial index's predicate, of which only its presence is compared. A default is not compared because each catalog prints it in its own rewritten form -(PostgreSQL ``''::text``, SQL Server ``((0))``), and a missing one fails the first insert that relies -on it rather than passing silently. An index that exists but cannot serve, such as +(PostgreSQL ``''::text``, SQL Server ``((0))``). A missing one on a ``NOT NULL`` column fails the +first insert that relies on it; on a column that takes NULL, that insert stores NULL and nothing +fails. An index that exists but cannot serve, such as an invalid or non-btree one on PostgreSQL or a disabled one on SQL Server, is reported by the backend that reads it. A store whose marker already matches is not re-read at open: the ADR 0064 fast path skips the batch and this check together, so a change made by hand after the marker was written is not @@ -67,6 +76,7 @@ from __future__ import annotations +import contextlib import logging import re from collections.abc import Callable, Iterable, Mapping @@ -117,7 +127,8 @@ re.I, ) _ALTER_TABLE = re.compile( - rf"\bALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?(?P{_NAME})(?=\s)", re.I + rf"\bALTER\s+TABLE\s+(?!(?:IF\s+EXISTS\s+)?#)(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?(?P
{_NAME})(?=\s)", + re.I, ) #: What may follow a DROP's last name: the statement's end, or a word that starts the next one. Any #: other text, such as ``DROP TABLE public . t``, leaves the strict pattern unmatched, so it raises. @@ -153,12 +164,16 @@ ) #: Every place a table or an index is created, dropped or renamed, read loosely, so a form the #: patterns above miss is counted and refused rather than silently left unchecked. A ``#`` temporary -#: table is not the store's. +#: table is not the store's, behind an ``IF [NOT] EXISTS`` guard too, but a ``DROP TABLE`` whose +#: list goes on past one is counted, so the strict pattern's miss raises. _LOOSE: Final = ( - (re.compile(r"\bCREATE\s+TABLE\s+(?!#)", re.I), _CREATE_TABLE), + (re.compile(r"\bCREATE\s+TABLE\s+(?!\s|(?:IF\s+NOT\s+EXISTS\s+)?#)", re.I), _CREATE_TABLE), (re.compile(r"\bCREATE\s+(?:UNIQUE\s+)?(?:(?:NON)?CLUSTERED\s+)?INDEX\b", re.I), _CREATE_INDEX), - (re.compile(r"\bALTER\s+TABLE\s+(?!#)", re.I), _ALTER_TABLE), - (re.compile(r"\bDROP\s+TABLE\s+(?!#)", re.I), _DROP_TABLE), + (re.compile(r"\bALTER\s+TABLE\s+(?!\s|(?:IF\s+EXISTS\s+)?#)", re.I), _ALTER_TABLE), + ( + re.compile(r"\bDROP\s+TABLE\s+(?!\s|(?:IF\s+EXISTS\s+)?#[\w$@#]++(?!\s*,))", re.I), + _DROP_TABLE, + ), (re.compile(r"\bDROP\s+INDEX\b", re.I), _DROP_INDEX), (re.compile(r"\bsp_rename\b", re.I), _SP_RENAME), ) @@ -172,6 +187,9 @@ {"constraint", "primary", "unique", "check", "foreign", "exclude", "default", "period", "index"} ) _TABLE_PRIMARY_KEY = re.compile(r"\bPRIMARY\s+KEY\s*(?:(?:NON)?CLUSTERED\s*)?\(", re.I) +#: PostgreSQL's ``PRIMARY KEY`` or ``UNIQUE`` ``USING INDEX ``, which turns an existing index +#: into the constraint. ``USING INDEX TABLESPACE`` is only a storage option. +_USING_INDEX = re.compile(r"\bUSING\s+INDEX\b(?!\s*TABLESPACE\b)", re.I) _PLAIN_KEY = re.compile(r'^(\[?[A-Za-z_][\w$]*\]?|"[^"]+")(?:\s+(ASC|DESC))?$', re.I) _PLAIN_NAME = re.compile(r'^(?:\[?[A-Za-z_][\w$]*\]?|"[^"]+")$') #: A key that is an expression: a call such as ``left(actor, 200)``, or a parenthesised expression. @@ -183,6 +201,17 @@ #: The words a statement inside a block starts with, at which an ``ALTER TABLE`` clause has ended #: when no ``;`` closes it. None can appear inside a column definition. _STATEMENT_START = frozenset({"if", "begin", "end", "exec", "execute", "else", "declare", "go"}) +#: The words after which a data word is a name: a column's, a constraint's, a referenced table's +#: or a rename's new name. After ``ON`` it is a foreign key's action. +_NAME_BEFORE = frozenset({"on", "add", "column", "exists", "constraint", "references", "to"}) +#: Words that start a data statement, which a clause ends at unless a word in ``_NAME_BEFORE`` +#: precedes them (BACKLOG #5062: an ``ADD CONSTRAINT`` read on into the next statement took that +#: statement's ``PRIMARY KEY`` as its own). +_DATA_STATEMENT = frozenset({"insert", "update", "delete", "merge", "select", "truncate"}) +#: What an ``ALTER`` or ``DROP`` that starts the next statement names, after the word itself. +_DDL_OBJECT = re.compile( + r"\s+(?:TABLE|INDEX|VIEW|PROC|PROCEDURE|TRIGGER|FUNCTION|SEQUENCE|SCHEMA|TYPE|DATABASE)\b", re.I +) _TOKEN = re.compile(r"""N?'(?:[^']|'')*'|"[^"]*"|\[[^\]]*\]|\w+|\S""") @@ -312,18 +341,38 @@ def _string_spans(text: str) -> list[tuple[int, int]]: return spans +def _quoted_end(text: str, i: int) -> int | None: + """The index after the quoted run that opens at ``text[i]``: a ``'`` string, a ``"`` name or a + SQL Server ``[...]`` name, in which a doubled close continues the run. ``None`` when ``text[i]`` + opens none. :func:`_balanced`, :func:`_top_level_items` and :func:`_clause` share it, so a + ``[a,b]`` or ``[end]`` reads as one name in each. A ``[`` that holds another ``[``, or that no + ``]`` closes, is a PostgreSQL subscript, as in ``a[b[1]]``, and opens none.""" + ch = text[i] + if ch not in "'\"[": + return None + if ch == "[" and i > 0 and (text[i - 1].isalnum() or text[i - 1] in "_$]"): + return None # a subscript or an ARRAY[...] literal, as in ARRAY[']'] + close = "]" if ch == "[" else ch + j = i + 1 + while (end := text.find(close, j)) >= 0: + if not text.startswith(close * 2, end): + return None if ch == "[" and "[" in text[i + 1 : end] else end + 1 + j = end + 2 + if ch == "[": + return None + raise ValueError(f"unterminated quote in DDL near {text[i : i + 40]!r}") + + def _balanced(text: str, start: int) -> tuple[str, int]: """The text inside the parenthesis opened at ``text[start - 1]``, and the index after its close. Quoted text is skipped, so a parenthesis inside a string literal does not count.""" - depth, i, quote = 1, start, "" + depth, i = 1, start while i < len(text): + if (end := _quoted_end(text, i)) is not None: + i = end + continue ch = text[i] - if quote: - if ch == quote: - quote = "" - elif ch in "'\"": - quote = ch - elif ch == "(": + if ch == "(": depth += 1 elif ch == ")": depth -= 1 @@ -336,24 +385,21 @@ def _balanced(text: str, start: int) -> tuple[str, int]: def _top_level_items(body: str) -> list[str]: """``body`` split on its top-level commas, so a ``DECIMAL(10, 2)`` stays one item.""" items: list[str] = [] - current: list[str] = [] - depth, quote = 0, "" - for ch in body: - if quote: - if ch == quote: - quote = "" - elif ch in "'\"": - quote = ch - elif ch == "(": + depth, i, last = 0, 0, 0 + while i < len(body): + if (end := _quoted_end(body, i)) is not None: + i = end + continue + ch = body[i] + if ch == "(": depth += 1 elif ch == ")": depth -= 1 elif ch == "," and depth == 0: - items.append("".join(current)) - current = [] - continue - current.append(ch) - items.append("".join(current)) + items.append(body[last:i]) + last = i + 1 + i += 1 + items.append(body[last:]) return [item.strip() for item in items if item.strip()] @@ -371,15 +417,13 @@ def _clause(segment: str) -> str: """The one clause of an ``ALTER TABLE`` that ``segment`` starts with: up to a top-level ``;``, an unmatched ``)``, a word that starts the next statement, or the end. A top-level comma means more than one clause, which raises.""" - depth, quote, i, n = 0, "", 0, len(segment) + depth, i, n, prev = 0, 0, len(segment), "" while i < n: + if (end := _quoted_end(segment, i)) is not None: + i, prev = end, "" + continue ch = segment[i] - if quote: - if ch == quote: - quote = "" - elif ch in "'\"": - quote = ch - elif ch == "(": + if ch == "(": depth += 1 elif ch == ")": if depth == 0: @@ -394,17 +438,69 @@ def _clause(segment: str) -> str: ): word = re.match(r"\w+", segment[i:]) assert word is not None + lower = word.group(0).lower() after = segment[i + len(word.group(0)) :] - if word.group(0).lower() in _STATEMENT_START and not ( - word.group(0).lower() == "if" and re.match(r"\s+(?:NOT\s+)?EXISTS\b", after, re.I) + if lower in _STATEMENT_START and not ( + lower == "if" and re.match(r"\s+(?:NOT\s+)?EXISTS\b(?!\s*\()", after, re.I) + ): + break + # A data or DDL statement starts here too. ON DELETE and ON UPDATE are a foreign + # key's actions, and the word after ADD [COLUMN] [IF NOT EXISTS] is a column's + # name; ALTER COLUMN and DROP COLUMN are the clause's own verbs. + if ( + lower == "create" + or (lower in _DATA_STATEMENT and prev not in _NAME_BEFORE) + or (lower in ("alter", "drop") and _DDL_OBJECT.match(after)) ): break + prev = lower i += len(word.group(0)) continue i += 1 return segment[:i].strip() +def _statement_end(text: str, start: int, dialect: Dialect | None) -> int: + """Where the statement that ``text[start:]`` continues ends: a top-level ``;``, an unmatched + ``)``, a word that starts the next statement, or the end. Unlike :func:`_clause` it reads on + through ``ELSE`` and ``END``, which a ``CASE`` in an index predicate holds, so it may read into a + following block. Off SQL Server it reads through a data word too, which PostgreSQL takes as a + column's name, so it may also read into a following statement; on SQL Server a data word is + reserved and ends it.""" + depth, i = 0, start + while i < len(text): + if (end := _quoted_end(text, i)) is not None: + i = end + continue + ch = text[i] + if ch == "(": + depth += 1 + elif ch == ")": + if depth == 0: + break + depth -= 1 + elif depth == 0 and ch == ";": + break + elif ( + depth == 0 + and (ch.isalpha() or ch == "_") + and not (text[i - 1].isalnum() or text[i - 1] in "_$") + ): + word = re.match(r"[\w$]+", text[i:]) + assert word is not None + lower = word.group(0).lower() + if ( + lower in ("if", "begin", "exec", "execute", "declare", "go", "create") + or (dialect == "sqlserver" and lower in _DATA_STATEMENT) + or (lower in ("alter", "drop") and _DDL_OBJECT.match(text, i + len(lower))) + ): + break + i += len(lower) + continue + i += 1 + return i + + # The types each catalog spells one way, keyed by every spelling the DDL may use. The live read # compares against these spellings: PostgreSQL's format_type() and SQL Server's sys.types names. _PG_TYPES: Final = MappingProxyType( @@ -623,7 +719,9 @@ def word(k: int) -> str: i = _skip_group(tokens, i) elif w == "default" and i + 1 < len(tokens): numbered_default = dialect == "postgres" and _numbers(" ".join(tokens[i + 1 :])) - i += 2 if tokens[i + 1] not in "+-" else 3 + i += 3 if tokens[i + 1] in ("+", "-") else 2 + if i > len(tokens): # a sign with nothing after it + raise ValueError(f"a default the live-schema check cannot read: {text!r}") if tokens[i - 1] == "(": i = _skip_group(tokens, i - 1) elif word(i) == "(": @@ -634,6 +732,11 @@ def word(k: int) -> str: if dialect == "postgres": raise ValueError(f"a PostgreSQL column collation is not compared: {text!r}") collation, i = _ident(tokens[i + 1]), i + 2 + if collation == "database_default": + collation = None # the database's own, which an expected None matches + elif collation == "catalog_default": + # The metadata catalog's collation, which the live read cannot tell apart. + raise ValueError(f"a catalog_default collation is not compared: {text!r}") elif w == "identity" and dialect == "sqlserver": identity, i = True, i + 1 if word(i) == "(": @@ -700,6 +803,8 @@ def _declared_key(text: str) -> str: inner = inner[1:-1].strip() if _PLAIN_NAME.match(inner): key = inner + elif _casts_a_column(inner): + raise ValueError(f"index key {text!r} is a cast the live-schema check cannot place") elif inner != key and re.search(r"\bCOLLATE\b", inner, re.I): # PostgreSQL stores ((col COLLATE x)) as the column with an index collation. raise ValueError(f"index key {text!r} carries options the live-schema check cannot compare") @@ -716,6 +821,22 @@ def _declared_key(text: str) -> str: return key_column(key) +def _casts_a_column(key: str) -> bool: + """Whether ``key`` opens with a cast of a column: ``a::text``, ``(a)::text`` or + ``CAST(a AS text)``. PostgreSQL stores a cast to the column's own type as the column, and any + other as an expression, and the reader does not know which. Read by hand, not by one pattern, because the parentheses around the name + repeat and a pattern for them nests one quantifier in another.""" + cast = re.match(r"CAST\s*\(", key, re.I) + rest = (key[cast.end() :] if cast else key).lstrip("( \t\r\n") + name = re.match(r'"[^"]+"|\w+', rest) + if name is None: + return False + after = rest[name.end() :].lstrip(") \t\r\n") + if cast: + return after != rest[name.end() :] and re.match(r"AS\b", after, re.I) is not None + return after.startswith("::") + + def _expression_end(key: str) -> int | None: """Where the expression that opens ``key`` ends, or ``None`` when ``key`` does not open with one or its parentheses do not balance.""" @@ -773,10 +894,46 @@ def altered(self, change: Callable[[ColumnShape], ColumnShape]) -> None: def _pk_columns(text: str) -> set[str]: """The columns of a ``PRIMARY KEY (...)`` in ``text``, a table item or an ``ADD CONSTRAINT``.""" - if (pk := _TABLE_PRIMARY_KEY.search(text)) is None: + # A string literal's text, as in a CHECK, is blanked first, so a PRIMARY KEY or USING INDEX + # inside one is not taken for the item's own. + parts: list[str] = [] + last = 0 + for start, end in _string_spans(text): + parts += [text[last : start + 1], " " * (end - start - 2)] + last = end - 1 + blanked = "".join([*parts, text[last:]]) + if _USING_INDEX.search(blanked): + raise ValueError(f"a key built from an existing index is not compared: {text[:120]!r}") + if (pk := _TABLE_PRIMARY_KEY.search(blanked)) is None: return set() inner, _ = _balanced(text, pk.end()) - return {_bare(k.split()[0]) for k in _top_level_items(inner)} + return {_bare(_TOKEN.findall(k)[0]) for k in _top_level_items(inner)} + + +def _is_constraint(item: str, dialect: Dialect | None) -> bool: + """Whether a table item, or what follows an ``ADD`` without ``COLUMN``, is a constraint rather + than a column. A SQL Server inline ``INDEX`` raises, because it builds a named index the reader + does not model, except on PostgreSQL, where ``index`` is a column's name, and so do + ``PERIOD`` and ``EXCLUDE`` when what follows is not their constraint's + own shape, because each may also be a column's name. A ``NOT NULL`` table constraint raises: + the reader does not apply it.""" + if re.match( + r'(?:CONSTRAINT\s+(?:"(?:[^"]|"")*"|\[(?:[^\]]|\]\])*\]|[\w$]+)\s+)?NOT\s+NULL\b', + item, + re.I, + ): + # PostgreSQL 18's NOT NULL table constraint, perhaps NOT VALID. + raise ValueError(f"a not-null constraint is not compared: {item[:120]!r}") + words = [w.lower() for w in _TOKEN.findall(item)[:2]] + [""] + if words[0] not in _NOT_A_COLUMN or (words[0] == "index" and dialect == "postgres"): + return False + if words[0] == "index": + raise ValueError(f"an inline index the live-schema check does not compare: {item[:120]!r}") + if (words[0] == "period" and words[1] != "for") or ( + words[0] == "exclude" and words[1] not in ("(", "using") + ): + raise ValueError(f"a table item the live-schema check cannot place: {item[:120]!r}") + return True class _Reader: @@ -788,15 +945,31 @@ def __init__(self, dialect: Dialect | None) -> None: self.dialect = dialect self.columns: dict[str, dict[str, _Built]] = {} self.indexes: dict[str, IndexShape] = {} + #: The words of each index whose key, INCLUDE list or predicate may name a column its key + #: columns do not show: an expression key, an INCLUDE or a WHERE, with its plain key + #: columns. A DROP COLUMN of one of those words that is not a key column raises, because + #: PostgreSQL drops such an index and the reader cannot tell. Keyed by table and index, + #: because a SQL Server index name is unique only within its table. + self.opaque: dict[tuple[str, str], tuple[frozenset[str], frozenset[str]]] = {} + #: The tables a CREATE TABLE has built and no DROP TABLE has removed since. + self.created: set[str] = set() def table(self, text: str, m: re.Match[str]) -> None: body, _end = _balanced(text, m.end()) - cols = self.columns.setdefault(_bare(m["name"]), {}) + table = _bare(m["name"]) + if table in self.created: + # A guarded second CREATE TABLE never runs: the first one built the table. + raise ValueError( + f"a second create table of {table}: its guard skips it, or it names a table of" + " another schema, which the reader does not tell apart" + ) + self.created.add(table) + cols = self.columns.setdefault(table, {}) keys: set[str] = set() pending: list[tuple[str, _Column, str]] = [] for item in _top_level_items(body): - first = item.split()[0] - if first.lower() in _NOT_A_COLUMN: + first = _TOKEN.findall(item)[0] + if _is_constraint(item, self.dialect): keys |= _pk_columns(item) elif self.dialect is None: cols.setdefault(_bare(first), _Built()) @@ -817,16 +990,38 @@ def index(self, text: str, m: re.Match[str]) -> None: if m["using"]: raise ValueError(f"index access method not compared: {m.group(0)!r}") body, end = _balanced(text, m.end()) + include = False while clause := _INDEX_TAIL.match(text, end): end = clause.end() + include = include or clause.group(0).lstrip().upper().startswith("INCLUDE") if text[end - 1] == "(": end = _balanced(text, end)[1] - self.indexes[_bare(m["name"])] = IndexShape( + name = _bare(m["name"]) + shape = IndexShape( _bare(m["table"]), tuple(_declared_key(item) for item in _top_level_items(body)), bool(m["unique"]), text[end:].lstrip().upper().startswith("WHERE"), ) + self.indexes[name] = shape + self.opaque.pop((shape.table, name), None) + if include or shape.partial or any(k.startswith("") for k in shape.columns): + # To the statement's end: a predicate has no closing mark of its own. Inside an + # EXEC string, to the string's end, its quotes undoubled, as alter() reads one. + tail = text[end:] + for start, stop in _string_spans(text): + if start < m.start() < stop: + tail = text[end : stop - 1].replace("''", "'") + break + tail = " " + tail # so the scan never starts at index 0 + # Nested dynamic SQL's quotes can defeat the scan: keep it all, which only raises more. + with contextlib.suppress(ValueError): + tail = tail[: _statement_end(tail, 1, self.dialect)] + definition = text[m.end() : end] + tail + self.opaque[(shape.table, name)] = ( + frozenset(_ident(w) for w in _TOKEN.findall(definition)), + frozenset(k.split(" ", 1)[0] for k in shape.columns), + ) def _built(self, table: str, name: str, action: str) -> _Built: cols = self.columns.get(table) @@ -846,21 +1041,38 @@ def alter(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> No words = clause.split() verb = [w.lower() for w in words[:2]] if verb[:1] == ["add"]: - rest = re.sub(r"^ADD\s+(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?", "", clause, flags=re.I) - first = rest.split()[0].lower() if rest.split() else "" - if first in _NOT_A_COLUMN: + head = re.match(r"ADD(\s+COLUMN\b)?\s*(?:IF\s+NOT\s+EXISTS\b\s*)?", clause, re.I) + assert head is not None + rest = clause[head.end() :] + if not rest: + raise ValueError(f"an add with nothing to add: {clause!r}") + # After ADD COLUMN what follows is a column, whatever its name (BACKLOG #5062). + if not head.group(1) and _is_constraint(rest, self.dialect): for key in _pk_columns(rest): self._not_null(table, key) return if self.dialect is None: - self.columns.setdefault(table, {}).setdefault(_bare(rest.split()[0]), _Built()) + self.columns.setdefault(table, {}).setdefault( + _bare(_TOKEN.findall(rest)[0]), _Built() + ) return name, col = _read_column(self.dialect, rest) built = self.columns.setdefault(table, {}).setdefault(name, _Built()) built.later.add(_finish(self.dialect, col, rest)) elif verb == ["drop", "column"]: name = re.sub(r"^DROP\s+COLUMN\s+(?:IF\s+EXISTS\s+)?", "", clause, flags=re.I) - column = _bare(name.split()[0]) + column = _bare(_TOKEN.findall(name)[0]) + for (on, index), (used, keys) in list(self.opaque.items()): + if on != table or column not in used: + continue + if column in keys: + # A key column takes the index with it, as _rewrite_keys below does. + del self.opaque[(on, index)] + else: + raise ValueError( + f"a drop column of {table}.{column}, which index {index}'s expression," + " INCLUDE or predicate may use, so the reader cannot tell whether it goes" + ) self.columns.get(table, {}).pop(column, None) # PostgreSQL drops an index on a dropped column; SQL Server refuses the drop. self._rewrite_keys(table, column, None) @@ -870,7 +1082,7 @@ def alter(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> No return # a table's storage options, such as LOCK_ESCALATION: not compared elif verb == ["alter", "column"]: self._alter_column(table, clause, words) - elif verb[:1] == ["rename"] and len(words) == 5 and words[1].lower() == "column": + elif verb == ["rename", "column"] and len(words) == 5 and words[3].lower() == "to": self._rename(table, _bare(words[2]), _bare(words[4])) else: raise ValueError(f"an alter table the live-schema check cannot read: {clause[:120]!r}") @@ -943,6 +1155,12 @@ def _rename(self, table: str, old: str, new: str) -> None: if moved is not None: built.later |= moved.ways() self._rewrite_keys(table, old, new) + for (on, index), (used, keys) in list(self.opaque.items()): + if on == table: + self.opaque[(on, index)] = ( + (used - {old}) | ({new} if old in used else set()), + (keys - {old}) | ({new} if old in keys else set()), + ) def rename(self, m: re.Match[str]) -> None: if m["old"].count(".") != 1: @@ -954,8 +1172,11 @@ def drop_tables(self, m: re.Match[str]) -> None: for name in _dropped(m, _DROPPED_TABLE): table = _bare(name) self.columns.pop(table, None) + self.created.discard(table) for index in [n for n, shape in self.indexes.items() if shape.table == table]: del self.indexes[index] + for key in [k for k in self.opaque if k[0] == table]: + del self.opaque[key] def drop_indexes(self, m: re.Match[str]) -> None: """Each index named, but on SQL Server only on the table its ``ON`` names: a name is unique @@ -964,9 +1185,14 @@ def drop_indexes(self, m: re.Match[str]) -> None: parts = item.split() name = _bare(parts[0]) on = _bare(parts[-1]) if len(parts) == 3 else None + if on is None and self.dialect == "sqlserver" and "." in parts[0]: + # SQL Server's legacy DROP INDEX
.. + on = _bare(parts[0].rsplit(".", 1)[0]) shape = self.indexes.get(name) if shape is not None and (on is None or shape.table == on): del self.indexes[name] + for key in [k for k in self.opaque if k[1] == name and on in (None, k[0])]: + del self.opaque[key] def shape(self) -> ServerSchemaShape: shapes: dict[str, Mapping[str, ColumnShape]] = {} @@ -977,8 +1203,8 @@ def shape(self) -> ServerSchemaShape: if len(ways) > 1: listed = " and ".join(sorted(s.describe() for s in ways)) raise ValueError( - f"column {table}.{name} is built two ways, as {listed}: a guarded ADD," - " an alter column or a second create table disagrees with the first" + f"column {table}.{name} is built two ways, as {listed}: its create" + " table, a guarded ADD or an alter column disagree" ) if ways: one[name] = next(iter(ways)) @@ -1008,8 +1234,12 @@ def declared_schema( for loose, strict in _LOOSE: if len(loose.findall(text)) != len(strict.findall(text)): raise ValueError(f"DDL the live-schema check cannot read: {text.strip()[:120]!r}") - if re.search(r"\bRENAME\s+TO\b|\bALTER\s+INDEX\b", text, re.I): + if re.search(r"\bRENAME\s+TO\b", text, re.I): raise ValueError(f"a rename the live-schema check cannot read: {text.strip()[:120]!r}") + if re.search(r"\bALTER\s+INDEX\b", text, re.I): + raise ValueError( + f"an alter index the live-schema check cannot read: {text.strip()[:120]!r}" + ) spans = _string_spans(text) events: list[tuple[int, str, re.Match[str]]] = [] for kind, pattern in ( diff --git a/messagefoundry/transports/framing.py b/messagefoundry/transports/framing.py index 735fc9ba0e..d0680b1b36 100644 --- a/messagefoundry/transports/framing.py +++ b/messagefoundry/transports/framing.py @@ -14,6 +14,7 @@ from __future__ import annotations import logging +import time from messagefoundry.config.wiring import _is_text_codec from messagefoundry.framing import ( @@ -36,6 +37,8 @@ __all__ = [ "FRAMING_CODE", "MULTIPLE_MESSAGES_CODE", + "REPLY_REPLACED_EVENT_SECONDS", + "ReplyReplacements", "FrameError", "FrameByteFault", "FramePayloadError", @@ -49,8 +52,10 @@ "codec_for", "declared_encoding", "encode_reply", + "encode_reply_reporting", "frame_for_delivery", "frame_reply", + "frame_reply_reporting", ] logger = logging.getLogger(__name__) @@ -69,9 +74,44 @@ _reply_fallback_logged: set[str] = set() #: The listeners whose reply-character replacement has been logged, once per connection for the -#: same reason (BACKLOG #5799): a narrow charset meets the same characters on every message. +#: same reason (BACKLOG #5799): a narrow charset meets the same characters on every message. The +#: MLLP, raw-TCP and X12 listeners also send a ``reply_replaced`` connection event, which +#: :class:`ReplyReplacements` throttles; it is stored only when connection events are captured. _reply_replacement_logged: set[str] = set() +#: The shortest gap between two ``reply_replaced`` events from one listener, the same window as the +#: ``tls_handshake_failed`` throttle. +REPLY_REPLACED_EVENT_SECONDS = 60.0 + + +class ReplyReplacements: + """One listener's throttle for its ``reply_replaced`` connection events (BACKLOG #5799). + + A narrow charset meets the same characters on every message, so one event per replaced reply + would grow with message volume and could crowd other kinds out of the runner's bounded event + queue. The first replaced reply is reported at once; after that, at most one report per + :data:`REPLY_REPLACED_EVENT_SECONDS`, made by the first replaced reply past the window and + carrying the count since the last report. Unlike the ``tls_handshake_failed`` throttle there is + no trailing report: replies counted after the last report are not reported until another reply + is replaced past the window, and not at all if none is. The reason is a count and fixed text, + never the charset setting or any part of the reply. Runs on the listener's event loop.""" + + def __init__(self) -> None: + self._unreported = 0 + self._reported_at: float | None = None + + def note(self) -> str | None: + """Count one replaced reply, and return the reason of the event due now, if one is.""" + self._unreported += 1 + now = time.monotonic() + if self._reported_at is not None and now - self._reported_at < REPLY_REPLACED_EVENT_SECONDS: + return None + count, self._unreported, self._reported_at = self._unreported, 0, now + return ( + f"{count} reply(ies) since the last report held characters the inbound charset " + "cannot encode, and each was replaced" + ) + def frame_for_delivery(codec: FrameCodec, payload: str, encoding: str, *, transport: str) -> bytes: """Frame one outbound ``payload`` for the wire, or refuse it permanently (ADR 0205 rule 1). @@ -152,19 +192,31 @@ def frame_reply(codec: FrameCodec, reply: str, encoding: str, *, connection: str frame, and an echoed control id that held a frame byte simply stops matching. A space is what the ACK builder already puts in place of an echoed CR or LF. The replacement is on bytes, for the reason :func:`frame_for_delivery` checks bytes. The reply is encoded by :func:`encode_reply`, - which says what it does with a charset that cannot hold it.""" - body = encode_reply(reply, encoding, connection=connection) + which says what it does with a charset that cannot hold it. This drops the flag saying whether + characters were replaced, so a listener calls :func:`frame_reply_reporting` instead and writes + the ``reply_replaced`` event from it (BACKLOG #5799).""" + return frame_reply_reporting(codec, reply, encoding, connection=connection)[0] + + +def frame_reply_reporting( + codec: FrameCodec, reply: str, encoding: str, *, connection: str = "" +) -> tuple[bytes, bool]: + """:func:`frame_reply`, and whether characters the charset cannot hold were replaced, so a + listener can write a ``reply_replaced`` connection event for that reply (BACKLOG #5799).""" + body, replaced = encode_reply_reporting(reply, encoding, connection=connection) if codec.start in body or codec.end in body: logger.warning( "reply held a frame start or end byte; each was replaced by a space before framing" ) # The replacement is the leaf's rule, shared with the test harness's ACK writers. - return codec.frame(codec.neutralise(body)) + return codec.frame(codec.neutralise(body)), replaced def encode_reply(reply: str, encoding: str, *, connection: str = "") -> bytes: - """Encode a listener's post-commit reply in its declared charset, for :func:`frame_reply` and - for the X12 listener, which writes its reply unframed (BACKLOG #5958). + """Encode a listener's post-commit reply in its declared charset. The listeners call + :func:`encode_reply_reporting`, which does this and also says whether characters were replaced: + :func:`frame_reply_reporting` for the MLLP and raw-TCP listeners, and the X12 listener directly, + since it writes its reply unframed (BACKLOG #5958). A reply whose charset NAME is unusable is sent in ``utf-8`` instead: a name that names no text codec, or one that refuses every conversion, would otherwise leave the ``AE`` @@ -182,6 +234,16 @@ def encode_reply(reply: str, encoding: str, *, connection: str = "") -> bytes: the warning each fallback logs, once per connection for each, since a narrow charset meets the same characters message after message. The charset setting and the reply are never logged: the setting is configuration that may hold anything, and the reply echoes the message.""" + return encode_reply_reporting(reply, encoding, connection=connection)[0] + + +def encode_reply_reporting( + reply: str, encoding: str, *, connection: str = "" +) -> tuple[bytes, bool]: + """:func:`encode_reply`, and whether characters the charset cannot hold were replaced. The + warning is logged once per connection; the flag is set on every reply replaced, for the + listener's ``reply_replaced`` connection event (BACKLOG #5799). A reply sent in ``utf-8`` + because the charset name is unusable is not a replacement, and the flag is False.""" unencodable = False try: body = reply.encode(encoding) @@ -200,8 +262,8 @@ def encode_reply(reply: str, encoding: str, *, connection: str = "") -> bytes: ) body = reply.encode("utf-8") if unencodable: - body = _encode_replacing(reply, encoding, connection) - return body + return _encode_replacing(reply, encoding, connection), True + return body, False def _encode_replacing(reply: str, encoding: str, connection: str) -> bytes: diff --git a/messagefoundry/transports/mllp.py b/messagefoundry/transports/mllp.py index 0749da33a1..13e58aad00 100644 --- a/messagefoundry/transports/mllp.py +++ b/messagefoundry/transports/mllp.py @@ -130,10 +130,11 @@ from messagefoundry.transports.base import cap_setting as _cap_setting from messagefoundry.transports.framing import ( MLLP_CODEC, + ReplyReplacements, check_frame_bytes, declared_encoding, frame_for_delivery, - frame_reply, + frame_reply_reporting, ) __all__ = [ @@ -2372,6 +2373,7 @@ def __init__(self, config: Source) -> None: self.max_messages_per_second, self.message_burst = _pacing_settings(s) # Carried only so a pacing report can name this connection (BACKLOG #290). self._pacing_name = config.name or "" + self._reply_replacements = ReplyReplacements() # BACKLOG #5799 # Per-connection peer-IP allowlist (Tier 4 operability): when set, a connecting peer whose IP # is not listed is refused before anything reads its socket -- with TLS on, that is before # the handshake, on every loop (BACKLOG #1606; see _TLS_HANDSHAKE_TIMEOUT). Absent/empty = no @@ -2995,6 +2997,12 @@ async def stop(self) -> None: logger.warning("MLLP server.wait_closed() exceeded shutdown grace; abandoning") self._server = None + async def _note_reply_replaced(self, peer_host: str | None) -> None: + """Count one replaced reply, and send the throttled ``reply_replaced`` event if one is due.""" + reason = self._reply_replacements.note() + if reason is not None: + await self._emit_event("reply_replaced", peer_host=peer_host, reason=reason) + async def _emit_event( self, kind: str, *, peer_host: str | None = None, reason: str | None = None ) -> None: @@ -3038,9 +3046,10 @@ def _owes_handler_failure_reply(self) -> bool: """ return owes_hl7_reply(self.ack_mode, self.content_type) - def _handler_failure_nak(self, message: bytes) -> bytes | None: + def _handler_failure_nak(self, message: bytes) -> tuple[bytes, bool] | None: """The framed ``AE`` NAK (``CE`` in enhanced mode) for a frame the inbound handler faulted - on, or ``None`` if none can be framed. Call it only when a reply is owed. + on, and whether characters its charset cannot hold were replaced in it, or ``None`` if none + can be framed. Call it only when a reply is owed. **Why AE.** It is this engine's code for "not accepted, and not because of what the message says". The runner answers ``AR`` for every refusal it treats as final and ``AE`` only for a @@ -3074,7 +3083,9 @@ def _handler_failure_nak(self, message: bytes) -> bytes | None: nak = build_ack( inbound, code="AE", text=_HANDLER_FAILURE_NAK_TEXT, ack_mode=self.ack_mode ) - return frame_reply(MLLP_CODEC, nak, self.encoding, connection=self._pacing_name) + return frame_reply_reporting( + MLLP_CODEC, nak, self.encoding, connection=self._pacing_name + ) except Exception as exc: # noqa: BLE001 -- fall back to the defaults, then give up logger.warning( "MLLP-level NAK for a handler fault could not be built: %s", safe_exc(exc) @@ -3114,7 +3125,8 @@ async def _answer_handler_failure( """ reason = safe_exc(exc) owed = self._owes_handler_failure_reply() - nak = self._handler_failure_nak(message) if owed else None + framed = self._handler_failure_nak(message) if owed else None + nak = None if framed is None else framed[0] if nak is not None: outcome = f"answering MSA-1 {_CODES[self.ack_mode]['AE']}, then closing the connection" elif owed: @@ -3131,6 +3143,8 @@ async def _answer_handler_failure( outcome, ) await self._emit_event("handler_error", peer_host=peer_host, reason=reason) + if framed is not None and framed[1]: + await self._note_reply_replaced(peer_host) return owed, nak async def _on_client( @@ -3309,14 +3323,18 @@ async def _on_client( failed = False if reply is not None: # ADR 0205: a reply never carries a second frame boundary. - writer.write( - frame_reply( - MLLP_CODEC, - reply, - self.encoding, - connection=self._pacing_name, - ) + wire, replaced = frame_reply_reporting( + MLLP_CODEC, + reply, + self.encoding, + connection=self._pacing_name, ) + writer.write(wire) + if replaced: + # BACKLOG #5799: a reply whose characters the charset forced + # a replacement of, throttled per listener. A frame byte + # turned into a space is not one, and writes only its warning. + await self._note_reply_replaced(peer_host) await self._drain_ack(writer) if unlisted and decoded: # BACKLOG #4907: every frame this read completed was recorded above, diff --git a/messagefoundry/transports/tcp.py b/messagefoundry/transports/tcp.py index ff0faec71c..880704ecd4 100644 --- a/messagefoundry/transports/tcp.py +++ b/messagefoundry/transports/tcp.py @@ -56,11 +56,12 @@ from messagefoundry.transports.framing import ( FrameCodec, FrameError, + ReplyReplacements, check_frame_bytes, codec_for, declared_encoding, frame_for_delivery, - frame_reply, + frame_reply_reporting, ) from messagefoundry.transports.mllp import ( DEFAULT_MAX_CONNECTIONS, @@ -538,6 +539,7 @@ def __init__(self, config: Source) -> None: ) # Carried only so a pacing report can name this connection (BACKLOG #290). self._pacing_name = config.name or "" + self._reply_replacements = ReplyReplacements() # BACKLOG #5799 # Per-connection peer-IP allowlist (Tier 4 operability): refuse a non-listed peer at accept. # Absent/empty = no restriction. Mirrors MLLPSource. sa = s.get("source_ip_allowlist") @@ -730,14 +732,18 @@ async def _on_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamW break # handler_error is recorded; close failed = False if reply is not None: - writer.write( - frame_reply( - self.codec, - reply, - self.encoding, - connection=self._pacing_name, - ) + wire, replaced = frame_reply_reporting( + self.codec, + reply, + self.encoding, + connection=self._pacing_name, ) + writer.write(wire) + if replaced and (note := self._reply_replacements.note()): + # BACKLOG #5799, throttled as the MLLP listener throttles it. + await self._emit_event( + "reply_replaced", peer_host=peer_host, reason=note + ) await self._drain_reply(writer) if failed: break diff --git a/messagefoundry/transports/x12.py b/messagefoundry/transports/x12.py index 3ed3335186..cf292334eb 100644 --- a/messagefoundry/transports/x12.py +++ b/messagefoundry/transports/x12.py @@ -67,7 +67,11 @@ register_source, wait_for_intake, ) -from messagefoundry.transports.framing import declared_encoding, encode_reply +from messagefoundry.transports.framing import ( + ReplyReplacements, + declared_encoding, + encode_reply_reporting, +) from messagefoundry.transports.mllp import ( DEFAULT_MAX_CONNECTIONS, DEFAULT_MAX_CONNECTIONS_PER_HOST, @@ -707,7 +711,7 @@ class X12Source(SourceConnector): """Listen for inbound raw-TCP connections, reassemble each ``ISA…IEA`` interchange, and hand its **raw bytes** to the pipeline handler. No HL7/X12 ACK: if that *pipeline* handler (:data:`~messagefoundry.transports.base.InboundHandler`) returns a non-``None`` reply it is written - back on the same connection, encoded by :func:`~messagefoundry.transports.framing.encode_reply` + back on the same connection, encoded by :func:`~messagefoundry.transports.framing.encode_reply_reporting` (BACKLOG #5958); the engine's returns ``None`` for every non-HL7 content type, so an X12 intake is fire-and-forget in practice. A config **Handler**'s return never reaches here — see this module's docstring.""" @@ -767,6 +771,7 @@ def __init__(self, config: Source) -> None: # Names this connection in a pacing report (BACKLOG #290) and in the reply-encoding warnings # (BACKLOG #5958). self._pacing_name = config.name or "" + self._reply_replacements = ReplyReplacements() # BACKLOG #5799 # Per-connection peer-IP allowlist (Tier 4 operability): refuse a non-listed peer at accept. # Absent/empty = no restriction. Mirrors TcpSource/MLLPSource. sa = s.get("source_ip_allowlist") @@ -1037,9 +1042,9 @@ async def _on_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamW # event is sent outside the except clause, so nothing chains the # encode error, whose `object` is the whole reply. reply_fault: str | None = None - wire = b"" + wire, replaced = b"", False try: - wire = encode_reply( + wire, replaced = encode_reply_reporting( reply, self.encoding, connection=self._pacing_name ) except (LookupError, UnicodeError) as exc: @@ -1068,6 +1073,11 @@ async def _on_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamW break continue writer.write(wire) # unframed: the interchange is the frame + if replaced and (note := self._reply_replacements.note()): + # BACKLOG #5799, throttled as the MLLP listener throttles it. + await self._emit_event( + "reply_replaced", peer_host=peer_host, reason=note + ) await self._drain_reply(writer) if failed: break diff --git a/scripts/coord/box-activity.ps1 b/scripts/coord/box-activity.ps1 index cc05e3795c..be11fbb4d2 100644 --- a/scripts/coord/box-activity.ps1 +++ b/scripts/coord/box-activity.ps1 @@ -123,9 +123,11 @@ function Get-TranscriptAgeHours { # NOT Get-ClaudeConfigRoots: that one filters to roots holding a sessions/ directory, which is the # right question for the liveness fence and the wrong one here. A root can hold transcripts and no # session registry, and dropping it would turn an evaluable signal into a missing one. + # Read the profile as Get-ClaudeConfigRoots does; its comment in session-registry.ps1 says why. $roots = if ($ConfigRoot) { @($ConfigRoot | Where-Object { Test-Path -LiteralPath $_ }) } + elseif (-not $env:USERPROFILE) { @() } else { - @(Get-ChildItem -Path $env:USERPROFILE -Directory -Filter '.claude*' -Force -EA SilentlyContinue | + @(Get-ChildItem -LiteralPath $env:USERPROFILE -Directory -Filter '.claude*' -Force -EA SilentlyContinue | ForEach-Object { $_.FullName }) } foreach ($r in $roots) { diff --git a/scripts/coord/session-registry.ps1 b/scripts/coord/session-registry.ps1 index 3f7f9d7450..918044a308 100644 --- a/scripts/coord/session-registry.ps1 +++ b/scripts/coord/session-registry.ps1 @@ -190,9 +190,10 @@ function Get-RecordStartedUtc($Record) { # Every registry record, with the root it came from attached. # # -IncludeUnreadable also returns a row for every file that could NOT be parsed (Record = $null, -# Unreadable = $true). A caller about to destroy something needs those: a record that is half-written -# -- i.e. a session that launched a moment ago -- fails to parse, and DROPPING it silently turns an -# occupied worktree from SKIP into PRUNE while the receipt reports one fewer record than existed. +# Unreadable = $true; Directory = $true when the row is a directory named *.json). A caller about to +# destroy something needs those: a record that is half-written -- i.e. a session that launched a +# moment ago -- fails to parse, and DROPPING it silently turns an occupied worktree from SKIP into +# PRUNE while the receipt reports one fewer record than existed. # It is off by default so the read-only roster callers keep the shape they already handle. function Get-SessionRecords { [CmdletBinding()] @@ -206,18 +207,19 @@ function Get-SessionRecords { # SessionStart hook, where a throw replaces the chat's whole starting context. $rec = $null $err = '' - if ($f -is [System.IO.DirectoryInfo]) { $err = 'a directory, not a file, so it cannot be read as a record' } + $isDir = $f -is [System.IO.DirectoryInfo] + if ($isDir) { $err = 'a directory, not a file, so it cannot be read as a record' } else { try { $rec = Get-Content -LiteralPath $f.FullName -Raw -EA Stop | ConvertFrom-Json -EA Stop } catch { $err = $_.Exception.Message } } if (-not $rec) { if (-not $err) { $err = 'the file parsed to nothing (empty, or being written right now)' } if ($IncludeUnreadable) { - $out += [pscustomobject]@{ Record = $null; Root = $root; File = $f.FullName; Unreadable = $true; Error = $err } + $out += [pscustomobject]@{ Record = $null; Root = $root; File = $f.FullName; Unreadable = $true; Error = $err; Directory = $isDir } } continue } - $out += [pscustomobject]@{ Record = $rec; Root = $root; File = $f.FullName; Unreadable = $false; Error = '' } + $out += [pscustomobject]@{ Record = $rec; Root = $root; File = $f.FullName; Unreadable = $false; Error = ''; Directory = $false } } } return $out diff --git a/scripts/hooks/announce-session.ps1 b/scripts/hooks/announce-session.ps1 index 958d856409..fc18ecabd9 100644 --- a/scripts/hooks/announce-session.ps1 +++ b/scripts/hooks/announce-session.ps1 @@ -803,8 +803,16 @@ try { # lookup started returning its match count -- sent an operator hunting for a missing file # that was in fact present TWICE, which is the one place the cause was visible. $matched = if ($lookup) { [int]$lookup.Matched } else { 0 } - $unreadable = if ($matched -gt 1) { 0 } else { - @(Get-SessionRecords -IncludeUnreadable | Where-Object { $_.Unreadable }).Count + # A DIRECTORY ROW IS NOT A RECORD BEING WRITTEN. The registry lists a directory named + # *.json as an unreadable row, so the files and the directories are counted apart, and + # only an unparsed FILE is called "maybe mid-write". With no unparsed file this is the + # MISSING case, and the directory rows are named after it. + $badFiles = 0 + $dirRows = 0 + if ($matched -le 1) { + foreach ($u in @(Get-SessionRecords -IncludeUnreadable | Where-Object { $_.Unreadable })) { + if ($u.Directory) { $dirRows++ } else { $badFiles++ } + } } # LEAD WITH THE DISCRIMINATOR. Write-Receipt folds this through Get-Clean with an 80-char # cap, so anything past that is gone from the only durable record of the decision. The @@ -813,8 +821,12 @@ try { # a duplicated one, which is the failure this note exists to prevent. $why = if ($matched -gt 1) { "AMBIGUOUS: $matched config roots hold a record for this id; will not self-resolve" - } elseif ($unreadable -gt 0) { - "UNREADABLE: $unreadable registry record(s) unparsed, maybe still being written" + } elseif ($badFiles -gt 0 -and $dirRows -gt 0) { + "UNREADABLE: $badFiles record(s) unparsed, maybe mid-write; $dirRows directory row(s)" + } elseif ($badFiles -gt 0) { + "UNREADABLE: $badFiles registry record(s) unparsed, maybe still being written" + } elseif ($dirRows -gt 0) { + "MISSING: no record matched this id; $dirRows registry row(s) are directories" } else { "MISSING: no registry record matched this session id" } diff --git a/scripts/security/crypto_operations.py b/scripts/security/crypto_operations.py index e2f1c242fe..ac5b3a9bb6 100644 --- a/scripts/security/crypto_operations.py +++ b/scripts/security/crypto_operations.py @@ -30,6 +30,10 @@ * a SECOND call to a callee a file already lists. The inventory is kept per file and token, so a new ``hashlib.sha256`` call beside an existing one changes nothing; +* a call to ANOTHER provider in a module a file already reaches, for a class the file already lists + through it. A ``via`` token names the module and the class, not the function, so a new call from + ``pipeline/cert_expiry.py`` to ``pki.make_self_signed``, which signs, would add no token beside + the ``sign_verify:via messagefoundry.pki`` its CRL signature check holds (vault BACKLOG #3512); * an algorithm or TLS value held in a VARIABLE. A token carries the algorithm only when the call names it, in the callee or as a literal or named constant anywhere in its arguments; * a plain ``ctx.options = ...`` or ``setattr(ctx, "options", ...)``. ``options`` is too common a diff --git a/scripts/security/scan_forbidden.py b/scripts/security/scan_forbidden.py index c4226f602e..0bd8fb034a 100644 --- a/scripts/security/scan_forbidden.py +++ b/scripts/security/scan_forbidden.py @@ -498,26 +498,30 @@ r"|(?:went|goes|moves?|moved) from)" ) _PR_PLAIN_STATE_VERB = rf"(?:{_PR_STRONG_VERB}|is(?: now| still)?|was|are|reads|now|at|from)" +#: The adverbs a record sentence hedges a verdict with, one list for each place one may stand: before +#: the verb (_PR_AUX), after a modal (_PR_MODAL), between "has" and "been", and before the verdict +#: (_PR_QUALIFIER). Lists kept apart drifted, so a word one place took unbound another (BACKLOG #8175 +#: item 6): " has likely been met", " is only partial", " never stays partial". +_PR_HEDGE = r"(?:likely|probably|still|now|also|only|then|already|so|never|yet|honestly|since)" +#: "has been" with any negations and hedges between, in any order and any markup ("has since been", +#: "hasn't yet been", "has still not been", "has _never_ been"). +_PR_HAS_BEEN = rf"(?:has|have|had)(?:n['\u2019]t)?(?:{_PR_SEP}(?:not|{_PR_HEDGE}))*{_PR_SEP}been" #: The passive and negated forms ("were", "has been", "isn't", "has not been", "is no longer") bind an #: unmarked identifier only with a state verdict ending its clause (_pr_verdict_bound). _PR_STATE_VERB = ( - rf"(?:{_PR_PLAIN_STATE_VERB}|were" - # A word may stand between "has" and "been" ("has since been met", "has never been met"). - r"|(?:(?:has|have|had)(?: not|n['\u2019]t)?(?: (?:since|still|now|yet|never|already))* )?been" + rf"(?:{_PR_PLAIN_STATE_VERB}|were|(?:{_PR_HAS_BEEN}|been)" r"|(?:is|was|are|were)(?:n['\u2019]t| not| no longer))" ) -_PR_PLAIN_QUALIFIER = r"(?:(?:a|an|the|its|permanent|genuine|accepted|honest)" + _PR_SEP + r")*" +_PR_PLAIN_QUALIFIER_WORDS = r"a|an|the|its|permanent|genuine|accepted|honest" +_PR_PLAIN_QUALIFIER = rf"(?:(?:{_PR_PLAIN_QUALIFIER_WORDS}){_PR_SEP})*" _PR_QUALIFIER = ( - r"(?:(?:a|an|the|its|permanent|genuine|accepted|honest|recorded|known|interim|provisional" - r"|likely|probably|still|already|never)" + _PR_SEP + r")*" + rf"(?:(?:{_PR_PLAIN_QUALIFIER_WORDS}|recorded|known|interim|provisional|{_PR_HEDGE}){_PR_SEP})*" ) #: Words that may stand between the identifier and its verb without unbinding it: a passive auxiliary -#: (" was held at partial"), a negated one (" isn't met") and the adverbs a record sentence -#: hedges with (" likely stays"). +#: (" was held at partial"), a negated one (" isn't met") and the hedges (" likely stays"). _PR_AUX = ( - r"(?:(?:is|was|are|were|be|been|(?:has|have|had)(?: not)? been|(?:has|have|had)n['\u2019]t been" - r"|(?:is|was|are|were)n['\u2019]t|not|no longer|likely|probably|still|now|also|only|then" - r"|already|so)" + _PR_SEP + r")*" + rf"(?:(?:is|was|are|were|be|been|{_PR_HAS_BEEN}" + rf"|(?:is|was|are|were)n['\u2019]t|not|no longer|{_PR_HEDGE})" + _PR_SEP + r")*" ) #: A modal or a negation bound to a bare verdict verb: " cannot pass", " would not be met", #: " needs to pass", " will remain partial". On an identifier the text does not mark as a @@ -526,8 +530,7 @@ _PR_MODAL = ( r"(?:can(?:not)?|can['\u2019]t|could|would|will|should|may|might|must|does|do|did" r"|(?:does|did|wo|would|could|should)n['\u2019]t|needs? to|has to|is (?:un)?able to)" - rf"(?:{_PR_SEP}(?:not|now|still|yet|never|only|honestly|also|then|reach|have|be|been|stay" - r"|remain|likely|probably))*" + rf"(?:{_PR_SEP}(?:not|{_PR_HEDGE}|reach|have|be|been|stay|remain))*" ) #: Read from the end of the identifier: " stays partial", " cell to pass", " | fail". _PR_VERDICT_AFTER = re.compile( @@ -549,13 +552,16 @@ rf"{_PR_PLAIN_QUALIFIER}{_PR_FMT}{_PR_VERDICT}" ) _PR_VERDICT_STATE_RE = re.compile(rf"(?i){_PR_VERDICT_STATE}") -#: A modal chained into a record verb (" will remain partial") is as strong as the verb alone. -_PR_MODAL_STRONG = re.compile(r"(?i)(?:stay|remain)$") +#: A modal chained into a record verb (" will remain partial") is as strong as the verb alone, +#: with or without a hedge after the verb (" will remain only partial"): the verb is searched as +#: a word anywhere in the modal group, not only at its end. +_PR_MODAL_STRONG = re.compile(r"(?i)(? will fail on the strict validator" is a verb and its phrase. _PR_VERDICT_END = re.compile( rf"(?i){_PR_FMT}(?:\s*(?:$|[.,;:!?)\]|])" - r"|\s+(?:yet|today|now|either|again|until|unless|because)\b)" + # Emphasis on the word ("_yet_", "*yet*", "`yet`") does not hide it, as "\b" hid "_yet_". + rf"|\s+{_PR_FMT}(?:yet|today|now|either|again|until|unless|because){_PR_EA})" ) #: A verb that states the verdict BEFORE the identifier: "does not meet ", "satisfies ASVS ", #: and the record's idiom for a requirement that does not pass yet, "an honest pass for ". "pass" @@ -609,8 +615,9 @@ #: one deleted, inside a word or a cell as well as around one, and keeps the hits of both readings. #: The deletion reaches the text the verdict, gap and map patterns read, not the line's kind: #: _pr_units decides a row, heading, list item or empty line from the line as written, so an -#: invisible character before a row's first pipe makes it a paragraph in both readings (an open -#: evasion). A fixed table, so an import pays nothing for it. +#: invisible character before a row's first pipe makes it a paragraph in both passes. A further +#: pass of each reading deletes them before the kinds are read (_pr_scan_reading). A fixed table, +#: so an import pays nothing for it. _PR_DEFAULT_IGNORABLE = ( (0x00AD, 0x00AD), (0x034F, 0x034F), @@ -790,16 +797,16 @@ #: GitHub ``blob/8.1.8/CHANGES.rst`` link is a version and a path, never a map. #: Starts only at the first digit of a run, so a long run of digits is read once, not once per digit. _PR_TARGET_NUMBER = re.compile(r"(?\s?)+") #: The lookahead class of main's full-stop split. _PR_BASE_SPLIT_LOOKAHEAD = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZ*`[(\"'#>-") @@ -1159,6 +1166,11 @@ def _pr_is_delimiter(row: str) -> bool: return "-" in row and set(row) <= _PR_TABLE_DELIMITER_CHARS +def _pr_between(found: list[int], above: int, below: int) -> bool: + """Whether a line number in ``found``, which is sorted, lies strictly between two lines.""" + return bisect.bisect_right(found, above) < bisect.bisect_left(found, below) + + def _pr_table_starts( units: _PrUnits, blanks: list[int], quote_blanks: list[int], quoted: set[int] ) -> list[bool]: @@ -1176,9 +1188,6 @@ def _pr_table_starts( These runs bound only the GFM reading (_pr_table_columns), whose columns can only add marks; the loose reading (_pr_loose_columns), which keeps every mark main kept, does not read them.""" - def between(found: list[int], above: int, below: int) -> bool: - return bisect.bisect_right(found, above) < bisect.bisect_left(found, below) - starts = [] # Whether every row since the last unit that is not a row opens with a quote marker. block_quoted = True @@ -1191,8 +1200,8 @@ def between(found: list[int], above: int, below: int) -> bool: and ( above is None or not above[2] - or between(blanks, above[0][0][1], line) - or (block_quoted and between(quote_blanks, above[0][0][1], line)) + or _pr_between(blanks, above[0][0][1], line) + or (block_quoted and _pr_between(quote_blanks, above[0][0][1], line)) ) ) return starts @@ -1321,8 +1330,9 @@ def scan_pr_body(body: str) -> list[str]: Reasons only, never the matched text. One hit per kind per LINE: sentences of one paragraph that restate a verdict on the same line report it once, rather than storming. - Read three times, and the hits are the union (BACKLOG #5582). The baseline reads the lines as - origin/main did before BACKLOG #5582 (see ``_PR_BASE_QUOTE``). The second reads each link as its text and each inline tag as no + Read three times, and the hits are the union (BACKLOG #5582). The baseline strips quote markers, + reads links and splits sentences as origin/main did before BACKLOG #5582 (see + ``_PR_BASE_QUOTE``). The second reads each link as its text and each inline tag as no edge, and the third keeps each link's target beside it, so a code path only a target names is seen; from the third only a map counts. Each reading builds its own units from one line model (:func:`_pr_lines`), so every reading keeps each line where it was and the hits merge by (line, @@ -1353,6 +1363,22 @@ def scan_pr_body(body: str) -> list[str]: return [f"pr-body:{line}: {PR_BODY_REASONS[kinds[kind]]}" for line, kind in sorted(found)] +def _pr_scan_units( + units: _PrUnits, + gfm: tuple[list[int], list[int], set[int]], + sentences: Callable[[str, bool], list[tuple[int, str]]], + kinds: frozenset[str], + found: set[tuple[int, int]], +) -> tuple[list[bool], list[set[int]], list[set[int]]]: + """Scan every unit with its own runs of rows and columns; return the runs and both columns.""" + starts = _pr_table_starts(units, *gfm) + asvs = _pr_table_columns(units, starts) + loose = _pr_loose_columns(units) + for unit, unit_asvs, unit_loose in zip(units, asvs, loose, strict=True): + _pr_scan_unit(unit, unit_asvs, unit_loose, found, sentences, kinds) + return starts, asvs, loose + + def _pr_scan_reading( lines: list[str], gfm: tuple[list[int], list[int], set[int]], @@ -1366,11 +1392,7 @@ def _pr_scan_reading( sentences = _pr_base_sentences if reading == _PR_BASE else _pr_sentences # Both passes of a reading share the units' kinds and lines, so they share where each run of rows # starts. - starts = _pr_table_starts(units, *gfm) - asvs = _pr_table_columns(units, starts) - loose = _pr_loose_columns(units) - for unit, unit_asvs, unit_loose in zip(units, asvs, loose, strict=True): - _pr_scan_unit(unit, unit_asvs, unit_loose, found, sentences, kinds) + starts, asvs, loose = _pr_scan_units(units, gfm, sentences, kinds, found) # Where the body holds an invisible character, it is read again with each one deleted. A unit # whose text and columns that leaves unchanged reads the same, so only the others are scanned. if invisible: @@ -1386,6 +1408,13 @@ def _pr_scan_reading( ): if unit[1] != plain[1] or unit_asvs != plain_asvs or unit_loose != plain_loose: _pr_scan_unit(unit, unit_asvs, unit_loose, found, sentences, kinds) + # The passes above read each line's kind as written, so an invisible character before a + # row's first pipe makes it a paragraph there. A further pass deletes every one before the + # kinds are read, so such a line is read as a row, with its own runs of rows. It only adds + # hits; where it builds the units the second pass built, it would add none. + regrouped = _pr_units([_PR_INVISIBLE.sub("", line) for line in lines], False, reading) + if regrouped != deleted: + _pr_scan_units(regrouped, gfm, sentences, kinds, found) def _pr_scan_unit( diff --git a/tests/_bound_proof.py b/tests/_bound_proof.py index e422ab3f6f..d93668cc0e 100644 --- a/tests/_bound_proof.py +++ b/tests/_bound_proof.py @@ -16,8 +16,10 @@ password, a second refusal) is returned as the engine sent it. ``tests/test_bound_step_up_injection.py`` pins the gate itself. -THE REFUSED FIRST TRY IS A REAL REQUEST. It passed the permission check, so it wrote its grant -audit row and, for a write, charged the admin-write gap. A test that counts those rows or budgets, +THE REFUSED FIRST TRY IS A REAL REQUEST. It passed the permission check, so where the trail +records the request it wrote audit rows: an ``auth.gate_refused`` row where the gate refused it, +or, on a ``proof_in_route`` route whose body refused the spend, a grant row and then an ``auth.gate_refused`` row (BACKLOG #1197). For a write it also +charged the admin-write gap. A test that counts those rows or budgets, reads the re-keyed session afterwards, or runs under a deadline a password hash outlasts should prove up front with :func:`prove` instead, and a suite whose retry would be paced turns ``admin_write_min_interval_seconds`` off. diff --git a/tests/test_adr_0019_0173_revert_guard.py b/tests/test_adr_0019_0173_revert_guard.py new file mode 100644 index 0000000000..2d76b7e6e2 --- /dev/null +++ b/tests/test_adr_0019_0173_revert_guard.py @@ -0,0 +1,123 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""A revert guard: ADR 0019 and ADR 0173 do not take back the restatements removed from them. + +ADR 0019's RNG amendment point 4 and its first 2026-10-10 note restated ADR 0138's Transit start +gate (vault BACKLOG #1173, item 3). ADR 0173's ODBC test amendment opened with its run dates in two +zones and repeated its versions in its limits (vault BACKLOG #3009, PR 2899 notes 3 and 4). + +This refuses the removed phrasings only. It does not prove a fact is stated once anywhere else. +Each refused phrase is checked against the removed wording, so a phrase that drifts from that +wording fails here instead of passing for ever. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +_ADR = Path(__file__).resolve().parent.parent / "docs" / "adr" +_ADR_0019 = _ADR / "0019-pluggable-keyprovider-hsm-kms-vault.md" +_ADR_0173 = ( + _ADR + / "0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md" +) + +# The removed wording, as it read on origin/main before the fix: the negative controls. +_OLD_0019_POINT_4 = ( + "In its place, `Engine.start` calls `enforce_transit_bound_attestation` in " + "`store/transit_attestation.py`, which checks for a recorded operator attestation naming the " + "configured Transit data key (BACKLOG #2337). Without one, the engine refuses to start under " + "`[security].enforcement = enforce` and only logs a warning under `warn`." +) +_OLD_0019_NOTE = ( + "Since BACKLOG #2337, an operator attests to the precondition with " + "`messagefoundry store attest-transit-bound`, and `Engine.start` reads that record" +) +_OLD_0173_FINDINGS = ( + "Two runs with results, dated 2026-10-16 and 2026-10-17 in Central time. In UTC, the first " + "run's legs ran from 02:22 to 02:25" +) +_OLD_0173_LIMIT = "Only that driver build, only Windows Server 2022, and only SQL Server 2022 RTM." + +_REFUSED_0019 = ("in its place,", "refuses to start", "logs a warning", "naming the configured") +_REFUSED_0019_NOTE = ("attest-transit-bound", "reads that record") +_REFUSED_0173_FINDINGS = ("in utc, the first run", "2026-10-17 in central time") +_REFUSED_0173_LIMIT = ("only windows server 2022", "only sql server 2022 rtm") + +# A 2026-11-21 correction note quotes the removed words on purpose; strip only the note itself. +_NOTE = re.compile(r"\*\(Corrected 2026-11-21,.*?\)\*", re.DOTALL) + + +def _flat(text: str) -> str: + """Join wrapped lines, drop blockquote markers and fold case, so a wrapped phrase matches.""" + return " ".join(w for w in _NOTE.sub("", text).split() if w != ">").lower() + + +def _between(text: str, start: str, end: str) -> str: + head = text.index(start) + return text[head : text.index(end, head)] + + +@pytest.mark.parametrize( + ("old", "refused"), + [ + (_OLD_0019_POINT_4, _REFUSED_0019), + (_OLD_0019_NOTE, _REFUSED_0019_NOTE), + (_OLD_0173_FINDINGS, _REFUSED_0173_FINDINGS), + (_OLD_0173_LIMIT, _REFUSED_0173_LIMIT), + ], +) +def test_each_refused_phrase_matches_the_removed_wording( + old: str, refused: tuple[str, ...] +) -> None: + for phrase in refused: + assert phrase in _flat(old), phrase + + +def test_adr_0019_does_not_revert_the_transit_gate_wording() -> None: + text = _ADR_0019.read_text(encoding="utf-8") + point_4 = _flat( + _between( + text, + "4. **Volume wears out a key, not the generator.**", + "**What this statement does not cover.**", + ) + ) + note = _flat( + _between( + text, + "> **Corrected 2026-10-10 (BACKLOG #1173).** The rotation precondition above", + "**Status: 11.3.4", + ) + ) + for phrase in _REFUSED_0019: + assert phrase not in point_4, phrase + for phrase in _REFUSED_0019_NOTE: + assert phrase not in note, phrase + # Positive controls: the pointer, the link and the caveat stay. + assert "enforce_transit_bound_attestation" in point_4 + assert "0138-transit-bulk-crypto-provider" in point_4 + assert "weaker than the counted bound" in point_4 + assert "enforce_transit_bound_attestation" in note + + +def test_adr_0173_odbc_amendment_does_not_revert_its_opening_or_version_limit() -> None: + text = _ADR_0173.read_text(encoding="utf-8") + amendment = _between( + text, + "**Amendment 2026-11-11 -- what the ODBC Driver 18 test measured", + "*(End of the amendment of 2026-11-11.", + ) + head, _, limits = amendment.partition("- **The limits.**") + findings, limits = _flat(head), _flat(limits) + for phrase in _REFUSED_0173_FINDINGS: + assert phrase not in findings, phrase + for phrase in _REFUSED_0173_LIMIT: + assert phrase not in limits, phrase + # Positive controls: the UTC times, the versions and the version limit are each still stated. + assert "02:22 to 02:25 utc" in findings + assert "windows server 2022 datacenter" in findings + assert "only the driver, windows and sql server versions above" in limits diff --git a/tests/test_announce_hook.py b/tests/test_announce_hook.py index 09c13f16c4..2caa3d8968 100644 --- a/tests/test_announce_hook.py +++ b/tests/test_announce_hook.py @@ -1143,6 +1143,36 @@ def test_a_duplicated_session_id_is_reported_as_ambiguous_not_missing( assert "MISSING" not in note, f"reported missing when it was duplicated: {note}" +@pytest.mark.parametrize( + ("directory", "bad_file", "want"), + [ + (True, False, "MISSING: no record matched this id; 1 registry row(s) are directories"), + (True, True, "UNREADABLE: 1 record(s) unparsed, maybe mid-write; 1 directory row(s)"), + (False, True, "UNREADABLE: 1 registry record(s) unparsed, maybe still being written"), + ], + ids=["directory-only", "directory-and-file", "file-only"], +) +def test_a_directory_row_is_not_called_a_record_being_written( + repo: Path, tmp_path: Path, directory: bool, bad_file: bool, want: str +) -> None: + """Vault BACKLOG #2985, added item 3. The registry lists a directory named *.json as an + unreadable row, and the NO_LOGIN receipt called it "maybe still being written". A directory is + not a record being written, so it is counted apart from the files, and with no unparsed file + the receipt reads MISSING. Red before the fix: the directory cases read as a record being + written. The file-only case is the control.""" + home = _registry(tmp_path / "home", "00000000-0000-0000-0000-000000000000", ".claude") + sessions = home / ".claude" / "sessions" + if directory: + (sessions / "dir.json").mkdir() + if bad_file: + (sessions / "bad.json").write_text("{ not json", encoding="utf-8") + sd = tmp_path / "sd" + run(repo, tmp_path=tmp_path, state_dir=sd, rows=[PEER, ACCT], env={"USERPROFILE": str(home)}) + assert outcomes(sd) == ["NO_LOGIN"], outcomes(sd) + note = " ".join(receipts(sd)) + assert want in note, note + + def test_repeated_stand_downs_do_not_arm_the_kill_ladder(repo: Path, tmp_path: Path) -> None: """A STAND-DOWN MUST BE RECOVERABLE, and one invocation cannot show that. diff --git a/tests/test_apiclient_sign_in_timeout.py b/tests/test_apiclient_sign_in_timeout.py index c9c66d9d6c..9a03f1f5f7 100644 --- a/tests/test_apiclient_sign_in_timeout.py +++ b/tests/test_apiclient_sign_in_timeout.py @@ -20,6 +20,7 @@ import ast import inspect +from collections.abc import Callable from pathlib import Path import httpx @@ -171,26 +172,44 @@ def test_a_client_timeout_up_to_the_floor_gets_the_floor_on_the_queued_reads(own assert seen["/auth/me"] == _every_phase(own) -def _methods_calling(name: str) -> set[str]: - """The ``EngineClient`` methods whose body calls ``self.()``, read from its source.""" +def _methods_with_a_call(matches: Callable[[ast.Call], bool]) -> set[str]: + """The ``EngineClient`` methods, ``async def`` ones included, whose body holds a call that + ``matches``, read from its source.""" tree = ast.parse(Path(inspect.getfile(EngineClient)).read_text(encoding="utf-8")) cls = next( n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == EngineClient.__name__ ) - found: set[str] = set() - for fn in cls.body: - if not isinstance(fn, ast.FunctionDef): - continue - for node in ast.walk(fn): - if ( - isinstance(node, ast.Call) - and isinstance(node.func, ast.Attribute) - and node.func.attr == name - and isinstance(node.func.value, ast.Name) - and node.func.value.id == "self" - ): - found.add(fn.name) - return found + return { + fn.name + for fn in cls.body + if isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)) + and any(isinstance(node, ast.Call) and matches(node) for node in ast.walk(fn)) + } + + +def _methods_calling(name: str) -> set[str]: + """The ``EngineClient`` methods whose body calls ``self.()``.""" + return _methods_with_a_call( + lambda call: ( + isinstance(call.func, ast.Attribute) + and call.func.attr == name + and isinstance(call.func.value, ast.Name) + and call.func.value.id == "self" + ) + ) + + +def _methods_setting_a_read_timeout() -> set[str]: + """The ``EngineClient`` methods that build an ``httpx.Timeout`` with its own ``read=``.""" + return _methods_with_a_call( + lambda call: ( + ( + (isinstance(call.func, ast.Attribute) and call.func.attr == "Timeout") + or (isinstance(call.func, ast.Name) and call.func.id == "Timeout") + ) + and any(kw.arg == "read" for kw in call.keywords) + ) + ) def test_the_census_of_queued_calls_matches_the_client() -> None: @@ -208,6 +227,16 @@ def test_the_census_of_queued_calls_matches_the_client() -> None: assert _methods_calling("_adopt_rotated") == {"reauth", "verify_mfa", "confirm_mfa"} +def test_no_method_builds_its_own_read_keyword_timeout() -> None: + """RED when: an ``EngineClient`` method builds its own ``httpx.Timeout(..., read=...)`` rather + than calling ``_sign_in_timeout``, so a longer reply wait escapes the census above. Control: + the scan finds the one method that does build one, ``_sign_in_timeout`` itself. It reads only + a ``read=`` keyword in a call inside a method body, so at least these escape it: a positional + ``httpx.Timeout(n)``, a scalar ``timeout=``, a module-level ``httpx.Timeout`` constant or helper + passed in, and ``httpx.Timeout(**kw)``.""" + assert _methods_setting_a_read_timeout() == {"_sign_in_timeout"} + + def test_confirm_mfa_sends_the_enrolment_code_only_when_given() -> None: """ADR 0207: a directory account's first factor needs the Administrator's code on an unstamped session, so the shared client must be able to carry it. RED when it cannot.""" diff --git a/tests/test_checks_settings_memo.py b/tests/test_checks_settings_memo.py index aedbd30662..a7c6406c05 100644 --- a/tests/test_checks_settings_memo.py +++ b/tests/test_checks_settings_memo.py @@ -8,6 +8,7 @@ from __future__ import annotations +import os from collections import Counter from pathlib import Path from typing import Any @@ -20,6 +21,19 @@ SAMPLES_CONFIG = Path(__file__).resolve().parents[1] / "samples" / "config" +@pytest.fixture(autouse=True) +def _hermetic(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Each test runs in an empty working directory with no ``MEFOR_*`` variables, so neither a + ``./messagefoundry.toml`` where pytest was started nor a variable the shell exports reaches + what the legs grade.""" + work = tmp_path / "cwd" + work.mkdir() + monkeypatch.chdir(work) + for name in list(os.environ): + if name.upper().startswith("MEFOR_"): + monkeypatch.delenv(name) + + def _count_reads(monkeypatch: pytest.MonkeyPatch) -> Counter[str]: calls: Counter[str] = Counter() real_load = checks._load_check_settings_uncached diff --git a/tests/test_coord_box_activity.py b/tests/test_coord_box_activity.py index e31301beba..b51719ab90 100644 --- a/tests/test_coord_box_activity.py +++ b/tests/test_coord_box_activity.py @@ -442,3 +442,49 @@ def test_dot_sourcing_does_not_change_the_callers_strict_mode(self, sandbox: Pat ) assert proc.returncode == 0, proc.stderr assert "lenient" in proc.stdout + + +class TestTheProfileIsReadByItsOwnName: + """Vault BACKLOG #2985, added item 2. With no -ConfigRoot, Get-TranscriptAgeHours listed + USERPROFILE with -Path, which reads its argument as a wildcard pattern: a profile named home[1] + matched only a folder named home1, so the transcript was never found and the signal read as + UNEVALUABLE. Red before the fix: the bracketed case returned null.""" + + def _age(self, sandbox: Path, home: Path | None) -> str: + env = {k: v for k, v in os.environ.items() if k.upper() != "USERPROFILE"} + if home is not None: + env["USERPROFILE"] = str(home) + ps = ( + f". '{sandbox / 'scripts' / 'coord' / 'box-activity.ps1'}'; " + "$a = Get-TranscriptAgeHours -WorktreePath 'D:\\proj\\App'; " + "if ($null -eq $a) { 'null' } else { [string]$a }" + ) + proc = subprocess.run( + ["pwsh", "-NoProfile", "-NonInteractive", "-Command", ps], + capture_output=True, + text=True, + timeout=TIMEOUT, + check=False, + env=env, + cwd=str(sandbox), + ) + assert proc.returncode == 0 and not proc.stderr.strip(), proc.stderr + return proc.stdout.strip() + + @pytest.mark.parametrize("home_name", ["home", "home[1]"]) + def test_a_transcript_under_the_profile_is_found(self, sandbox: Path, home_name: str) -> None: + d = sandbox / home_name / ".claude" / "projects" / "D--proj-App" + d.mkdir(parents=True) + f = d / "turn.jsonl" + f.write_text('{"t":1}\n', encoding="utf-8") + _back_date(f, 5) + age = self._age(sandbox, sandbox / home_name) + assert age != "null", f"no transcript found under the profile {home_name}" + assert float(age) == pytest.approx(5, abs=0.1) + + def test_an_unset_profile_names_no_root(self, sandbox: Path) -> None: + """No profile reads as UNEVALUABLE, not as a throw, and not as the current directory.""" + d = sandbox / ".claude" / "projects" / "D--proj-App" + d.mkdir(parents=True) + (d / "turn.jsonl").write_text('{"t":1}\n', encoding="utf-8") + assert self._age(sandbox, None) == "null" diff --git a/tests/test_derived_gate_decision_audit.py b/tests/test_derived_gate_decision_audit.py index ceb5dc87f5..e99abd1580 100644 --- a/tests/test_derived_gate_decision_audit.py +++ b/tests/test_derived_gate_decision_audit.py @@ -29,21 +29,26 @@ from messagefoundry.api.security import ( _GateRefusal, _mfa_refusal, + _record_route_refusal, _recorded_decision, + refuse_unless_step_up_window_live, require_paced, require_phi_read, require_reauth_only, require_reauth_only_action, require_step_up, require_step_up_action, + spend_step_up_action, ) from messagefoundry.auth import Permission, Role from messagefoundry.auth.identity import ALL_CHANNELS, Identity from messagefoundry.auth.service import ( STEP_UP_ACTION_ADMIN_USER_UPDATE, + STEP_UP_ACTION_CONFIG_RELOAD, STEP_UP_ACTION_SESSION_TERMINATE, AuthService, ) +from messagefoundry.auth.tokens import hash_token from messagefoundry.config.settings import AuthSettings, EgressSettings from messagefoundry.pipeline import Engine from tests._admin_account import create_local_user_chosen @@ -67,21 +72,20 @@ async def engine(tmp_path: Path) -> AsyncIterator[Engine]: await eng.stop() -async def _service(engine: Engine) -> AuthService: +async def _service(engine: Engine, **overrides: Any) -> AuthService: """One administrator; one paced write and one PHI read per window; the new-address check on. ``require_mfa`` is off so the base gate's factor refusal does not answer first, and the minimum - write interval is off so the second write is refused by the count alone.""" - service = AuthService( - engine.store, - AuthSettings( - require_mfa=False, - admin_new_ip_step_up=True, - admin_write_min_interval_seconds=0, - admin_write_rate_limit_per_actor=1, - phi_read_rate_limit_per_actor=1, - ), - ) + write interval is off so the second write is refused by the count alone. ``overrides`` replace + any of those settings.""" + settings: dict[str, Any] = { + "require_mfa": False, + "admin_new_ip_step_up": True, + "admin_write_min_interval_seconds": 0, + "admin_write_rate_limit_per_actor": 1, + "phi_read_rate_limit_per_actor": 1, + } + service = AuthService(engine.store, AuthSettings(**(settings | overrides))) await service.initialize() user_id = await create_local_user_chosen( service, @@ -419,3 +423,137 @@ def test_a_gate_refusal_survives_copy_and_pickle_with_its_reason() -> None: "throttled", {"Retry-After": "3"}, ) + + +# --- A step-up refusal a route body makes after its gate admitted the request (BACKLOG #1197) --- +# +# A ``proof_in_route`` gate writes its grant row, then the route body spends the proof +# (``spend_step_up_action``) or, when only the session window is owed, checks it +# (``refuse_unless_step_up_window_live``). Each refusal there used to leave the grant row alone. + +_ROUTE_ACTION = STEP_UP_ACTION_CONFIG_RELOAD + + +def _route_body_app( + engine: Engine, service: AuthService, check: Callable[[Request], Any], ran: list[str] +) -> FastAPI: + """A POST probe gated as purge and reload are, whose body runs ``check`` and then records that + it got past it.""" + app = create_app(engine, auth=service) + gate = Depends( + require_step_up_action(_ROUTE_ACTION, Permission.USERS_MANAGE, proof_in_route=True) + ) + + async def probe(request: Request, _: Identity = gate) -> dict[str, str]: + await check(request) + ran.append("past the check") + return {"ok": "1"} + + app.add_api_route(_PROBE, probe, methods=["POST"]) + return app + + +async def _spend(request: Request) -> None: + await spend_step_up_action(request, _ROUTE_ACTION) + + +async def _reauth(app: FastAPI, token: str, purpose: str | None) -> str: + body = {"password": PW} if purpose is None else {"password": PW, "purpose": purpose} + async with _client(app, _HOME) as c: + r = await c.post("/me/reauth", json=body, headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == 200, r.text + return str(r.json()["token"]) + + +_GRANT_ROW = (_GRANTED, {"permission": Permission.USERS_MANAGE.value, "path": _PROBE}, _HOME) +_REFUSAL_ROW = ( + _REFUSED, + {"permission": Permission.USERS_MANAGE.value, "path": _PROBE, "reason": "step_up"}, + _HOME, +) + + +async def test_a_refused_spend_in_the_route_body_leaves_a_refusal_row(engine: Engine) -> None: + """RED when: ``spend_step_up_action`` refuses without recording it, so the request leaves only + its gate's grant row. The control is the same request with the bound proof minted: the spend + passes and adds no refusal row.""" + service = await _service(engine, admin_write_rate_limit_per_actor=10) + ran: list[str] = [] + app = _route_body_app(engine, service, _spend, ran) + token = await _login(app) + + refused = await _call(app, "POST", token, _HOME) + assert refused.status_code == 403, refused.text + assert refused.headers.get("X-Step-Up-Action") == _ROUTE_ACTION + assert ran == [] + assert await _decisions(engine) == [_GRANT_ROW, _REFUSAL_ROW] + + token = await _reauth(app, token, _ROUTE_ACTION) + admitted = await _call(app, "POST", token, _HOME) + assert admitted.status_code == 200, admitted.text + assert ran == ["past the check"] + assert await _decisions(engine) == [_GRANT_ROW, _REFUSAL_ROW, _GRANT_ROW] + + +async def test_a_lapsed_window_refused_in_the_route_body_leaves_a_refusal_row( + engine: Engine, +) -> None: + """RED when: ``refuse_unless_step_up_window_live`` refuses without recording it. The control is + the same request once a plain re-proof has made the window live again.""" + service = await _service(engine, admin_write_rate_limit_per_actor=10) + ran: list[str] = [] + app = _route_body_app(engine, service, refuse_unless_step_up_window_live, ran) + token = await _login(app) + await engine.store.mark_session_reauthed(hash_token(token), now=0.0) # lapse the window + + refused = await _call(app, "POST", token, _HOME) + assert refused.status_code == 403, refused.text + assert "X-Step-Up-Action" not in refused.headers + assert ran == [] + assert await _decisions(engine) == [_GRANT_ROW, _REFUSAL_ROW] + + token = await _reauth(app, token, None) + admitted = await _call(app, "POST", token, _HOME) + assert admitted.status_code == 200, admitted.text + assert ran == ["past the check"] + assert await _decisions(engine) == [_GRANT_ROW, _REFUSAL_ROW, _GRANT_ROW] + + +@pytest.mark.parametrize("check", [_spend, refuse_unless_step_up_window_live]) +async def test_a_failed_refusal_row_write_still_refuses( + engine: Engine, check: Callable[[Request], Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """The refusal never fails open: when the refusal row cannot be written, the request is still + refused and the route body never gets past the check, as in the gate's own decision block.""" + service = await _service(engine, admin_write_rate_limit_per_actor=10) + + attempts: list[str] = [] + + async def broken(*_: object, **__: object) -> None: + attempts.append("audit_gate_refused") + raise RuntimeError("audit store down") + + monkeypatch.setattr(service, "audit_gate_refused", broken) + ran: list[str] = [] + app = _route_body_app(engine, service, check, ran) + token = await _login(app) + # Lapse the window for the window check; the spend refuses anyway, with no bound proof minted. + await engine.store.mark_session_reauthed(hash_token(token), now=0.0) + transport = httpx.ASGITransport(app=app, client=(_HOME, 12345), raise_app_exceptions=False) + async with httpx.AsyncClient(transport=transport, base_url="http://t") as c: + r = await c.post(_PROBE, headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == 500, r.text + assert attempts == ["audit_gate_refused"], "the 500 must come from the refusal-row write" + assert await _decisions(engine) == [_GRANT_ROW], "the gate admitted it; the route body refused" + assert ran == [] + + +async def test_a_route_body_refusal_with_no_admitting_gate_logs_its_missing_row( + caplog: pytest.LogCaptureFixture, +) -> None: + """A route that refuses with no ``proof_in_route`` gate in front has no permission to name, so + it writes no row, and says so in the log rather than dropping the row silently.""" + request = _post_request() + with caplog.at_level("WARNING", logger="messagefoundry.api.security"): + await _record_route_refusal(request, _GateRefusal(403, "refused", reason="step_up")) + assert "no admitting proof_in_route gate" in caplog.text diff --git a/tests/test_mllp_handler_failure.py b/tests/test_mllp_handler_failure.py index a72886da5e..bd1b6ec14b 100644 --- a/tests/test_mllp_handler_failure.py +++ b/tests/test_mllp_handler_failure.py @@ -26,6 +26,7 @@ import contextlib import logging import sys +import time from collections.abc import Callable from pathlib import Path from typing import Any, NoReturn @@ -33,6 +34,7 @@ import pytest import messagefoundry.transports.base as base_mod +import messagefoundry.transports.framing as framing_mod from messagefoundry.config.models import AckMode, ConnectorType, ContentType, Source from messagefoundry.config.settings import EgressSettings from messagefoundry.config.wiring import ConnectionSpec, InboundConnection, Registry @@ -646,6 +648,93 @@ async def narrow(raw: bytes) -> str: assert "framing_error" not in cap.kinds(), cap.kinds() +async def test_a_burst_of_altered_replies_writes_one_throttled_reply_replaced_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # BACKLOG #5799 item 1: the replacement's WARNING is logged once per connection per process, so + # without an event the second altered ACK left no record at all. The event is throttled per + # listener, so a burst inside one window writes one event, not one per message, which could + # fill the runner's bounded event queue and crowd other kinds out. Red on the code before: no + # `reply_replaced`; red with an unthrottled event: twenty of them. + monkeypatch.setattr(framing_mod, "_reply_replacement_logged", set()) + cap = _Capture() + source = _mllp(encoding="ascii") + source.on_connection_event = cap + texts = iter(["café", "plain"] + ["naïve"] * 19) + + async def narrow(raw: bytes) -> str: + return build_ack(raw, code="AA", text=next(texts)) + + await source.start(narrow) + try: + reader, writer = await asyncio.open_connection("127.0.0.1", source.sockport) + for _ in range(21): + writer.write(frame(_ADT)) + await writer.drain() + await _read_reply(reader) + writer.close() + await writer.wait_closed() + finally: + await asyncio.wait_for(source.stop(), timeout=5.0) + replaced = [e for e in cap.events if e[0] == "reply_replaced"] + assert len(replaced) == 1, cap.events + assert replaced[0][1] is not None and replaced[0][2] is not None + assert replaced[0][2].startswith("1 reply(ies) since the last report") + assert "naïve" not in replaced[0][2] and "ascii" not in replaced[0][2] + + +def test_the_reply_replaced_throttle_reports_the_count_once_the_window_passes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # BACKLOG #5799 item 1: the first at once, then at most one per window, carrying the count of + # replaced replies since the last report. + clock = [1000.0] + monkeypatch.setattr(time, "monotonic", lambda: clock[0]) + throttle = framing_mod.ReplyReplacements() + first = throttle.note() + assert first is not None and first.startswith("1 reply(ies)") + assert [throttle.note() for _ in range(500)] == [None] * 500 + clock[0] += framing_mod.REPLY_REPLACED_EVENT_SECONDS + later = throttle.note() + assert later is not None and later.startswith("501 reply(ies)") + assert throttle.note() is None + + +async def test_a_handler_fault_nak_the_charset_altered_writes_a_reply_replaced_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # BACKLOG #5799 item 1: the handler-fault NAK echoes the control id, and a byte the ascii + # inbound cannot decode reaches it as a character ascii cannot encode, so the NAK is altered + # too. It writes `reply_replaced` after `handler_error`. Red on the code before: no such event. + monkeypatch.setattr(framing_mod, "_reply_replacement_logged", set()) + cap = _Capture() + source = _mllp(encoding="ascii") + source.on_connection_event = cap + await source.start(_boom) + try: + reader, writer = await asyncio.open_connection("127.0.0.1", source.sockport) + writer.write(frame(_ADT.replace("MSG1", "MSG\xe91").encode("latin-1"))) + await writer.drain() + assert b"MSA|AE|MSG?1|" in await _read_reply(reader) + writer.close() + await writer.wait_closed() + finally: + await asyncio.wait_for(source.stop(), timeout=5.0) + assert cap.kinds()[:3] == ["established", "handler_error", "reply_replaced"], cap.kinds() + + +def test_the_handler_fault_nak_flags_a_replacement_only_when_one_was_made( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The warn-once set is module state, so this test's addition is discarded after it. + monkeypatch.setattr(framing_mod, "_reply_replacement_logged", set()) + source = _mllp(encoding="ascii") + clean = source._handler_failure_nak(b"MSH|^~\\&|S|F|R|F|20260101||ADT^A01|C1|P|2.5\r") + altered = source._handler_failure_nak(b"MSH|^~\\&|S|F|R|F|20260101||ADT^A01|C\xe91|P|2.5\r") + assert clean is not None and clean[1] is False + assert altered is not None and altered[1] is True + + async def _raise_locked(*args: Any, **kwargs: Any) -> NoReturn: raise RuntimeError("database is locked") diff --git a/tests/test_one_frame_one_message.py b/tests/test_one_frame_one_message.py index e747728952..d9f9d6235e 100644 --- a/tests/test_one_frame_one_message.py +++ b/tests/test_one_frame_one_message.py @@ -680,6 +680,27 @@ def test_frame_reply_replaces_what_a_narrow_charset_cannot_hold( assert "utf-8" not in warnings[0] +def test_the_reporting_variants_flag_a_replaced_reply_every_time() -> None: + """BACKLOG #5799 item 1: the warning is once per connection, but the flag a listener writes its + ``reply_replaced`` event from is set on every reply replaced, and on no other. A clean reply and + the utf-8 fallback for an unusable charset name are not replacements.""" + reply = MSH + CR + "MSA|AA|CTRL1|\u00e9" + CR + for _ in range(2): + wire, replaced = framing_mod.frame_reply_reporting( + MLLP_CODEC, reply, "ascii", connection="IB_FLAG" + ) + assert replaced and wire == frame_reply(MLLP_CODEC, reply, "ascii", connection="IB_FLAG") + assert framing_mod.encode_reply_reporting(reply, "ascii", connection="IB_FLAG")[1] + assert not framing_mod.frame_reply_reporting(MLLP_CODEC, CLEAN, "ascii")[1] + assert not framing_mod.encode_reply_reporting(reply, "utf-8")[1] + assert not framing_mod.encode_reply_reporting(reply, "not-a-real-codec")[1] + # A frame byte turned into a space is not a charset replacement, and sets no flag. + framed, replaced = framing_mod.frame_reply_reporting( + MLLP_CODEC, MSH + CR + "MSA|AA|C" + SB + "1" + CR, "ascii" + ) + assert not replaced and framed.count(b"\x0b") == 1 + + @pytest.mark.parametrize( "msh2", ["?~" + BS + "&", "^?" + BS + "&", "^~?&", "^~" + BS + "?"], @@ -842,8 +863,10 @@ async def handler(raw: bytes) -> str: def test_the_mllp_handler_fault_nak_is_one_frame_when_the_header_holds_a_start_byte() -> None: source = MLLPSource(Source(type=ConnectorType.MLLP, settings={"host": "127.0.0.1", "port": 0})) header = f"MSH|{ENC}|S|F|R|F|20260101||ADT^A01|C{SB}1|P|2.5{CR}" - nak = source._handler_failure_nak(header.encode("utf-8")) - assert nak is not None and nak.count(b"\x0b") == 1 and nak.count(b"\x1c") == 1 + framed = source._handler_failure_nak(header.encode("utf-8")) + assert framed is not None + nak = framed[0] + assert nak.count(b"\x0b") == 1 and nak.count(b"\x1c") == 1 async def test_the_tcp_listener_sends_one_frame_when_its_reply_holds_its_start_byte() -> None: diff --git a/tests/test_release_pipeline.py b/tests/test_release_pipeline.py index b25e22d6c5..68fa6f6939 100644 --- a/tests/test_release_pipeline.py +++ b/tests/test_release_pipeline.py @@ -1204,6 +1204,25 @@ def _posix_tool_env() -> dict[str, str]: return env +#: The timeout for a short subprocess here: a bash run of an extracted step, or a one-line probe. +#: It does not measure speed: nothing in this file reads a duration. On Windows it does not bound +#: a grandchild that still holds the pipes. +#: +#: WHY IT STAYS AT 60 S (BACKLOG #3633 item 2). That row records one overrun: on engine PR 2327's +#: run 38674972250, `over-long-body[console]` took 84.5 s in notes.sh on windows-2025, and that +#: PR's CI triage comment reports the same tree passing on windows-2022 in the same run. On a +#: Windows 11 dev box the test took about 1.6 s (measured 2026-11-21). Nothing here was measured on +#: a windows-2025 runner. Raising this alone would not help. The CI test legs run pytest with a +#: per-test `--timeout`, its matrix `pytest_timeout` in ci.yml: 60 s on ubuntu, 120 s on Windows. +#: That cap covers the whole test, its setup and every call in it, and with +#: `--timeout-method=thread` pytest-timeout ends the whole worker process when it fires, rather +#: than failing the one test with this call's output. So on ubuntu the cap fires before this +#: timeout can, and on Windows a test that makes two such calls, as `over-long-body` does, can +#: reach the cap first even at this value. Allowing a longer stall needs the per-test cap raised, for +#: these tests or for the leg; this value would follow it. +_HANG_TIMEOUT_S = 60 + + def _run_leak_gate(bash: str, workdir: Path, script: Path, env: dict[str, str]) -> tuple[int, str]: """Run the extracted step from ``workdir`` the way the runner would; return (rc, combined output). @@ -1221,7 +1240,7 @@ def _run_leak_gate(bash: str, workdir: Path, script: Path, env: dict[str, str]) cwd=str(workdir), env=env, capture_output=True, - timeout=60, + timeout=_HANG_TIMEOUT_S, ) return proc.returncode, (proc.stdout + proc.stderr).decode("utf-8", "replace") @@ -2089,12 +2108,68 @@ def _clone_venv(template: Path, root: Path) -> tuple[Path, Path]: return exe, Path(purelib) +#: A heredoc fed to an interpreter on stdin, as every release smoke and tag guard is fed: +#: ``python - [args] <<'TAG'``, the body, then ``TAG`` alone at column 0 of the +#: dedented ``run:`` block. ``flags`` stops at the first word that is not a dash flag, so a flag +#: that takes a value (``-X utf8``) makes the invocation unreadable here rather than misread. +_STDIN_HEREDOC = re.compile( + r"\S*python[0-9.]*(?P(?:[ \t]+-[A-Za-z]+)*)[ \t]+-(?=[ \t])[^\n]*<<'(?P[A-Z]+)'\n" + r"(?P.*?)\n(?P=tag)\n", + re.S, +) + +#: Any such heredoc, whatever its invocation, so :func:`_step_flags` can count the copies it read. +_ANY_HEREDOC = re.compile(r"<<'(?P[A-Z]+)'\n(?P.*?)\n(?P=tag)\n", re.S) + + +@functools.cache +def _step_flags(script: str) -> tuple[str, ...]: + """The interpreter flags release.yml passes the interpreter that ``script`` is fed to. + + Read from the workflow by the script's own text, so an execution test runs a smoke or a tag + guard under the flags the step really uses (BACKLOG #1583). Before this, ``_run_smoke`` + hardcoded ``-I``, so the intact checkout the acceptance keeps present could never answer: a + step that dropped ``-I`` would have left every execution test here green. If two steps ever + feed the same script, the flags of every copy must agree, or no single answer exists. + + Both sides are read through :func:`_executed_shell`, so a comment quoting an invocation is not + taken for one, and a script extracted with or without its comment lines matches either way. + Every heredoc carrying the script must have a readable invocation, so a copy whose header this + cannot parse fails here rather than dropping out of the comparison. + """ + want = _executed_shell(script) + shells = [ + _executed_shell(str(step.get("run") or "")) + "\n" + for job in _jobs().values() + for step in (job.get("steps") or []) + if isinstance(step, dict) + ] + headers = [ + tuple(m.group("flags").split()) + for shell in shells + for m in _STDIN_HEREDOC.finditer(shell) + if m.group("body") == want + ] + copies = sum(m.group("body") == want for shell in shells for m in _ANY_HEREDOC.finditer(shell)) + assert len(headers) == copies, ( + f"release.yml carries the script in {copies} heredoc(s) but {len(headers)} invocation(s) " + f"could be read; an unreadable one would run under flags nothing here checks" + ) + found = set(headers) + assert len(found) == 1, ( + f"expected the script to be fed to exactly one interpreter flag list in release.yml, found " + f"{sorted(found)}: either no step feeds it on stdin any more, or two copies are run " + f"under different flags" + ) + return next(iter(found)) + + def _run_smoke( exe: Path, script: str, workdir: Path, *, - isolated: bool = True, + flags: Sequence[str] | None = None, args: Sequence[str] = (), ) -> tuple[int, str, str]: """Run ``script`` the way the step does; return (rc, stdout, combined output). @@ -2103,15 +2178,19 @@ def _run_smoke( ``built=$(...)`` and everything else the script says goes to stderr, so a diagnostic that leaked onto stdout would silently become the version the release compares against the tag. - ``-I`` matches the workflow. The one caller that drops it is the checkout-shadow control, which - exists to prove the in-venv assertion fires rather than that the flag is spelled right. + ``flags`` defaults to the step's own, read by :func:`_step_flags`. A caller passes other flags + only as a control, to show what the same run does without the step's isolation. ``args`` follow the ``-``, as ``python -I - "$built" "$want"`` passes them to a tag guard. """ - argv = [str(exe), *(["-I"] if isolated else []), "-", *args] + argv = [str(exe), *(_step_flags(script) if flags is None else flags), "-", *args] + # release.yml sets neither, and either one changes what a flagless control can reach: + # PYTHONSAFEPATH keeps the cwd off sys.path, PYTHONPATH adds another tree to it. + env = {k: v for k, v in os.environ.items() if k not in ("PYTHONSAFEPATH", "PYTHONPATH")} proc = subprocess.run( # noqa: S603 # nosec B603 - fixed argv, no shell, test-local paths argv, input=script.encode("utf-8"), cwd=str(workdir), + env=env, capture_output=True, timeout=120, ) @@ -2158,7 +2237,8 @@ def test_a_wheel_smoke_accepts_a_correctly_built_wheel( purelib, dist, pkg, _SMOKE_VERSION, package_files=_good_package(pkg, _SMOKE_VERSION) ) - rc, stdout, out = _run_smoke(exe, script, _intact_checkout(tmp_path / "checkout", pkg)) + work = _intact_checkout(tmp_path / "checkout", pkg) + rc, stdout, out = _run_smoke(exe, script, work) assert rc == 0, ( f"{job}'s smoke REJECTED a well-formed install, so every rejection below is measuring a " f"broken harness rather than the smoke.\n{out}" @@ -2175,6 +2255,15 @@ def test_a_wheel_smoke_accepts_a_correctly_built_wheel( ) assert _SHADOW_VERSION not in out, f"the intact checkout answered {job}'s smoke.\n{out}" + # THE INTACT CHECKOUT IS LIVE (BACKLOG #1583's acceptance). The run above used the step's own + # flags, so its pass shows those flags keep the checkout out only if the checkout would + # otherwise get in. The same run without them must be refused for exactly that reason. + rc, _stdout, out = _run_smoke(exe, script, work, flags=()) + assert rc != 0 and "OUTSIDE the smoke venv" in out, ( + f"without the step's flags ({' '.join(_step_flags(script)) or 'none'}) the intact checkout " + f"did not reach {job}'s smoke, so the pass above does not show the flags keep it out.\n{out}" + ) + def _no_package_tree(purelib: Path, dist: str, pkg: str) -> None: """The force-include produced nothing. Installs cleanly, named exactly like a good wheel.""" @@ -2288,7 +2377,7 @@ def test_a_wheel_smoke_refuses_a_module_resolved_outside_the_smoke_venv( for rel, text in _good_package(pkg, "9.9.9").items(): (shadow / pkg / rel).write_text(text, encoding="utf-8") - rc, _stdout, out = _run_smoke(exe, script, shadow, isolated=False) + rc, _stdout, out = _run_smoke(exe, script, shadow, flags=()) assert rc != 0, ( f"{job}'s smoke accepted a module resolved from the CHECKOUT instead of the smoke venv — it " f"would report on the source tree and never open the wheel.\n{out}" @@ -3168,6 +3257,7 @@ def _run_probe( """ env = dict(os.environ) env.pop("PYTHONPATH", None) + env.pop("PYTHONSAFEPATH", None) # it keeps the cwd off sys.path, so the bare arm would fail if pythonpath is not None: env["PYTHONPATH"] = str(pythonpath) return subprocess.run( # noqa: S603 # nosec B603 - fixed argv, no shell, test-local paths @@ -3179,7 +3269,7 @@ def _run_probe( text=True, encoding="utf-8", errors="replace", - timeout=60, + timeout=_HANG_TIMEOUT_S, check=False, ) @@ -3809,7 +3899,11 @@ def _run_notes_prefix(tmp_path: Path, case: str, changelog: str, *, bounded: boo env["GITHUB_REPOSITORY"] = "MEFORORG/MessageFoundry" bash = require_bash(tmp_path, env) proc = subprocess.run( # noqa: S603 # nosec B603 - fixed argv, no shell, test-local paths - [bash, "-e", str(script)], cwd=str(work), env=env, capture_output=True, timeout=60 + [bash, "-e", str(script)], + cwd=str(work), + env=env, + capture_output=True, + timeout=_HANG_TIMEOUT_S, ) out = (proc.stdout + proc.stderr).decode("utf-8", "replace") assert proc.returncode == 0, ( @@ -4361,6 +4455,104 @@ def test_a_draft_publisher_refuses_while_the_variable_is_set_and_the_upload_did_ assert not any("--draft=false" in c for c in calls), calls +#: The draft publishers' refusal, as each step echoes it. +_DRAFT_REFUSAL = re.compile(r'echo "(::error::\$GATE_NAME is \'true\'[^"\n]*)"') + +#: Clauses of that refusal which docs/SUPPLY-CHAIN.md, *The draft*, must carry too. Compared after +#: :func:`_flat_text`, so the doc's backticks and line wraps do not count, and with the refusal's +#: `$GATE_NAME` read as the doc's "the variable". The test below names a clause listed here once it +#: is gone from either copy, the organization prohibition among them (vault BACKLOG #2975 item 16). +#: Each is matched anywhere in the copy, so a clause the doc carries twice, such as "remove any +#: copy from the pypi environment", is named only once both are gone. The list is not every clause: +#: the publisher re-run step, for one, is worded differently in the two copies and is not compared. +_DRAFT_REFUSAL_CLAUSES = ( + "holds its own copy of the variable, with a value that is not true in any letter case", + "a copy removed since", + "the remedies below clear it either way, so it need not be told apart", + "remove any copy from the pypi environment", + "re-runs the jobs after it", + "a re-run failed jobs reuses the upload", + "is queued, waiting or in progress", + "none can start before the restore", + "note whether", + "such as false", + "for this repository only", + "do not edit or delete an organization copy", + "other repositories may read", + "whatever its result, and before the next release", + "deleting it if", + "or that release skips its upload too and still goes public", + "within 30 days of a runs first attempt", +) + + +def _flat_text(text: str) -> str: + """``text`` in lower case, with quotes and backticks dropped and whitespace runs made one space.""" + return " ".join(re.sub(r"[`'\"]", "", text).lower().split()) + + +def test_the_draft_refusal_is_one_text_and_the_doc_carries_each_clause() -> None: + """The refusal is kept by hand in three places: the two draft publishers' `::error::` strings + and docs/SUPPLY-CHAIN.md, *The draft* (vault BACKLOG #2975 item 16). The two strings must be + identical, and each clause in `_DRAFT_REFUSAL_CLAUSES` must be in both the string and the doc. + + Mutation: edit one publisher's string, or drop a clause, such as the organization prohibition, + from the string or the doc. Red here.""" + jobs = _jobs() + texts = [] + for publisher in (_PUBLISH_JOB, _CONSOLE_PUBLISH_JOB): + run = _executed_shell(str(_release_step(jobs[publisher], "--draft=false").get("run"))) + found = _DRAFT_REFUSAL.findall(run) + assert len(found) == 1, f"{publisher}: expected one draft refusal, found {len(found)}" + texts.append(found[0]) + assert texts[0] == texts[1], ( + f"{_PUBLISH_JOB} and {_CONSOLE_PUBLISH_JOB} echo different refusals; they share one text" + ) + doc = (_REPO / "docs" / "SUPPLY-CHAIN.md").read_text(encoding="utf-8") + start = doc.index("- **The draft.**") + section = _flat_text(doc[start : doc.index("- **The provenance gate.**", start)]) + refusal = _flat_text(texts[0].replace("$GATE_NAME", "the variable")) + # A floor, so an emptied clause list cannot pass vacuously. + assert len(_DRAFT_REFUSAL_CLAUSES) >= 15, _DRAFT_REFUSAL_CLAUSES + missing = [ + f"{clause!r} not in the {where}" + for clause in _DRAFT_REFUSAL_CLAUSES + for where, text in (("refusal", refusal), ("doc", section)) + if clause not in text + ] + assert not missing, "\n".join(missing) + + +#: The job-level pattern plus the contexts only a step-level `if:` adds: `env` and `steps`, either of +#: which can carry a variable in from an `env:` entry, and `inputs`, which is empty on a tag push. +#: Wide on purpose: a `steps.` condition that reads no variable is flagged too. +_STEP_GATE = re.compile( + rf"{_VARIABLE_GATE.pattern}|\b(?:env|steps|inputs)\b", flags=_VARIABLE_GATE.flags +) + + +@pytest.mark.parametrize("publisher", [_PUBLISH_JOB, _CONSOLE_PUBLISH_JOB]) +def test_no_step_of_a_draft_publisher_is_gated_on_a_variable(publisher: str) -> None: + """The job-level walk, `_variable_gated_jobs`, reads no step's `if:` (vault BACKLOG #2975 item + 12). A publisher step skipped by an unset variable leaves the release a draft on a green run, + so no step of either draft publisher may carry a variable gate. The planted gate is the + positive control. + + Mutation: put `if: vars.PUBLISH_HARNESS == 'true'` on a draft publisher's step. Red here.""" + job = copy.deepcopy(_jobs()[publisher]) + steps = [s for s in job["steps"] if isinstance(s, dict)] + assert steps, f"{publisher} has no steps" + + def gated() -> list[object]: + return [s.get("name") for s in steps if _STEP_GATE.search(str(s.get("if") or ""))] + + assert not gated(), f"{publisher} step(s) {gated()} are gated on a variable; unset, they skip" + publish = _release_step(job, "--draft=false") + for planted in ("vars.PUBLISH_HARNESS == 'true'", "env.GATE == 'true'", "inputs.go"): + publish["if"] = planted + assert gated() == [publish.get("name")], planted + + # --- (14) every PyPI publish runs in a publish-only job that names `pypi` (vault BACKLOG #2631) ------ # # The environment key sits on a whole job. Put on a job that also builds, an approval on the diff --git a/tests/test_revocation_guard_census.py b/tests/test_revocation_guard_census.py index 5cd4f7ec9d..394efe9c04 100644 --- a/tests/test_revocation_guard_census.py +++ b/tests/test_revocation_guard_census.py @@ -24,7 +24,7 @@ or that a guard checks a CRL: the behaviour tests (at least ``tests/test_revocation_guard_remaining_hops.py``, ``tests/test_hop_refusal_revocation.py`` and ``tests/test_vault_revocation_hop_guard.py``) prove that. A second hop added inside a function that -is already guarded passes here too, so read the function in review. +is already listed, Guarded or Exempt, passes here too, so read the function in review. **It goes red.** Delete the guard call from one guarded site and :func:`test_every_guarded_site_calls_a_guard` fails naming that site; measured when this file was @@ -34,7 +34,10 @@ renaming either link of the chain from the mount to the Vault guard failed :func:`test_every_guard_name_reaches_a_root`. So did a second def named ``refuse_an_unrevoked_hop`` in another module, and renaming the Vault guard's ``_crossed_unrevoked`` call failed -:func:`test_the_vault_root_decides_through_the_authority`. +:func:`test_the_vault_root_decides_through_the_authority`. Moving the ``EmailDestination.__init__`` +entry from Guarded to Exempt and deleting its ``RevocationHopGuard.capture`` call failed +:func:`test_the_exempt_sites_are_the_pinned_list` and no other test in this file; before that test +existed, the same change passed them all (vault BACKLOG #3512). **The relaxed-hop handoff census** at the end of this file is a second list, of the sites that reach ``relax_verify_expiry`` (vault BACKLOG #5086). ``RevocationHopGuard.capture`` gives no CRL @@ -324,6 +327,32 @@ def __post_init__(self) -> None: ), } +#: The sites :data:`_CENSUS` lists as Exempt, pinned exactly (vault BACKLOG #3512). A Guarded hop +#: moved to Exempt, with its guard call deleted, can pass every other check here (a relaxed hop +#: fails its own census below), so this list is the second edit such a change needs. A diff that +#: edits both still passes, so review stays the check on what is added here. What this census +#: does not prove is in the module docstring. +_EXEMPT_SITES = frozenset( + { + "messagefoundry/apiclient/client.py::_build_verify_context", + "messagefoundry/auth/trust_anchors.py::anchor_cadata", + "messagefoundry/config/tls_policy.py::", + "messagefoundry/config/tls_policy.py::crl_scratch_context", + "messagefoundry/config/tls_probe.py::_offer_context", + "messagefoundry/pki.py::_all_load_as_no_ca", + "messagefoundry/pki.py::_openssl_reads_as_ca", + "messagefoundry/pki.py::_refuse_unless_openssl_loads", + "messagefoundry/transports/http_listener.py::HttpSource.__init__", + "messagefoundry/transports/mllp.py::MLLPSource.__init__", + "messagefoundry/transports/rest.py::_insecure_opener", + "messagefoundry/transports/rest.py::_shared_no_redirect_opener", + "messagefoundry/tray/probe.py::_pinned_context", + "messagefoundry/tray/probe.py::build_verify", + "messagefoundry/verify/federation.py::_idp_opener", + "messagefoundry/verify/smoke.py::live_smoke_ssl_context", + } +) + @dataclass(frozen=True, slots=True) class _Scan: @@ -435,18 +464,27 @@ def _scan() -> _Scan: def test_every_site_is_in_the_census() -> None: """The check that stops the next unguarded hop: a new site fails here until it is classified.""" - unlisted = sorted(_scan().sites - _CENSUS.keys()) + sites = _scan().sites + # 42 sites when this floor was set (vault BACKLOG #3512), so 30 lets twelve go with no edit + # here. Each retired site still needs its census entry deleted, by the test below. + # It fails a scan that finds nothing, over which the check below would pass. + assert len(sites) >= 30, f"the scan found only {len(sites)} sites, floor 30" + unlisted = sorted(sites - _CENSUS.keys()) assert not unlisted, ( f"verifying client TLS context(s) with no census entry: {unlisted}. Add a guard " f"(RevocationHopGuard.capture, refuse_unrevoked_verified_hop for an https hop, or " f"mount_strict_reply_adapter for an hvac Vault client, which must not use " - f"RevocationHopGuard) and list the site as Guarded, or list it as Exempt with the reason. " + f"RevocationHopGuard) and list the site as Guarded, or list it as Exempt with the reason " + f"and add it to _EXEMPT_SITES. " f"See ADR 0173 and docs/DEPLOYMENT.md, 'Revocation-guard behavior'." ) def test_every_census_entry_is_still_a_site() -> None: """A stale entry would keep an exemption alive for code that no longer exists.""" + # 42 entries when this floor was set (vault BACKLOG #3512). It fails a census emptied, over + # which the check below would pass. + assert len(_CENSUS) >= 30, f"only {len(_CENSUS)} census entries, floor 30" stale = sorted(_CENSUS.keys() - _scan().sites) assert not stale, f"census entries that are no longer a site: {stale}" @@ -454,9 +492,9 @@ def test_every_census_entry_is_still_a_site() -> None: def test_every_guarded_site_calls_a_guard() -> None: scan = _scan() guarded = {site: entry for site, entry in _CENSUS.items() if isinstance(entry, Guarded)} - # 15 sites were Guarded when this floor was set, so 10 lets up to five retire with no edit here. - # It is a floor against a census emptied or turned all Exempt, over which the check below would - # pass on nothing. It does not catch a single hop moved from Guarded to Exempt; review does. + # A floor against a census emptied or turned all Exempt, over which the check below would pass + # on nothing. A single hop moved from Guarded to Exempt fails the next test unless + # _EXEMPT_SITES moves too. assert len(guarded) >= 10, f"only {len(guarded)} Guarded census entries, floor 10" unguarded = [ f"{site} (guard expected in {entry.by or 'the site itself'}; {entry.note or 'no note'})" @@ -466,6 +504,17 @@ def test_every_guarded_site_calls_a_guard() -> None: assert not unguarded, f"census sites marked Guarded whose guard call is gone: {unguarded}" +def test_the_exempt_sites_are_the_pinned_list() -> None: + """A Guarded hop moved to Exempt fails here, named, unless :data:`_EXEMPT_SITES` moves too.""" + exempt = {site for site, entry in _CENSUS.items() if isinstance(entry, Exempt)} + assert exempt == _EXEMPT_SITES, ( + f"Exempt in the census, not in _EXEMPT_SITES: {sorted(exempt - _EXEMPT_SITES)}; in " + f"_EXEMPT_SITES, not Exempt in the census: {sorted(_EXEMPT_SITES - exempt)}. Add a site to " + f"_EXEMPT_SITES only once review has read the exemption's reason; a hop moved there from " + f"Guarded loses its revocation guard" + ) + + def _def_count(name: str) -> int: """How many ``def``s named ``name`` the package holds, nested ones and methods included.""" return sum( diff --git a/tests/test_rotate_key_rotation_record.py b/tests/test_rotate_key_rotation_record.py index 0eae5cc024..21ae9328e3 100644 --- a/tests/test_rotate_key_rotation_record.py +++ b/tests/test_rotate_key_rotation_record.py @@ -941,3 +941,45 @@ async def test_engine_start_passes_the_chain_answer_and_holds_the_key(tmp_path: assert rows[_DEK].fingerprint == dek_fingerprint(_key_id(key_a)) assert rows[_DEK].last_rotated == _OLD_DATE assert rows[ROTATION_RECORD_ID].fingerprint == dek_fingerprint(_key_id(key_b)) + + +async def test_engine_start_before_any_run_on_a_store_with_no_keyed_chain_still_stamps( + tmp_path: Path, +) -> None: + """BACKLOG #4942's remainder, as the code stands. A ``serve`` start on a new key before any + ``rotate-key`` run, on a store with no keyed audit chain: the store is opened through + ``open_store`` with no ``before_first_write`` hook, as ``serve`` passes none (only + ``rotate-key`` passes one, BACKLOG #4936), and a real ``Engine.start`` runs the reconcile. Nothing tells this + start from a key changed by hand after a run, so it stamps the new key and opens no record. + Whether this order is to be refused or held, or left to the warning, is the row's open + decision; this test pins what the code does until it is made.""" + from messagefoundry.config.settings import EgressSettings, StoreSettings + from messagefoundry.pipeline.engine import Engine + from messagefoundry.store.base import open_store + + db, key_a, key_b = tmp_path / "keyless.db", generate_key(), generate_key() + await _seed_keyless_chain(db, tmp_path / "uploads", key_a) + store = await open_store( + StoreSettings(path=str(db), encryption_key=key_b, encryption_keys_retired=key_a), + keyless_chain_refusal=None, + ) + try: + assert isinstance(store, MessageStore) + assert audit_chain_rolled(store) is None # no keyed chain to answer from + engine = Engine( + store, + secret_rotation_settings=SecretRotationSettings(), + security_enforcement=SecurityEnforcement.WARN, + egress_settings=EgressSettings(deny_by_default=False), + ) + except BaseException: + await store.close() # engine.stop() closes it otherwise + raise + try: + await engine.start() + rows = await store.get_secret_rotation_meta() + finally: + await engine.stop() + assert rows[_DEK].fingerprint == dek_fingerprint(_key_id(key_b)) + assert rows[_DEK].last_rotated != _OLD_DATE + assert ROTATION_RECORD_ID not in rows diff --git a/tests/test_scan_forbidden.py b/tests/test_scan_forbidden.py index 1399586dba..f09b4fd1b8 100644 --- a/tests/test_scan_forbidden.py +++ b/tests/test_scan_forbidden.py @@ -1317,6 +1317,59 @@ def test_a_header_row_marks_only_its_own_table_and_column(sf) -> None: # A marked identifier is never exempt. ("10", "verdict", f"ASVS {_REQ}: the row is not failing but stays {_PARTIAL}."), ("10", "verdict", f"| ASVS {_REQ} | the parser | is never failing; the cell is failing |"), + # A blank line after a dash placeholder row, or between ASVS tables, ends nothing either. + ("9", "verdict", f"{_HEAD}| - | - | - |\n\n{_ROW}"), + ( + "9", + "verdict", + f"{_HEAD}| a | b | c |\n\n| ASVS {_REQ} | the limb | {_PASS.title()} (12 messages) |", + ), + ("9", "verdict", f"{_HEAD}| a | b | c |\n\n{_HEAD}{_ROW}"), + # Step 8: an escaped pipe in the header and in the row, and an escaped backslash before a real + # pipe in the header. Main flags each too; these pin the columns. + ("8", "verdict", f"| a \\| b | ASVS | Note | Result |\n|---|---|---|---|\n| a \\| b {_ROW}"), + ("8", "verdict", f"| a \\\\| ASVS | Note | Result |\n|---|---|---|---|\n| x {_ROW}"), + # Step 11, the hedge vocabularies: one list (_PR_HEDGE) for every place a hedge stands. Each of + # these missed while the lists differed. + ("11", "verdict", f"ASVS {_REQ} has likely been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} is only {_PARTIAL}."), + ("11", "verdict", f"ASVS {_REQ} is also {_PARTIAL}."), + ("11", "verdict", f"ASVS {_REQ} never stays {_PARTIAL}."), + ("11", "verdict", f"ASVS {_REQ} will already stay {_PARTIAL}."), + ("11", "verdict", f"ASVS {_REQ} honestly stays {_PARTIAL}."), + ("11", "verdict", f"ASVS {_REQ} will so stay {_PARTIAL}."), + # Step 11: underscore emphasis on the word that ends a modal's clause. + ("11", "verdict", f"{_REQ} cannot {_PASS} _yet_."), + ("11", "verdict", f"{_REQ} will {_FAIL} _today_."), + ("11", "verdict", f"{_REQ} cannot {_PASS} *yet*."), + ("11", "verdict", f"{_REQ} will {_FAIL} **today**."), + ("11", "verdict", f"{_REQ} cannot {_PASS} `yet`."), + # Step 11: a hedge before the negation, and markup or extra space inside "has ... been". + ("11", "verdict", f"ASVS {_REQ} has still not been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} has likely not been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} has *likely* been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} has _never_ been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} has **not** been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} has likely been {_MET}."), + # A hedge after the modal's record verb keeps it strong, beside an unmarked id or a version. + # The "already" pair is flagged by main and was lost by an earlier head of this branch. + ("11", "verdict", f"{_REQ} will remain already {_PARTIAL} for the parser"), + ( + "11", + "verdict", + f"Applies to lxml 5.1.1, which will remain already {_PARTIAL} for the parser", + ), + ("11", "verdict", f"{_REQ} will remain only {_PARTIAL} for the parser"), + ("11", "verdict", f"{_REQ} will stay still {_PARTIAL} for the parser"), + # Step 11: underscore emphasis on a cell's connective and on a list's "and". Main flags each + # through the markup-deleted reading of the cell; these pin it. + ("11", "verdict", f"| ASVS {_REQ} | the limb | {_PASS.title()} _until_ the fix |"), + ("11", "verdict", f"| {_REQ} _and_ {_REQ_B} | {_PARTIAL} |"), + # Step 11: a zero-width character before the first pipe of a data row, a delimiter row or a + # header row. + ("11", "verdict", f"{_HEAD}{chr(0x200B)}{_ROW}"), + ("11", "verdict", f"| ASVS | Note | Result |\n{chr(0x200B)}|---|---|---|\n{_ROW}"), + ("11", "verdict", f"{chr(0x200B)}{_HEAD}{_ROW}"), ] #: The six bodies engine PR 2893's review named as false positives: CI prose and a component row about #: HL7 v2.5.1. Main flags each. Step 10, which an earlier head of this branch built to drop them, was @@ -1502,6 +1555,13 @@ def test_a_header_row_marks_only_its_own_table_and_column(sf) -> None: ("11", f"| Version (not an ASVS id) | Note | Result |\n|---|---|---|\n{_ROW}"), ("11", f"| Version (not ASVS) | Note | Result |\n|---|---|---|\n{_ROW}"), ("11", f"| Not in ASVS | Note | Result |\n|---|---|---|\n{_ROW}"), + # Step 11: the same hedges beside a version, or before a CI verdict on an unmarked id; emphasis + # on a word that starts an object; a zero-width character before a row under a header that does + # not name ASVS. + ("11", f"Python 3.9.7 has likely been {_MET}."), + ("11", "The parser on 2.5.1 is only passing locally."), + ("11", f"{_REQ} will {_FAIL} _the_ handshake."), + ("11", f"| Version | Note | Result |\n|---|---|---|\n{chr(0x200B)}{_ROW}"), ] @@ -2815,8 +2875,9 @@ def _generated_pr_bodies(count: int = 600) -> list[str]: def test_the_scan_reports_at_least_every_hit_origin_main_reported(sf, sf_frozen_main) -> None: """The baseline is one pass of the union, but it runs the head's table model, so this is not true - by construction. The test pins it, with no exception, against two oracles: the pre-BACKLOG #5582 - reading rebuilt here, and the vendored origin/main scanner with #5582's readings.""" + by construction. The test pins it, with no exception, against two + oracles: the pre-BACKLOG #5582 reading rebuilt here, and the vendored origin/main scanner with + #5582's readings.""" harvested = set(_harvested_pr_bodies()) fired_harvested = fired_generated = 0 for body in [*harvested, *_generated_pr_bodies()]: diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 5e39e13b26..5755daa9c6 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -15,6 +15,7 @@ from __future__ import annotations import sqlite3 +import traceback from collections.abc import AsyncIterator from contextlib import asynccontextmanager from pathlib import Path @@ -22,13 +23,16 @@ import aiosqlite import pytest +from messagefoundry.redaction import _COUNT_OPENER, safe_exc from messagefoundry.store import MessageStore from messagefoundry.store.schema_verify import ( _ORDINARY_TABLE, SchemaMismatchError, + _remedy, is_schema_step_error, live_schema_differences, read_schema_shape, + run_schema_step, ) from messagefoundry.store.store import _SCHEMA, _await_connection_worker_exit @@ -200,10 +204,10 @@ async def test_a_counted_store_whose_salt_is_a_readable_foreign_object_gets_the_ _TABLES_FLAGGED_VIRTUAL = ( f"SELECT m.name, NOT ({_ORDINARY_TABLE}) FROM sqlite_master AS m WHERE m.type = 'table'" ) -#: Every schema object with a flag saying whether it is a view, so one walk both counts what it saw -#: and finds the views (a view query alone returns nothing on the built schema, so it cannot show it -#: ran). The flag is in the SQL, so the negative control below pins the same predicate. -_OBJECTS_FLAGGED_VIEW = "SELECT name, type = 'view' FROM sqlite_master" +#: Every schema object with a flag saying whether it is a view or a trigger, so one walk both counts +#: what it saw and finds those (a query for them alone returns nothing on the built schema, so it +#: cannot show it ran). The flag is in the SQL, so the negative control below pins the same predicate. +_OBJECTS_FLAGGED_VIEW_OR_TRIGGER = "SELECT name, type IN ('view', 'trigger') FROM sqlite_master" async def test_the_expected_shape_holds_no_virtual_table() -> None: @@ -215,7 +219,7 @@ async def test_the_expected_shape_holds_no_virtual_table() -> None: await MessageStore._migrate(db) async with db.execute(_TABLES_FLAGGED_VIRTUAL) as cur: tables = [tuple(r) for r in await cur.fetchall()] - async with db.execute(_OBJECTS_FLAGGED_VIEW) as cur: + async with db.execute(_OBJECTS_FLAGGED_VIEW_OR_TRIGGER) as cur: objects = [tuple(r) for r in await cur.fetchall()] # Positive control: the walk saw the built schema (40 tables when this floor was set), so the # absence below cannot pass on an empty walk. @@ -227,24 +231,30 @@ async def test_the_expected_shape_holds_no_virtual_table() -> None: virtual = [name for name, is_virtual in tables if is_virtual] assert virtual == [] # The reads skip views too, so a view this build created would never be verified either - # (BACKLOG #6719 item 10). - views = [name for name, is_view in objects if is_view] - assert views == [] + # (BACKLOG #6719 item 10). And the foreign-object remedy tells the operator to drop a view or a + # trigger that stops an upgrade, which is safe only while this build creates neither. + views_or_triggers = [name for name, flagged in objects if flagged] + assert views_or_triggers == [] async def test_the_virtual_table_probe_finds_one_without_fts5(tmp_path: Path) -> None: # Negative control for the pin above that needs no fts5 (BACKLOG #6719 item 8): a planted - # virtual table is flagged, an ordinary one is not, and the view flag marks a view. + # virtual table is flagged, an ordinary one is not, and the view flag marks a view and a trigger. path = tmp_path / "probe.db" - _sql(path, "CREATE TABLE plain (a)", "CREATE VIEW v AS SELECT 1") + _sql( + path, + "CREATE TABLE plain (a)", + "CREATE VIEW v AS SELECT 1", + "CREATE TRIGGER tr AFTER INSERT ON plain BEGIN SELECT 1; END", + ) _plant_unloaded_virtual_table(path, "planted") async with _connected(path) as db: async with db.execute(_TABLES_FLAGGED_VIRTUAL) as cur: rows = {r[0]: bool(r[1]) for r in await cur.fetchall()} - async with db.execute(_OBJECTS_FLAGGED_VIEW) as cur: - views = [name for name, is_view in await cur.fetchall() if is_view] + async with db.execute(_OBJECTS_FLAGGED_VIEW_OR_TRIGGER) as cur: + flagged = {name for name, is_one in await cur.fetchall() if is_one} assert rows == {"plain": False, "planted": True} - assert views == ["v"] + assert flagged == {"v", "tr"} async def test_a_planted_ordinary_table_with_rootpage_zero_is_not_skipped(tmp_path: Path) -> None: @@ -410,3 +420,530 @@ async def test_the_open_refuses_a_name_held_by_another_kind_of_object( assert text.startswith(f"store {path} is from an incompatible version; recreate it:"), text assert info.value.cause is not None and cause in info.value.cause, info.value.cause assert isinstance(info.value.__cause__, sqlite3.OperationalError) + + +# --- BACKLOG #6719 item 3: a foreign view or trigger that stops the upgrade ------------------------ + + +def _preset_columns(path: Path) -> set[str]: + conn = sqlite3.connect(path) + try: + return {r[1] for r in conn.execute("PRAGMA table_info(search_presets)")} + finally: + conn.close() + + +@pytest.mark.parametrize( + ("kind", "dependent", "drop"), + [ + pytest.param("view", "CREATE VIEW vv AS SELECT x FROM vt", "DROP VIEW vv", id="view"), + pytest.param( + "trigger", + "CREATE TRIGGER tt AFTER INSERT ON users BEGIN SELECT x FROM vt; END", + "DROP TRIGGER tt", + id="trigger", + ), + ], +) +async def test_a_foreign_object_that_stops_a_migration_gets_the_drop_remedy( + tmp_path: Path, kind: str, dependent: str, drop: str, monkeypatch: pytest.MonkeyPatch +) -> None: + # A 0.3.2 preset table needs the RENAME COLUMN migration, and SQLite re-checks every view and + # trigger after it. One that reads an unloaded module fails that check, naming itself. The store + # is otherwise this build's, so the remedy is to drop that object, not to recreate the store. + # A short relative path keeps the remedy inside the cut whatever the runner's temp path is. + monkeypatch.chdir(tmp_path) + path = Path("foreign.db") + await _fresh(path) + _sql(path, "ALTER TABLE search_presets RENAME COLUMN owner_user_id TO owner") + _plant_unloaded_virtual_table(path, "vt") + name, table = dependent.split()[2], "vv" if kind == "view" else "users" + conn = sqlite3.connect(path) + try: + conn.execute("PRAGMA writable_schema = ON") + conn.execute( + "INSERT INTO sqlite_master (type, name, tbl_name, rootpage, sql) VALUES (?, ?, ?, 0, ?)", + (kind, name, table, dependent), + ) + conn.commit() + finally: + conn.close() + with pytest.raises(SchemaMismatchError) as info: + await _fresh(path) + cause = info.value.cause + assert cause is not None and cause.startswith(f"error in {kind} {name}: no such module"), cause + text = str(info.value) + assert text.startswith( + f"store {path}: save the CREATE statement of the {kind} '{name}' from sqlite_master, drop" + " it, and restart." + ), text + assert "recreate" not in text and "NEW store key" not in text, text + # The remedy is true: with that object dropped, the same migration runs and the open succeeds. + _sql(path, drop) + await _fresh(path) + assert "owner_user_id" in _preset_columns(path) + + +# --- BACKLOG #6720 item 4: the verify's own read -------------------------------------------------- + + +async def test_a_shape_error_from_the_verify_read_is_refused_with_the_remedy( + tmp_path: Path, +) -> None: + # No statement of the script or the migrations touches shared_body, so the first read of it is + # the verify's column read. A virtual table whose stored SQL the ordinary-table predicate does + # not recognise (two spaces) is read there, and its unloaded module raises. + path = tmp_path / "read.db" + await _fresh(path) + _sql( + path, + "DROP TABLE shared_body", + "PRAGMA writable_schema = ON", + "INSERT INTO sqlite_master (type, name, tbl_name, rootpage, sql) VALUES ('table'," + " 'shared_body', 'shared_body', 0," + " 'CREATE VIRTUAL TABLE shared_body USING no_such_module(x)')", + ) + with pytest.raises(SchemaMismatchError) as info: + await _fresh(path) + text = str(info.value) + assert text.startswith(f"store {path} is from an incompatible version; recreate it:"), text + assert "The schema step failed: no such module" in text, text + cause = info.value.__cause__ + assert isinstance(cause, sqlite3.OperationalError) + # The verify's read raised it, not the script or a migration. + frames = {f.name for f in traceback.extract_tb(cause.__traceback__)} + assert {"run_schema_step", "read_schema_shape"} <= frames, frames + + +def _real_sqlite_error(statement: str) -> sqlite3.OperationalError: + conn = sqlite3.connect(":memory:") + try: + with pytest.raises(sqlite3.OperationalError) as info: + conn.execute(statement) + finally: + conn.close() + return info.value + + +async def _verify_raising( + monkeypatch: pytest.MonkeyPatch, target: str, exc: sqlite3.OperationalError +) -> BaseException: + """``verify_live_schema`` with ``target`` raising ``exc``; returns what the verify raised.""" + from messagefoundry.store import schema_verify + + # Warm the expected shape first: its scratch build calls read_schema_shape too, and on a cold + # cache the patched error would come from there rather than from the live read. + await schema_verify._expected_shape(_SCHEMA, MessageStore._migrate) + + async def raising(*_args: object, **_kwargs: object) -> object: + raise exc + + monkeypatch.setattr(schema_verify, target, raising) + async with _connected(":memory:") as db: + with pytest.raises(sqlite3.OperationalError) as info: + await schema_verify.verify_live_schema( + db, + schema=_SCHEMA, + migrate=MessageStore._migrate, + path="x.db", + counts_under_dek=False, + ) + return info.value + + +async def test_a_read_error_that_is_not_a_shape_keeps_its_own_error( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Control: a real SQLITE_ERROR whose message names no shape is not given the remedy. + exc = _real_sqlite_error("SELEC 1") + assert exc.sqlite_errorcode & 0xFF == sqlite3.SQLITE_ERROR + assert await _verify_raising(monkeypatch, "read_schema_shape", exc) is exc + frames = {f.name for f in traceback.extract_tb(exc.__traceback__)} + assert "run_schema_step" in frames, frames + + +async def test_a_failure_building_the_expected_shape_keeps_its_own_error( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A shape message from this build's own scratch build is this build's defect, which recreating + # the store would not fix, so only the live read is classified. + exc = _real_sqlite_error("SELECT missing FROM sqlite_master") + assert is_schema_step_error(exc), str(exc) + assert await _verify_raising(monkeypatch, "_expected_shape", exc) is exc + + +@pytest.mark.parametrize( + ("view_name", "cause", "found"), + [ + pytest.param("vv", "error in view vv: no such module: m", ("view", "vv"), id="plain"), + pytest.param( + "vv", "error in view vv after rename: no such column: c", ("view", "vv"), id="suffix" + ), + pytest.param("a:b", "error in view a:b: no such module: m", ("view", "a:b"), id="colon"), + pytest.param("users", "error in view users: no such module: m", None, id="expected-table"), + pytest.param( + "USERS", "error in view USERS after rename: no such column: c", None, id="expected-case" + ), + pytest.param( + "ix_queue_fifo_in_seq", + "error in view ix_queue_fifo_in_seq: no such module: m", + None, + id="expected-index", + ), + pytest.param("vv", "error in table vv: no such module: m", None, id="a-table"), + pytest.param("vv", "error in view other: no such module: m", None, id="not-in-the-file"), + ], +) +async def test_the_foreign_object_is_matched_against_the_file( + tmp_path: Path, view_name: str, cause: str, found: tuple[str, str] | None +) -> None: + from messagefoundry.store.schema_verify import _foreign_objects + + path = tmp_path / "named.db" + _sql(path, f'CREATE VIEW "{view_name}" AS SELECT 1 AS a') + async with _connected(path) as db: + assert await _foreign_objects(db, cause) == ((found,) if found else ()) + + +@pytest.mark.parametrize( + ("views", "reads", "statement", "expected_cause", "found"), + [ + pytest.param( + ("vv", "vv after"), + "c FROM t", + "ALTER TABLE t DROP COLUMN c", + "error in view vv after drop column: no such column: c", + ("vv",), + id="vv-after-the-change", + ), + pytest.param( + ("vv after", "vv"), + "c FROM t", + "ALTER TABLE t DROP COLUMN c", + "error in view vv after after drop column: no such column: c", + ("vv", "vv after"), + id="vv-after-after-the-change", + ), + pytest.param( + ("vv", "vv after"), + "missing FROM t", + "ALTER TABLE t RENAME TO t2", + "error in view vv: no such column: missing", + ("vv",), + id="vv-before-the-change", + ), + pytest.param( + ("vv after", "vv"), + "missing FROM t", + "ALTER TABLE t RENAME TO t2", + "error in view vv after: no such column: missing", + ("vv after",), + id="vv-after-before-the-change", + ), + pytest.param( + ("vv", "vv after drop column"), + "c FROM t", + "ALTER TABLE t DROP COLUMN c", + "error in view vv after drop column: no such column: c", + ("vv", "vv after drop column"), + id="broken-vv-beside-a-healthy-suffix-name", + ), + pytest.param( + ("vv", "vv: no such column"), + "missing FROM t", + "ALTER TABLE t RENAME TO t2", + "error in view vv: no such column: missing", + ("vv", "vv: no such column"), + id="broken-vv-beside-a-healthy-message-name", + ), + pytest.param( + ("a:b", "a"), + "missing FROM t", + "ALTER TABLE t RENAME TO t2", + "error in view a:b: no such column: missing", + ("a:b",), + id="a-bare-colon-is-not-the-separator", + ), + pytest.param( + ("users after drop column", "users"), + "missing FROM t", + "ALTER TABLE t RENAME TO t2", + "error in view users after drop column: no such column: missing", + (), + id="a-candidate-under-an-expected-name", + ), + ], +) +async def test_a_name_that_is_a_prefix_of_another_is_told_apart( + tmp_path: Path, + views: tuple[str, str], + reads: str, + statement: str, + expected_cause: str, + found: tuple[str, ...], +) -> None: + # Views "vv" and "vv after" both fit "error in view vv after ...", so the longest name alone + # would tell the operator to drop "vv after" when "vv" stopped the change. Each cause is + # SQLite's own text, and views[0] is the broken view. A view already broken fails SQLite's + # first check, with no suffix; a view the change breaks fails its re-check after the change, + # with the "after drop column" suffix. Where both names rank first the code does not pick + # between them, so both are returned and the remedy names neither. In the suffix-name pair the + # text itself cannot settle the pair, since the healthy view's own name holds the suffix. The + # message-name pair and "vv after after drop column" are ones a list of SQLite's messages or + # suffixes could settle, and the code keeps none (see _foreign_objects). SQLite writes ": " + # after a name, so "a" is no candidate for "a:b". A view under a name this build creates among + # the candidates gives the plain remedy, so nothing is returned. + from messagefoundry.store.schema_verify import _foreign_objects + + path = tmp_path / "prefix.db" + _sql(path, "CREATE TABLE t (a, c)", "CREATE TABLE u (c)") + broken, healthy = views + _sql(path, f'CREATE VIEW "{broken}" AS SELECT {reads}') + _sql(path, f'CREATE VIEW "{healthy}" AS SELECT c FROM u') + conn = sqlite3.connect(path) + try: + with pytest.raises(sqlite3.OperationalError) as info: + conn.execute(statement) + finally: + conn.close() + assert str(info.value) == expected_cause + async with _connected(path) as db: + assert await _foreign_objects(db, expected_cause) == tuple(("view", n) for n in found) + + +_SERVICE_PATH = r"C:\ProgramData\MessageFoundry\data\stores\production\instance-a\messagefoundry.db" +_CAUSE = "error in view {} after drop column: no such column: c" + + +def _named(name: str) -> tuple[str, str]: + """The one-name remedy for view ``name`` on _SERVICE_PATH, and the whole message.""" + remedy = ( + f"store {_SERVICE_PATH}: save the CREATE statement of the view {name!r} from sqlite_master," + " drop it, and restart." + ) + message = ( + f"{remedy} This build did not create it, and it stops the store's upgrade. The schema step" + f" failed: {_CAUSE.format(name)}." + ) + return remedy, message + + +async def _refusal(path: Path, broken: str) -> SchemaMismatchError: + # The refusal for one broken view, which the DROP COLUMN re-check names. + _sql(path, "CREATE TABLE t (a, c)", f'CREATE VIEW "{broken}" AS SELECT c FROM t') + async with _connected(path) as db: + with pytest.raises(SchemaMismatchError) as info: + await run_schema_step( + db, + db.execute("ALTER TABLE t DROP COLUMN c"), + path=_SERVICE_PATH, + counts_under_dek=False, + ) + assert isinstance(info.value.__cause__, sqlite3.OperationalError) + return info.value + + +def _plain(cause: str) -> str: + return f"store {_SERVICE_PATH} {_remedy(False)} The schema step failed: {cause}." + + +async def test_one_name_is_named_only_while_its_whole_remedy_survives_the_cut( + tmp_path: Path, +) -> None: + # safe_exc cuts a printed error at 200 characters, marking the cut with _COUNT_OPENER. The + # longest name whose remedy ends before that marker is named, with the whole text pinned; one + # character more and the remedy would be cut, so the plain remedy names no object. + stem = "daily_census_by_unit_and_attending_for_the_weekly_report_of_the_quality_team" + fits = 0 + for k in range(1, len(stem) + 1): + remedy, message = _named(stem[:k]) + rendered = safe_exc(SchemaMismatchError(message)) + if not rendered.startswith(f"SchemaMismatchError: {remedy}"): + break + fits = k + assert 0 < fits < len(stem) + name, longer = stem[:fits], stem[: fits + 1] + + remedy, message = _named(name) + refusal = await _refusal(tmp_path / "fits.db", name) + assert str(refusal) == message + assert refusal.cause == _CAUSE.format(name) + rendered = safe_exc(refusal) + assert rendered.startswith(f"SchemaMismatchError: {remedy}"), rendered + + remedy, message = _named(longer) + rendered = safe_exc(SchemaMismatchError(message)) + assert remedy not in rendered and _COUNT_OPENER in rendered, rendered + refusal = await _refusal(tmp_path / "cut.db", longer) + assert str(refusal) == _plain(_CAUSE.format(longer)) + + +@pytest.mark.parametrize( + ("healthy", "reads", "statement", "cause"), + [ + pytest.param( + "vv after drop column", + "c FROM t", + "ALTER TABLE t DROP COLUMN c", + "error in view vv after drop column: no such column: c", + id="healthy-suffix-name", + ), + pytest.param( + "vv: no such column", + "missing FROM t", + "ALTER TABLE t RENAME TO t2", + "error in view vv: no such column: missing", + id="healthy-message-name", + ), + ], +) +async def test_two_candidates_get_the_plain_remedy( + tmp_path: Path, healthy: str, reads: str, statement: str, cause: str +) -> None: + # A broken vv beside a healthy view. The text fits both, so naming either could tell the + # operator to drop the healthy one. + path = tmp_path / "both.db" + _sql(path, "CREATE TABLE t (a, c)", "CREATE TABLE u (c)") + _sql(path, f"CREATE VIEW vv AS SELECT {reads}") + _sql(path, f'CREATE VIEW "{healthy}" AS SELECT c FROM u') + async with _connected(path) as db: + with pytest.raises(SchemaMismatchError) as info: + await run_schema_step( + db, db.execute(statement), path=_SERVICE_PATH, counts_under_dek=False + ) + assert info.value.cause == cause + assert str(info.value) == _plain(cause) + + +async def test_a_last_rank_only_match_gets_the_plain_remedy(tmp_path: Path) -> None: + # A broken TEMP view "vv x" is outside the main schema the match reads, so the only name the + # text fits is the healthy "vv", with the remainder " x: ...". That is no form SQLite writes + # after the object it names, so "vv" is not named and the remedy is main's plain one. + path = tmp_path / "temp.db" + _sql(path, "CREATE TABLE t (a)", "CREATE VIEW vv AS SELECT a FROM t") + async with _connected(path) as db: + await db.execute('CREATE TEMP VIEW "vv x" AS SELECT missing FROM t') + with pytest.raises(SchemaMismatchError) as info: + await run_schema_step( + db, + db.execute("ALTER TABLE t RENAME TO t2"), + path=_SERVICE_PATH, + counts_under_dek=False, + ) + cause = "error in view vv x: no such column: missing" + assert info.value.cause == cause + assert str(info.value) == _plain(cause) + + +@pytest.mark.parametrize( + ("kind", "names", "cause", "found"), + [ + pytest.param( + "view", + ("vv", "vv after"), + "error in view vv after rename: no such module: m", + ("vv",), + id="vv-after-rename", + ), + pytest.param( + "view", + ("vv", "vv after"), + "error in view vv after after rename: no such module: m", + ("vv", "vv after"), + id="vv-after-after-rename", + ), + pytest.param( + "view", + ("vv", "vv: x"), + "error in view vv: x after rename: no such module: m", + ("vv", "vv: x"), + id="colon-name-after-rename", + ), + pytest.param( + "view", + ("vv", "vv: x"), + "error in view vv: no such module: m", + ("vv",), + id="colon-name-prefix", + ), + pytest.param( + "view", + ("vv", "vv after x"), + "error in view vv after x: no such module: m", + ("vv", "vv after x"), + id="colon-outranks-a-shorter-after", + ), + pytest.param( + "trigger", + ("tr", "tr after"), + "error in trigger tr after rename: no such module: m", + ("tr",), + id="trigger-after-rename", + ), + pytest.param( + "trigger", + ("tr", "tr after"), + "error in trigger tr after after rename: no such module: m", + ("tr", "tr after"), + id="trigger-after-after-rename", + ), + ], +) +async def test_a_prefix_name_is_told_apart_in_the_rename_recheck( + tmp_path: Path, kind: str, names: tuple[str, str], cause: str, found: tuple[str, ...] +) -> None: + # The RENAME COLUMN migration's re-check writes the " after rename" suffix. These causes are + # written out in SQLite's form rather than raised, so one test can cover a colon name and a + # trigger pair without a view or trigger built to break under each. + from messagefoundry.store.schema_verify import _foreign_objects + + path = tmp_path / "prefix.db" + _sql(path, "CREATE TABLE t (a)") + for name in names: + if kind == "view": + _sql(path, f'CREATE VIEW "{name}" AS SELECT a FROM t') + else: + _sql(path, f'CREATE TRIGGER "{name}" AFTER INSERT ON t BEGIN SELECT 1; END') + async with _connected(path) as db: + assert await _foreign_objects(db, cause) == tuple((kind, n) for n in found) + + +# --- BACKLOG #6720 item 1: a foreign view using an unloaded function or collation ---------------- + + +@pytest.mark.parametrize( + "view", + [ + pytest.param("CREATE VIEW vf AS SELECT f(name) AS n FROM search_presets", id="function"), + pytest.param( + "CREATE VIEW vf AS SELECT name FROM search_presets ORDER BY name COLLATE mycoll", + id="collation", + ), + ], +) +async def test_a_foreign_view_using_an_unloaded_function_or_collation_stops_nothing( + tmp_path: Path, view: str +) -> None: + # Measured on the local SQLite: neither the script, the RENAME COLUMN migration nor the verify + # fails on such a view, so there is no failure for the step test to classify. Reading the view + # fails, as the control below shows, and the open succeeds all the same. + path = tmp_path / "foreign-view.db" + await _fresh(path) + _sql(path, "ALTER TABLE search_presets RENAME COLUMN owner_user_id TO owner") + conn = sqlite3.connect(path) + try: + conn.create_function("f", 1, lambda x: x) + conn.create_collation("mycoll", lambda a, b: (a > b) - (a < b)) + conn.execute(view) + conn.commit() + finally: + conn.close() + # Positive control: without the function or collation loaded, reading the view does fail. + conn = sqlite3.connect(path) + try: + with pytest.raises(sqlite3.OperationalError, match="no such (function|collation)"): + conn.execute("SELECT * FROM vf").fetchall() + finally: + conn.close() + await _fresh(path) + assert "owner_user_id" in _preset_columns(path) diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py new file mode 100644 index 0000000000..f3eb84228f --- /dev/null +++ b/tests/test_server_schema_verify_5062.py @@ -0,0 +1,520 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""BACKLOG #5062: DDL forms the server-DB live schema check misread without raising. + +Each test of a fix failed before it: the reader either built a wrong expected shape or let a form it +cannot place through. The rest are controls that pin what the fixes must not change. A form the reader cannot place now raises ``ValueError``, which the unit +test that reads each shipped batch would surface before an open does. The shipped batches' own +expected shapes are pinned by ``tests/test_sqlserver_postgres_schema_verify_1720.py``. +""" + +from __future__ import annotations + +import pytest + +from messagefoundry.store.server_schema_verify import declared_schema + + +def test_add_column_takes_any_name_as_a_column() -> None: + """After ``ADD COLUMN`` what follows is a column, so a column named like a constraint word, + ``index``, ``period`` or ``exclude``, enters the expected shape rather than being skipped.""" + shape = declared_schema( + ( + "CREATE TABLE t (a INT)", + "ALTER TABLE t ADD COLUMN index TEXT", + "ALTER TABLE t ADD COLUMN IF NOT EXISTS period TEXT", + "ALTER TABLE t ADD COLUMN exclude TEXT NOT NULL", + ), + "postgres", + ) + assert shape.columns["t"] == frozenset({"a", "index", "period", "exclude"}) + assert shape.column_shapes["t"]["exclude"].nullable is False + + +@pytest.mark.parametrize( + ("item", "match"), + [ + ("INDEX ix_t (a)", "inline index"), + ("INDEX ix_t NONCLUSTERED (a)", "inline index"), + ("period INT NULL", "cannot place"), + ("exclude INT NULL", "cannot place"), + ], +) +def test_a_table_item_that_is_an_index_or_could_be_a_column_raises(item: str, match: str) -> None: + with pytest.raises(ValueError, match=match): + declared_schema((f"CREATE TABLE t (a INT NULL, {item})",), "sqlserver") + + +def test_a_constraint_of_the_period_or_exclude_shape_is_still_a_constraint() -> None: + shape = declared_schema(("CREATE TABLE t (a INT, EXCLUDE USING gist (a WITH =))",), "postgres") + assert shape.columns["t"] == frozenset({"a"}) + + +def test_an_add_constraint_does_not_read_on_into_the_next_statement() -> None: + """An ``ADD CONSTRAINT`` with no ``;`` after it used to read on into the next ``ALTER TABLE`` + and take that statement's ``PRIMARY KEY`` columns as its own table's.""" + shape = declared_schema( + ( + "CREATE TABLE a (x INT NOT NULL, id INT NULL)", + "CREATE TABLE b (id INT NOT NULL)", + "IF 1 = 1 ALTER TABLE a ADD CONSTRAINT ck_a CHECK (x > 0)\n" + "ALTER TABLE b ADD CONSTRAINT pk_b PRIMARY KEY (id)", + "IF 1 = 1 ALTER TABLE a ADD CONSTRAINT ck_b CHECK (x < 9)\n" + "UPDATE b SET id = 1 WHERE id = 0", + ), + "sqlserver", + ) + assert shape.column_shapes["a"]["id"].nullable is True + assert shape.column_shapes["b"]["id"].nullable is False + + +def test_a_foreign_key_action_does_not_end_an_add_clause() -> None: + shape = declared_schema( + ( + "CREATE TABLE a (id INT NOT NULL PRIMARY KEY)", + "CREATE TABLE b (x INT NULL)", + "ALTER TABLE b ADD a_id INT NULL REFERENCES a(id) ON DELETE CASCADE ON UPDATE NO ACTION", + ), + "sqlserver", + ) + assert shape.column_shapes["b"]["a_id"].nullable is True + + +def test_a_primary_key_over_a_quoted_name_with_a_space_is_not_null() -> None: + shape = declared_schema(('CREATE TABLE t ("my col" INT, PRIMARY KEY ("my col"))',), "postgres") + assert shape.column_shapes["t"]["my col"].nullable is False + + +def test_a_primary_key_inside_a_check_literal_marks_nothing() -> None: + shape = declared_schema( + ("CREATE TABLE t (a INT, b INT, CHECK (a::text <> 'PRIMARY KEY (b)'))",), "postgres" + ) + assert shape.column_shapes["t"]["b"].nullable is True + + +@pytest.mark.parametrize( + "clause", + [ + "ADD CONSTRAINT pk_t PRIMARY KEY USING INDEX ix_t", + "ADD PRIMARY KEY USING INDEX ix_t", + "ADD CONSTRAINT uq_t UNIQUE USING INDEX ix_t", + ], +) +def test_a_key_built_from_an_existing_index_raises(clause: str) -> None: + with pytest.raises(ValueError, match="existing index"): + declared_schema(("CREATE TABLE t (a INT)", f"ALTER TABLE t {clause}"), "postgres") + + +def test_using_index_tablespace_is_only_a_storage_option() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT)", + "ALTER TABLE t ADD CONSTRAINT pk_t PRIMARY KEY (a) USING INDEX TABLESPACE fast", + ), + "postgres", + ) + assert shape.column_shapes["t"]["a"].nullable is False + + +@pytest.mark.parametrize("key", ["(a::text)", "((a :: varchar(10)))", "CAST(a AS text)"]) +def test_a_key_that_only_casts_a_column_raises(key: str) -> None: + """PostgreSQL stores a cast to the column's own type as the column, so the key may read live + as ``a`` while the reader would say ````.""" + with pytest.raises(ValueError, match="cast"): + declared_schema((f"CREATE INDEX ix ON t ({key})",)) + + +def test_an_expression_around_a_cast_is_still_an_expression() -> None: + shape = declared_schema(("CREATE INDEX ix ON t (lower(a::text))",)) + assert shape.named_indexes["ix"].columns == ("",) + + +def test_a_default_sign_with_nothing_after_it_is_a_value_error() -> None: + with pytest.raises(ValueError, match="default"): + declared_schema(("CREATE TABLE t (a INT DEFAULT -)",), "postgres") + + +@pytest.mark.parametrize("clause", ["ADD COLUMN IF NOT EXISTS", "ADD COLUMN"]) +def test_an_add_with_nothing_to_add_raises(clause: str) -> None: + with pytest.raises(ValueError, match="nothing to add"): + declared_schema(("CREATE TABLE t (a INT)", f"ALTER TABLE t {clause}")) + + +def test_an_alter_index_is_refused_as_what_it_is() -> None: + with pytest.raises(ValueError, match="alter index"): + declared_schema(("ALTER INDEX ix_t SET (fillfactor = 70)",)) + + +def test_collate_database_default_is_the_database_collation() -> None: + shape = declared_schema( + ("CREATE TABLE t (a NVARCHAR(64) COLLATE DATABASE_DEFAULT NOT NULL)",), "sqlserver" + ) + assert shape.column_shapes["t"]["a"].collation is None + + +def test_collate_catalog_default_raises() -> None: + with pytest.raises(ValueError, match="catalog_default"): + declared_schema( + ("CREATE TABLE t (a NVARCHAR(64) COLLATE CATALOG_DEFAULT NOT NULL)",), "sqlserver" + ) + + +def test_a_guarded_drop_of_a_temporary_table_is_not_the_stores() -> None: + shape = declared_schema(("CREATE TABLE t (a INT)", "DROP TABLE IF EXISTS #tmp")) + assert set(shape.columns) == {"t"} + + +def test_a_rename_column_without_to_raises() -> None: + with pytest.raises(ValueError, match="cannot read"): + declared_schema(("CREATE TABLE t (a INT)", "ALTER TABLE t RENAME COLUMN a x b")) + + +def test_a_bracketed_name_with_a_comma_or_a_keyword_is_one_name() -> None: + shape = declared_schema( + ( + "CREATE TABLE t ([a,b] INT NULL, c INT NULL)", + "IF COL_LENGTH('t','end') IS NULL ALTER TABLE t ADD [end] INT NULL", + ), + "sqlserver", + ) + assert shape.columns["t"] == frozenset({"a,b", "c", "end"}) + + +def test_a_second_create_table_raises() -> None: + """A guarded second ``CREATE TABLE`` never runs, so the columns it alone names are never built.""" + with pytest.raises(ValueError, match="second create table"): + declared_schema( + ("CREATE TABLE IF NOT EXISTS t (a INT)", "CREATE TABLE IF NOT EXISTS t (a INT, b INT)") + ) + # After a DROP the table is created again. + shape = declared_schema(("CREATE TABLE t (a INT)", "DROP TABLE t", "CREATE TABLE t (b INT)")) + assert shape.columns["t"] == frozenset({"b"}) + + +@pytest.mark.parametrize( + "index", + [ + "CREATE INDEX ix ON t (lower(b))", + "CREATE INDEX ix ON t (a) WHERE b IS NOT NULL", + "CREATE INDEX ix ON t (a) INCLUDE (b)", + ], +) +def test_a_drop_column_an_opaque_index_may_use_raises(index: str) -> None: + with pytest.raises(ValueError, match="drop column"): + declared_schema(("CREATE TABLE t (a INT, b INT)", index, "ALTER TABLE t DROP COLUMN b")) + + +def test_a_drop_column_an_opaque_index_does_not_name_keeps_the_index() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT, b INT, c INT)", + "CREATE INDEX ix ON t (a) WHERE b IS NOT NULL", + "ALTER TABLE t DROP COLUMN c", + ) + ) + assert "ix" in shape.named_indexes and shape.columns["t"] == frozenset({"a", "b"}) + + +def test_a_legacy_sqlserver_drop_index_names_its_table() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL)", + "CREATE TABLE u (a INT NULL)", + "CREATE INDEX ix ON u (a)", + "DROP INDEX t.ix", + ), + "sqlserver", + ) + assert shape.named_indexes["ix"].table == "u" + gone = declared_schema( + ("CREATE TABLE u (a INT NULL)", "CREATE INDEX ix ON u (a)", "DROP INDEX u.ix"), + "sqlserver", + ) + assert "ix" not in gone.named_indexes + + +@pytest.mark.parametrize( + "statements", + [ + ("CREATE TABLE t (a INT)", "ALTER TABLE t ADD CONSTRAINT nn_a NOT NULL a NOT VALID"), + ("CREATE TABLE t (a INT, CONSTRAINT nn_a NOT NULL a)",), + ("CREATE TABLE t (a INT, NOT NULL a)",), + ], +) +def test_a_not_null_table_constraint_raises(statements: tuple[str, ...]) -> None: + with pytest.raises(ValueError, match="not-null constraint"): + declared_schema(statements, "postgres") + + +# --- review round 1 ------------------------------------------------------------------------------ + + +def test_a_drop_column_after_a_rename_still_sees_the_opaque_index() -> None: + with pytest.raises(ValueError, match="drop column"): + declared_schema( + ( + "CREATE TABLE t (a INT, b INT)", + "CREATE INDEX ix ON t (lower(b))", + "ALTER TABLE t RENAME COLUMN b TO c", + "ALTER TABLE t DROP COLUMN c", + ) + ) + + +def test_a_drop_column_reads_the_predicate_to_its_statement_end_only() -> None: + with pytest.raises(ValueError, match="drop column"): + declared_schema( + ( + "CREATE TABLE t (a INT, b TEXT, c INT)", + "CREATE INDEX ix ON t (a) WHERE b <> ';' AND c IS NULL", + "ALTER TABLE t DROP COLUMN c", + ) + ) + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL, b INT NULL, c INT NULL)" + " CREATE INDEX ix ON t (a) WHERE b > 0 ALTER TABLE t DROP COLUMN c", + ), + "sqlserver", + ) + assert "ix" in shape.named_indexes + + +def test_a_drop_of_an_include_index_key_column_drops_the_index() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT, b INT)", + "CREATE INDEX ix ON t (a) INCLUDE (b)", + "ALTER TABLE t DROP COLUMN a", + ) + ) + assert "ix" not in shape.named_indexes + + +@pytest.mark.parametrize("item", ['CONSTRAINT "nn a" NOT NULL a', "CONSTRAINT [nn a] NOT NULL a"]) +def test_a_not_null_constraint_with_a_quoted_name_raises(item: str) -> None: + with pytest.raises(ValueError, match="not-null constraint"): + declared_schema((f"CREATE TABLE t (a INT, {item})",), "postgres") + + +@pytest.mark.parametrize( + "key", ["((a)::text)", "(a::pg_catalog.text)", '(a::"text")', "(CAST(a AS pg_catalog.text))"] +) +def test_a_key_that_opens_with_a_cast_raises(key: str) -> None: + with pytest.raises(ValueError, match="cast"): + declared_schema((f"CREATE INDEX ix ON t ({key})",)) + + +def test_a_bracketed_filegroup_does_not_hide_the_next_statement() -> None: + shape = declared_schema( + ( + "CREATE TABLE a (x INT NOT NULL)", + "CREATE TABLE b (y INT NULL, z INT NULL)", + "IF 1 = 1 ALTER TABLE a ADD CONSTRAINT pk_a PRIMARY KEY (x) ON [PRIMARY]\n" + "UPDATE b SET z = 1, y = 2", + ), + "sqlserver", + ) + assert shape.column_shapes["a"]["x"].nullable is False + + +@pytest.mark.parametrize("name", ["delete", "update", "insert", "merge", "truncate", "select"]) +def test_add_column_takes_a_data_statement_word_as_the_name(name: str) -> None: + shape = declared_schema( + ("CREATE TABLE t (a INT)", f"ALTER TABLE t ADD COLUMN {name} TEXT"), "postgres" + ) + assert name in shape.columns["t"] + + +def test_a_postgres_column_named_index_is_a_column() -> None: + shape = declared_schema(("CREATE TABLE t (index TEXT, a INT)",), "postgres") + assert shape.columns["t"] == frozenset({"index", "a"}) + + +def test_using_index_inside_a_check_literal_is_text() -> None: + shape = declared_schema(("CREATE TABLE t (a TEXT, CHECK (a <> 'USING INDEX x'))",), "postgres") + assert shape.columns["t"] == frozenset({"a"}) + + +def test_an_unterminated_add_ends_at_an_alter_database() -> None: + shape = declared_schema( + ( + "CREATE TABLE a (x INT NULL)", + "IF 1 = 1 ALTER TABLE a ADD c INT NULL\n" + "ALTER DATABASE CURRENT SET READ_COMMITTED_SNAPSHOT ON", + ), + "sqlserver", + ) + assert shape.column_shapes["a"]["c"].nullable is True + + +# --- review round 2 ------------------------------------------------------------------------------ + + +def test_a_case_in_a_predicate_does_not_end_the_opaque_index_words() -> None: + with pytest.raises(ValueError, match="drop column"): + declared_schema( + ( + "CREATE TABLE t (a INT, b INT, c INT)", + "CREATE INDEX ix ON t (a) WHERE CASE WHEN b > 0 THEN 1 ELSE 0 END = 1" + " AND c IS NULL", + "ALTER TABLE t DROP COLUMN c", + ) + ) + + +@pytest.mark.parametrize("name", ["delete", "update", "insert"]) +def test_a_constraint_named_like_a_data_word_keeps_its_key(name: str) -> None: + shape = declared_schema( + ("CREATE TABLE t (id INT)", f"ALTER TABLE t ADD CONSTRAINT {name} PRIMARY KEY (id)"), + "postgres", + ) + assert shape.column_shapes["t"]["id"].nullable is False + + +def test_using_index_tablespace_on_its_own_line_is_a_storage_option() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT)", + "ALTER TABLE t ADD CONSTRAINT pk_t PRIMARY KEY (a) USING INDEX\n TABLESPACE fast", + ), + "postgres", + ) + assert shape.column_shapes["t"]["a"].nullable is False + + +def test_a_t_sql_if_exists_guard_ends_an_unterminated_add() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL)", + "IF COL_LENGTH('t','y') IS NULL ALTER TABLE t ADD y INT NULL\n" + "IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'ix') CREATE INDEX ix ON t (a)", + ), + "sqlserver", + ) + assert shape.column_shapes["t"]["y"].nullable is True and "ix" in shape.named_indexes + + +def test_a_nested_subscript_is_not_a_bracketed_name() -> None: + shape = declared_schema(("CREATE INDEX ix ON t ((a[b[1]]))",)) + assert shape.named_indexes["ix"].columns == ("",) + + +@pytest.mark.parametrize( + "statement", + ["ALTER TABLE IF EXISTS #t ADD x INT NULL", "CREATE TABLE\n #tmp (x INT NULL)"], +) +def test_a_temporary_table_is_not_the_stores_in_any_spacing(statement: str) -> None: + shape = declared_schema(("CREATE TABLE t (a INT NULL)", statement), "sqlserver") + assert set(shape.columns) == {"t"} + + +@pytest.mark.parametrize("name", ['"x""y"', "nn$a", "[x]]y]"]) +def test_a_not_null_constraint_with_an_escaped_or_dollar_name_raises(name: str) -> None: + with pytest.raises(ValueError, match="not-null constraint"): + declared_schema((f"CREATE TABLE t (a INT, CONSTRAINT {name} NOT NULL a)",), "postgres") + + +# --- review round 3 repair: regressions against main ----------------------------------------------- + + +def test_a_guarded_drop_whose_list_goes_on_past_a_temporary_table_raises() -> None: + with pytest.raises(ValueError, match="cannot read"): + declared_schema(("CREATE TABLE u (a INT NULL)", "DROP TABLE IF EXISTS #tmp, u")) + + +@pytest.mark.parametrize( + ("statement", "partial"), + [ + ("IF COL_LENGTH('t','b') IS NOT NULL EXEC('CREATE INDEX ix ON t (a) WHERE b > 0')", True), + ("EXEC('CREATE INDEX ix ON t (a) INCLUDE (b)')", False), + ("EXEC('CREATE INDEX ix ON t (a) WHERE b <> ''x''')", True), + ], +) +def test_an_opaque_index_inside_an_exec_string_is_read(statement: str, partial: bool) -> None: + shape = declared_schema(("CREATE TABLE t (a INT NULL, b INT NULL)", statement), "sqlserver") + assert shape.named_indexes["ix"].partial is partial + + +@pytest.mark.parametrize("name", ["update", "delete", "insert"]) +def test_a_rename_to_a_data_word_is_read(name: str) -> None: + shape = declared_schema( + ("CREATE TABLE t (a INT)", f"ALTER TABLE t RENAME COLUMN a TO {name}"), "postgres" + ) + assert shape.columns["t"] == frozenset({name}) + + +@pytest.mark.parametrize( + "statement", + ["DROP TABLE IF EXISTS #t$1, u", "DROP TABLE IF EXISTS #a#b, u", "DROP TABLE #tmp, u"], +) +def test_a_drop_list_that_goes_on_past_any_temporary_name_raises(statement: str) -> None: + with pytest.raises(ValueError, match="cannot read"): + declared_schema(("CREATE TABLE u (a INT NULL)", statement)) + + +def test_a_partial_index_in_nested_dynamic_sql_is_read() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL, b NVARCHAR(9) NULL)", + "EXEC('EXEC(''CREATE INDEX ix ON t (a) WHERE b <> ''''x'''''')')", + ), + "sqlserver", + ) + assert shape.named_indexes["ix"].partial + + +# --- Wave 3 assembly repair -------------------------------------------------------------------- + + +def test_an_array_literal_holding_a_bracket_is_not_a_bracketed_name() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a TEXT)", + "EXEC('ALTER TABLE t ADD CONSTRAINT ck CHECK (a <> ARRAY['']''])')", + ), + "postgres", + ) + assert shape.columns["t"] == frozenset({"a"}) + + +@pytest.mark.parametrize("word", ["merge", "delete", "x$delete"]) +def test_a_data_word_in_a_predicate_does_not_end_the_opaque_words(word: str) -> None: + with pytest.raises(ValueError, match="drop column"): + declared_schema( + ( + f"CREATE TABLE t (a INT, {word} INT, c INT)", + f"CREATE INDEX ix ON t (a) WHERE {word} > 0 AND c IS NULL", + "ALTER TABLE t DROP COLUMN c", + ) + ) + + +def test_opaque_words_are_kept_per_table_on_sqlserver() -> None: + """A SQL Server index name is unique only within its table, so a plain ix on u must not hide + the partial ix on t.""" + with pytest.raises(ValueError, match="drop column"): + declared_schema( + ( + "CREATE TABLE t (a INT NULL, c INT NULL)", + "CREATE TABLE u (a INT NULL, c INT NULL)", + "CREATE INDEX ix ON t (a) WHERE c > 0", + "CREATE INDEX ix ON u (a)", + "ALTER TABLE t DROP COLUMN c", + ), + "sqlserver", + ) + + +def test_a_sqlserver_data_statement_ends_an_unterminated_predicate() -> None: + """On SQL Server UPDATE is reserved, so it starts the next statement, whose words are not the + index's.""" + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL, c INT NULL, d INT NULL)", + "CREATE INDEX ix ON t (a) WHERE c > 0\nUPDATE t SET d = 1", + "ALTER TABLE t DROP COLUMN d", + ), + "sqlserver", + ) + assert "ix" in shape.named_indexes diff --git a/tests/test_shape_error_callers_6720.py b/tests/test_shape_error_callers_6720.py index bba8972958..3ee28619de 100644 --- a/tests/test_shape_error_callers_6720.py +++ b/tests/test_shape_error_callers_6720.py @@ -1,36 +1,44 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""BACKLOG #6720: two callers of ``base.is_store_shape_error`` that the widened +"""BACKLOG #6720: callers of ``base.is_store_shape_error`` that the widened ``schema_verify._SHAPE_MESSAGES`` reaches. An expected name held by an object of another kind (a view, an index, a table) now reads as a store -shape error. At least three callers outside the schema step act on that; this file pins these two -(the ``verify-audit-chain`` walk in ``__main__`` is the third, and is not covered here): +shape error. At least these callers outside the schema step act on that, and this file pins them: * ``auth.service._is_revoke_defect``: the post-commit session revoke raises such an error at once, unretried, and records no ``auth.sessions_revoke_failed`` row, as it does for any other defect. * ``store.note_audit_chain_read``: the open no longer tags such an error as row evidence about the audit chain, so it is reported as a store this build cannot read. +* ``audit-verify``'s walk in ``__main__``: such an error raised by ``verify_audit_chain`` is + "could not start", exit 2, rather than the stopped-walk FAIL line and exit 1. Each case is a real SQLite error from every collision ``test_schema_verify_6719_6720`` measures, so the code and the text are SQLite's own and a collision added there is pinned here too. The control -is a -syntax error: the same ``SQLITE_ERROR`` code, but not a shape message, which keeps the old handling. +is a syntax error: the same ``SQLITE_ERROR`` code, but not a shape message, which keeps the old +handling. """ from __future__ import annotations +import contextlib +import io import sqlite3 +from pathlib import Path from typing import Any import pytest +from messagefoundry.__main__ import main from messagefoundry.auth import service as service_module from messagefoundry.auth.passwords import hash_password from messagefoundry.auth.service import SESSIONS_REVOKE_FAILED_ACTION, AuthService from messagefoundry.config.settings import AuthSettings from messagefoundry.store.base import is_store_shape_error +from messagefoundry.store.crypto import generate_key from messagefoundry.store.store import AUDIT_CHAIN_READ_NOTE, MessageStore, note_audit_chain_read +from tests.test_audit_keyless_chain_flagged import _AT_REST_ENV +from tests.test_keyless_chain_every_command import _keyed_chain from tests.test_schema_verify_6719_6720 import _COLLISIONS _PASSWORD = "Str0ng-Synthetic-Pass!!" @@ -142,3 +150,48 @@ def test_a_sqlite_error_that_is_not_a_shape_is_still_tagged() -> None: exc = _not_shape() note_audit_chain_read(exc) assert AUDIT_CHAIN_READ_NOTE in getattr(exc, "__notes__", ()) + + +# --- audit-verify's walk --------------------------------------------------------------------------- + + +def _audit_verify_with_a_walk_raising( + exc: Exception, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> tuple[int, str, str]: + """``audit-verify`` against a real keyed chain whose walk raises ``exc``. Returns the exit code, + stdout and stderr.""" + monkeypatch.chdir(tmp_path) + for name in _AT_REST_ENV: + monkeypatch.delenv(name, raising=False) + key = generate_key() + db = tmp_path / "keyed.db" + _keyed_chain(db, key) + monkeypatch.setenv("MEFOR_STORE_ENCRYPTION_KEY", key) + + async def raising(self: MessageStore, **kwargs: object) -> object: + raise exc + + monkeypatch.setattr(MessageStore, "verify_audit_chain", raising) + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + rc = main(["audit-verify", "--db", str(db)]) + return rc, out.getvalue(), err.getvalue() + + +@pytest.mark.parametrize(("existing", "step"), _COLLISIONS) +def test_a_name_held_by_another_kind_of_object_stops_audit_verify_as_could_not_start( + existing: str, step: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + exc = _sqlite_error("CREATE TABLE other (a TEXT)", existing, step) + rc, out, err = _audit_verify_with_a_walk_raising(exc, tmp_path, monkeypatch) + assert rc == 2, (out, err) + assert "cannot open the store" in err, err + assert not out.startswith("FAIL: "), out + + +def test_a_sqlite_error_that_is_not_a_shape_still_stops_audit_verify_with_a_fail_line( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + rc, out, err = _audit_verify_with_a_walk_raising(_not_shape(), tmp_path, monkeypatch) + assert rc == 1, (out, err) + assert out.startswith("FAIL: the audit chain check stopped part way"), out diff --git a/tests/test_stage_dispatcher.py b/tests/test_stage_dispatcher.py index a0746c80bf..ebd258eb9a 100644 --- a/tests/test_stage_dispatcher.py +++ b/tests/test_stage_dispatcher.py @@ -1887,7 +1887,8 @@ async def _stand_in_for_sweep(d: StageDispatcher, lane: str) -> None: sweep these tests disable. The caller has already established the stranding; this counts it, caps it, and makes it loud. - Shared by `_wait_lane` (phase targets) and `_wait_lane_until` (work predicates) so the cap has ONE + Shared by `_wait_lane` (phase targets), `_wait_lane_until` (work predicates) and + `_drive_lanes_to_stop` (test 8's multi-lane drive) so the cap has ONE definition. The cap is a property of the LANE's contention rate, not of the call site: two separate budgets would let one test spend it twice and still read as within the allowance. """ @@ -2335,10 +2336,61 @@ async def test_adr0070_7_reload_resumes_idempotently(store: Any) -> None: await d.stop() -async def test_adr0070_8_correlated_outage_single_reload_rearms_all(store: Any) -> None: - """ADR 0070 test 8: N lanes STOP under one (store-down-style) root cause; each emits its own - connection_stopped (ADR-0044 durable dedup collapses them to one operator signal downstream), and a - SINGLE ``notify_work`` reload broadcast re-arms ALL of them with the streak reset.""" +async def _drive_lanes_to_stop( + d: StageDispatcher, mc: ManualClock, lanes: list[str], *, timeout: float = 20.0 +) -> None: + """Fire every due park timer until each of ``lanes`` is STOPPED, bounded by real time. + + The loop this replaced ran 30 rounds and never re-readied a lane, and it failed on the SQL + Server 2025 leg (BACKLOG #3456). The three captured logs read for this show one pattern: all + four lanes fault once, and only ``IB_OUTAGE_3`` faults again. A lane parked after its first fault + whose re-claim comes back EMPTY takes T12: ``phase=IDLE`` with no timer. The sweep that would + re-ready it is disabled here, so no clock advance re-claims it. That fits what `_wait_lane` + stands in for (a swallowed 1222). The logs do not show it as the cause: the dispatcher's + lock-timeout line is INFO and was not captured. So a stranded lane is re-readied under the + same capped, warned allowance, and the loop's bound is a wall-clock ceiling, not a round count. + A stranding before any contention route is recorded (a lock-timeout abort or a head skip) + still fails here, as it failed the old loop, and names that route as unrecorded. The counters + are dispatcher-wide, so a later stranding is excused by any earlier counted one. A stand-in + waits until no lane is CLAIMING or PROCESSING, so the re-claim does not race a sibling's + claim or re-pend, which is where this test's own lanes contend. + """ + + def all_stopped() -> bool: + return all(d.phase(ln) is _LanePhase.STOPPED for ln in lanes) + + busy = (_LanePhase.CLAIMING, _LanePhase.PROCESSING) + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while loop.time() < deadline: + if all_stopped(): + return + quiet = not any(d.phase(ln) in busy for ln in lanes) + for ln in lanes: + # IDLE is never a waypoint on this path (PARKED -> READY -> CLAIMING -> PROCESSING -> + # PARKED or STOPPED), so an IDLE lane with no timer is a stranding. + if quiet and _terminal_idle(d, ln): + if d.claim_lock_timeouts + d.claim_head_skips == 0: + raise _WaitTimeout( + f"{ln} stranded in terminal IDLE with no contention recorded\n" + + await _expiry_report(lane=ln) + ) + await _stand_in_for_sweep(d, ln) + mc.advance(120.0) # past every lane's capped backoff, so every armed park timer fires + await _settle(rounds=4) + if all_stopped(): + return + phases = {ln: d.phase(ln) for ln in lanes} + first = next(ln for ln in lanes if d.phase(ln) is not _LanePhase.STOPPED) + raise _WaitTimeout( + f"not every lane STOPPED within {timeout:g}s: {phases!r}\n" + + await _expiry_report(all_stopped, lane=first) + ) + + +async def _correlated_outage_rearms_all(store: Any, *, abort_second_claim: bool) -> None: + """The body of ADR 0070 test 8. ``abort_second_claim`` aborts the claim that follows the + first fault on a store lock timeout, the shape SQL Server returns on a 1222.""" mc = ManualClock(1000.0) stub = RecordingStub(store, mc.time) stub.set_policy(_always_raise) # the shared root cause: every lane's handoff raises @@ -2346,22 +2398,28 @@ async def test_adr0070_8_correlated_outage_single_reload_rearms_all(store: Any) lanes = [f"IB_OUTAGE_{i}" for i in range(4)] for lane in lanes: await _seed(store, lane, [100.0]) - d = _make(store, stub, set(), clock=mc, alert_sink=alert, infra_fault_stop_after=2) + shim: _ClaimShim | None = None + if abort_second_claim: + shim = _ClaimShim( + store, lanes[0], mode="lock_timeout_once", extra_lanes=frozenset(lanes[1:]), times=0 + ) # armed by hand below + d = _make(shim or store, stub, set(), clock=mc, alert_sink=alert, infra_fault_stop_after=2) await d.start() try: for lane in lanes: d.mark_ready(lane) - # Drive every lane to STOP (stop_after=2 → two faults each). GENEROUSLY bounded, not a fixed - # round count: the slow SQL Server 2025 async needs more advance/settle rounds than - # SQLite/SS-2022 to march all four lanes through both faults + the STOP latch. Each round fires - # the (due) park timers and settles; once a lane STOPs it stays STOPPED, so the loop just needs - # enough rounds for the slowest lane — 30 is far past the ~2 a fast backend takes. - for _ in range(30): - if all(d.phase(ln) == _LanePhase.STOPPED for ln in lanes): - break - mc.advance(120.0) # past every lane's capped backoff → fire all park timers - await _settle(rounds=20) - assert all(d.phase(ln) == _LanePhase.STOPPED for ln in lanes) + if shim is not None: + for lane in lanes: + await _wait_lane(d, lane, _LanePhase.PARKED) # each lane's first fault + shim._remaining = 1 + # Drive every lane to STOP (stop_after=2 gives two faults each). + await _drive_lanes_to_stop(d, mc, lanes) + if shim is not None: + assert shim._remaining == 0, "the armed abort never reached a claim" + assert d.claim_lock_timeouts >= 1 + assert any(_sweep_standins(ln) for ln in lanes), ( + "the abort stranded no lane, so this arm did not exercise the stand-in" + ) # Each stopped lane emitted its own connection_stopped (the dedup is downstream, ADR 0044). assert {name for name, _ in alert.stopped} == set(lanes) @@ -2382,6 +2440,26 @@ async def test_adr0070_8_correlated_outage_single_reload_rearms_all(store: Any) await d.stop() +async def test_adr0070_8_correlated_outage_single_reload_rearms_all(store: Any) -> None: + """ADR 0070 test 8: N lanes STOP under one (store-down-style) root cause; each emits its own + connection_stopped (ADR-0044 durable dedup collapses them to one operator signal downstream), and a + SINGLE ``notify_work`` reload broadcast re-arms ALL of them with the streak reset.""" + await _correlated_outage_rearms_all(store, abort_second_claim=False) + + +@pytest.mark.parametrize("store", ["sqlite"], indirect=True) +async def test_the_outage_drive_stands_in_for_an_aborted_reclaim(store: Any) -> None: + """The pin for `_drive_lanes_to_stop`, not an ADR 0070 guarantee: the test harness's stand-in, + not the dispatcher, re-claims the stranded lanes, because the sweep is disabled. Test 8's body + with the claim after every lane's first fault aborted on a lock timeout. The 30-round loop it + replaced fails this arm, because nothing re-claims a stranded lane. + + SQLite only: the abort is injected, so a server backend adds nothing but its own contention, + which could spend a lane's single stand-in a second time.""" + with pytest.warns(UserWarning, match="sweep stand-in"): + await _correlated_outage_rearms_all(store, abort_second_claim=True) + + async def test_adr0070_9_content_retry_is_not_an_infra_fault(store: Any) -> None: """ADR 0070 test 9 (sharp edge 2 — the discriminator): a repeated CONTENT retry (the body ``mark_failed``s its head — a message-content re-pend, ``i==0`` / ``made_progress=False``) must NOT diff --git a/tests/test_store_privilege_check.py b/tests/test_store_privilege_check.py index ce0f1acb07..ba9890ec36 100644 --- a/tests/test_store_privilege_check.py +++ b/tests/test_store_privilege_check.py @@ -631,6 +631,65 @@ def test_cli_json_reports_every_family_and_no_secret( assert by_hop["smtp"]["state"] == "not_probed" +#: ESC, DEL, a C1 control (CSI), RIGHT-TO-LEFT OVERRIDE and LINE SEPARATOR. ``json.dumps`` always +#: escapes ESC; it escapes the other four only under ``ensure_ascii``, so ``--json`` output must +#: carry each as a ``\uXXXX`` escape (BACKLOG #2891, PR 2390 note 3). +_HOSTILE = "a\x1b[31mb\x7fc\x9bd\u202ee\u2028f" + + +def _assert_escaped(out: str) -> None: + """``out`` is ASCII, and every character in it but a newline is printable. ``str.splitlines`` + would drop U+2028 as a line break, so the check splits on nothing. With the caller's check + that ``out`` decodes back to :data:`_HOSTILE`, that proves each of its characters was written + as an escape.""" + raw = [ch for ch in out if ch != chr(10) and not (ch.isascii() and ch.isprintable())] + assert not raw, f"--json output carries a raw character: {out!r}" + + +def test_the_escape_assertion_fails_on_unescaped_json() -> None: + """The control for :func:`_assert_escaped`: output written without ``ensure_ascii`` fails it, + and so does output that leaves only U+2028 raw, which ``json.loads`` accepts.""" + with pytest.raises(AssertionError, match="carries a raw character"): + _assert_escaped(json.dumps({"error": _HOSTILE}, ensure_ascii=False)) + escaped_ls, raw_ls = chr(92) + "u2028", chr(0x2028) + only_line_separator_raw = json.dumps({"error": _HOSTILE}).replace(escaped_ls, raw_ls) + assert json.loads(only_line_separator_raw) == {"error": _HOSTILE} + with pytest.raises(AssertionError, match="carries a raw character"): + _assert_escaped(only_line_separator_raw) + _assert_escaped(json.dumps({"error": _HOSTILE}, indent=2)) + + +def test_cli_json_result_escapes_controls_and_bidi_in_a_detail( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _clear_env(monkeypatch) + report = dataclasses.replace( + _unobservable_report(), backend=StoreBackend.POSTGRES, detail=_HOSTILE + ) + _stub_probe(monkeypatch, report) + argv = ["check-privileges", "--service-config", str(_server_toml(tmp_path)), "--json"] + code = main(argv) + out = capsys.readouterr().out # read first, so a failing assert never echoes it raw + _assert_escaped(out) + assert code == EXIT_UNOBSERVABLE + store = next(h for h in json.loads(out)["hops"] if h["hop"] == "store") + assert _HOSTILE in store["detail"] + + +def test_cli_json_error_escapes_controls_and_bidi_in_the_message( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _clear_env(monkeypatch) + monkeypatch.setattr( + "messagefoundry.__main__._load_service_settings", lambda *a, **k: (None, _HOSTILE) + ) + code = main(["check-privileges", "--service-config", "unused.toml", "--json"]) + out = capsys.readouterr().out + _assert_escaped(out) + assert code == EXIT_SETTINGS + assert json.loads(out) == {"error": _HOSTILE} + + def test_cli_says_serve_would_refuse_an_over_grant_under_enforce( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: diff --git a/tests/test_tcp_x12_handler_failure.py b/tests/test_tcp_x12_handler_failure.py index 7d7a021597..989f80271e 100644 --- a/tests/test_tcp_x12_handler_failure.py +++ b/tests/test_tcp_x12_handler_failure.py @@ -391,6 +391,11 @@ async def handler(raw: bytes) -> str: assert "framing_error" not in _kinds(events), name sent = b"".join(writer.written) assert b"MSA|AA|C1|note ?" in sent, name + # BACKLOG #5799 item 1: the altered reply is recorded as an event, not only in the warn-once + # log line. Red on the code before: no `reply_replaced` in the events. + replaced = [e for e in events if e[0] == "reply_replaced"] + assert len(replaced) == 1, name + assert str(replaced[0][2]).startswith("1 reply(ies) since the last report"), name async def test_an_x12_reply_in_an_unusable_charset_name_is_sent_in_utf8( @@ -478,7 +483,8 @@ async def narrow_reply(raw: bytes) -> str: events = await _drive(source, _ThenEof(EDI * 2), writer, handler=narrow_reply) assert seen == [EDI] * 2 assert writer.written == [b"synthetic reply ?"] * 2 - assert _kinds(events) == ["established", "closed"] + # One `reply_replaced` for both altered replies: the event is throttled (BACKLOG #5799 item 1). + assert _kinds(events) == ["established", "reply_replaced", "closed"] assert_capture_sees(caplog, "messagefoundry.transports.x12") assert not [r for r in caplog.records if r.levelno >= logging.ERROR] diff --git a/tests/test_worktree_remove_in_use.py b/tests/test_worktree_remove_in_use.py index 7ee4c56a75..9ca6681966 100644 --- a/tests/test_worktree_remove_in_use.py +++ b/tests/test_worktree_remove_in_use.py @@ -795,3 +795,26 @@ def test_a_directory_git_leaves_behind_is_reported_and_exits_non_zero(rig: Rig) assert proc.returncode != 0, _out(proc) assert "the directory is still there" in _out(proc), _out(proc) assert "Removed worktree" not in _out(proc), _out(proc) + + +def test_a_removal_that_cannot_be_confirmed_gone_is_not_reported_clean(rig: Rig) -> None: + """Vault BACKLOG #2985, added item 1, its end-state part. After git removes the tree, the run + checks the directory is CONFIRMED gone: a not-found under a folder this user may not list is not + a removal. Red with the rule before engine PR 3027 (Test-PresentOrThrow) put back: it read that + not-found as gone and said "Removed". The folder holding the tree is denied listing; git still + removes the tree by name.""" + wt = rig.add(rig.primary.parent / "box" / "Repo-unlisted") + + with _denied_listing(rig, wt.parent) as probe: + proc = rig.run("-Path", str(wt)) + assert not wt.exists(), _explain(wt.parent, probe, proc) + assert proc.returncode != 0, _explain(wt.parent, probe, proc) + assert "could not be confirmed gone" in _out(proc), _explain(wt.parent, probe, proc) + assert "Removed worktree" not in _out(proc), _explain(wt.parent, probe, proc) + + # Control: the same layout, with listing allowed, is a clean removal. + other = rig.add(rig.primary.parent / "box" / "Repo-listed") + proc = rig.run("-Path", str(other)) + assert proc.returncode == 0, _out(proc) + assert "Removed worktree" in _out(proc), _out(proc) + assert not other.exists() diff --git a/tests/test_x12_parsing.py b/tests/test_x12_parsing.py index eb7ab0d88d..9e7007beef 100644 --- a/tests/test_x12_parsing.py +++ b/tests/test_x12_parsing.py @@ -387,8 +387,9 @@ def test_split_keeps_the_whitespace_terminator_of_a_malformed_interchange_cut_at # Three trailers that close the frame at once, two of them not a clean IEA. Any segment opening with -# IEA closes it (BACKLOG #5807 keeps that rule): the reader cannot see a connection end, so a frame -# it held there would be dropped with no row. +# IEA closes it: the reader cannot see a connection end, so a frame it held there would be dropped +# with no row. BACKLOG #5807 asks for a separator check after IEA, which would break these; a build +# of it was reverted in PR 3031, and the row is open. _TRAILERS_THAT_CLOSE = [ pytest.param("IEA1*000000001~", id="dropped-separator"), pytest.param("IEAX*1~", id="longer-id"), diff --git a/tests/tooling_manifest.txt b/tests/tooling_manifest.txt index 4f17921f43..6894ab8cb7 100644 --- a/tests/tooling_manifest.txt +++ b/tests/tooling_manifest.txt @@ -23,6 +23,7 @@ # tests/test_tooling_partition.py pins this file against the tree and fails if a new non-engine test # lands in neither this list nor its explicit stay-list. tests/test_adr0071_crossing_count.py +tests/test_adr_0019_0173_revert_guard.py tests/test_adr_index_coverage.py tests/test_afk_decision_log.py tests/test_afk_digest.py