diff --git a/changelog.d/5512.security.md b/changelog.d/5512.security.md new file mode 100644 index 0000000000..1f9eb49f67 --- /dev/null +++ b/changelog.d/5512.security.md @@ -0,0 +1,17 @@ +- **An empty host no longer counts as loopback on the cleartext, revocation and trust-anchor + checks.** The shared on-box check read `""` as this machine, so in the shipped code a hop with an + unset host would have skipped those checks while its real destination was unknown. Each caller + now says what an empty host means. A blank HTTP listener host binds `127.0.0.1`, so the + peer-control gate reads it as on-box. A log forwarder with no host has no hop to judge. The + log-forwarding and key-share checks still count a blank value as this host. A generic ODBC + `server`, and the `server` of the SQL Server preset (`Database`, `DatabasePoll`, + `DatabaseLookup`, `DatabaseRef`), that names no host is refused at every posture, and neither + `tls_hop_attested` nor `cleartext_accepted` crosses it. A preset `server` of `None`, as a + `DatabaseRef` can carry, is refused too, and is never sent as the host `None`. At least a blank + value, a bare `:port`, `[]`, an empty entry beside a comma, and a host made only of brackets, + colons and digits that is neither all digits nor an IPv6 literal, such as `[,]` or `:1433:`, + name no host. A plain number, bare or before a port (`1433`, `[1433]`, `12:34`), and the IPv6 + literals `::` and `[::]` are accepted. A protocol prefix with nothing after it, such as `tcp:`, + is not caught. The same values are refused at load in a SQL Server + `[store].server`, and a value of spaces in a PostgreSQL one. An empty PostgreSQL `server` still loads, and that hop is judged off-box. + (`BACKLOG #5512`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5dc226a7e9..79aa5c68ab 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -192,7 +192,7 @@ backend-limited. | `vault_revocation_attested_reason` | str | — | **required** with `vault_revocation_attested = true`: what covers revocation of the store Vault's certificate, for example its short lifetime, and of an `https://` proxy's in front of it. The flag without it, a blank one, one holding a control character or a lone surrogate, or a reason without the flag is refused at load. It is printed in the loosening report and the serve-time warning, so put no secret in it. Env: `MEFOR_STORE_VAULT_REVOCATION_ATTESTED_REASON` | | `require_encryption` | bool | `false` | keeps the keyless refusal in force past the audited opt-out. It does not create that refusal, which is the default; [PHI.md](PHI.md#3-encryption-at-rest) §3 states the rule and the opt-out. It encrypts nothing itself, so a key is still needed. | | `allow_unencrypted_phi` | | | **→ moved to `[security].allow_unencrypted_phi`** (ADR 0118) — set it there; no longer accepted in `[store]`. | -| `server`, `port` | str/int | — / 1433 | server DBs (required for `sqlserver`) | +| `server`, `port` | str/int | — / 1433 | server DBs (required for `sqlserver`, where at least a blank value, a bare `:1433`, `[]`, an empty entry beside a comma, and a host made only of brackets, colons and digits that is neither all digits nor an IPv6 literal (such as `[,]` or `:1433:`) are refused at load, while a plain number such as `1433` or `12:34`, `::` and `[::]` are accepted, and a protocol prefix with no host, such as `tcp:`, is not caught; on `postgres` a value of spaces is refused, and an empty one reads as `PGHOST`, then asyncpg's local default, with the hop judged off-box) | | `database` | str | — | server DBs (required for `sqlserver`) | | `auth` | enum | `sql` | `sql` · `integrated` · `entra` (SQL Server). `integrated` connects `Trusted_Connection=yes` — the **service account's** Windows identity authenticates (no SQL password); the turnkey **gMSA** walkthrough (grant the gMSA a SQL login + run the service under it) is [`DEPLOY-SERVER-DB.md` §1.1](DEPLOY-SERVER-DB.md). | | `username` | str | — | server DBs (required when `auth = sql`) | diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 308cace66e..bf2572b083 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -2193,6 +2193,12 @@ host. `DatabasePoll`, which takes only [its allowlist](#the-generic-driver-allowlist). `DatabaseLookup` and `DatabaseRef` take only a Microsoft driver. - `server` must hold no comma, since the preset adds its own `,`. Put the port in `port`. +- `server` must name a host (BACKLOG #5512), at every posture, and neither `tls_hop_attested` + nor `cleartext_accepted` crosses the refusal, since the preset would send `SERVER=,` and + the driver would pick its own destination. A `server` of `None`, which a `DatabaseRef` can carry, + is refused the same way and is never sent as the host `None`. What counts as naming no host is + stated once, in the `server` row of the generic dialect's [*Values*](#values-on-the-generic-dialect) + table, and the preset reads the same spellings. - `server` must hold no `\`. The preset always sends a port, so an instance name there is not what the driver dials; a driver that reads the instance in place of the port, as FreeTDS does, would dial a port the check never compared. Set `port` to the instance's port. @@ -2441,7 +2447,7 @@ built, and the error names the setting and never the value: | `database`, `username`, every `odbc_params` value (`PORT` and `SSLmode` included) | plain, `SSLmode=verify-full` | printable ASCII; none of `;`, `{`, `}`, `=`, `"`, `'`; not empty or blank; no leading or trailing space. An `odbc_params` value of `None` is refused, never sent as the text `None`; leave the keyword out instead. An `odbc_params` value of `true` or `false` is refused, never sent as the text `True` or `False`; write the driver's own spelling as a string. An unset `database` or `username` is left out of the string | | `SSLmode`, in any case of the keyword | plain | for MySQL Connector/ODBC under its registered name, exactly one of `DISABLED`, `PREFERRED`, `REQUIRED`, `VERIFY_CA`, `VERIFY_IDENTITY`, in upper case; refused on Microsoft's `ODBC Driver for SQL Server`, which reads `Encrypt` instead; for psqlODBC, exactly one of `disable`, `allow`, `prefer`, `require`, `verify-ca`, `verify-full`, in lower case. See [*The `SSLmode` spelling*](#the-sslmode-spelling) | | `odbc_driver` | braced, `DRIVER={PostgreSQL Unicode}` | printable ASCII, and none of `;`, `{`, `}` | -| `server` | plain | printable ASCII, and none of `;`, `{`, `}`, `=`, `"`, `'`; `None` is refused | +| `server` | plain | printable ASCII, and none of `;`, `{`, `}`, `=`, `"`, `'`; `None` is refused, and so is at least a blank value, a bare `:port`, `[]`, an empty entry on either side of a comma, and a host made only of brackets, colons and digits that is neither all digits nor an IPv6 literal (such as `[,]` or `:1433:`), whatever the posture, `tls_hop_attested` or `cleartext_accepted`. A plain number (`1433`, `[1433]`) or digits-only host with a port (`12:34`), and the IPv6 literals `::` and `[::]`, are accepted. The SQL Server preset (`Database`, `DatabasePoll`, `DatabaseLookup`, `DatabaseRef`) refuses the same spellings the same way, except that a value holding a comma meets the preset's own comma refusal first. A protocol prefix with no host after it, such as `tcp:`, is not caught | | `password` | braced, with the `}}` escape | printable ASCII. See below | Why no braces. On 2026-10-30, the engine's braced strings were measured against real drivers. @@ -4247,7 +4253,7 @@ that carries no recognized credential crosses in three ways that do not claim th | | claim | disposition | |---|---|---| -| the hop is **on-box** (loopback / `localhost` / empty host) | not a network exposure | ALLOW | +| the hop is **on-box** (loopback / `localhost`; an empty host is not on-box) | not a network exposure | ALLOW | | `cleartext_accepted = true` + `cleartext_reason` | this hop is **not** secure, and we accept that | **WARN** — crossed, loudly logged **and recorded at every construction** | | `[security].enforcement = warn` | the instance-wide refuse/warn dial is at `warn` | WARN — but **only for the raw transports** (`MLLP()`, `Tcp()`, `X12()`, `DICOM()`, `Email()`, `Ftp()`). The HTTP family (`Rest()`, `Soap()`, `FHIR()`, `DICOMweb()`, `FhirLookup()`) shipped these refusals unconditionally, and ADR 0092 decision 5 forbids a cell getting weaker, so a no-loosen floor turns that WARN back into a REFUSE there. The dial is **not** a substitute for the declaration | diff --git a/docs/adr/0092-posture-keyed-transport-hop-refusal-refuse-the-insecure-phi-hop.md b/docs/adr/0092-posture-keyed-transport-hop-refusal-refuse-the-insecure-phi-hop.md index 97baea46b0..cb8c5bc1bc 100644 --- a/docs/adr/0092-posture-keyed-transport-hop-refusal-refuse-the-insecure-phi-hop.md +++ b/docs/adr/0092-posture-keyed-transport-hop-refusal-refuse-the-insecure-phi-hop.md @@ -58,7 +58,7 @@ secure hop (a proxy-terminated / trusted-segment hop) that replaces reliance on A thin `enforce_insecure_hop(disp, *, message, cell, audit_sink)` acts on the decision: raise `InsecureHopRefused` (a `ValueError`, so it surfaces as a config-load / `build_check` error) on REFUSE; loud-log **+ audit** on WARN; no-op on ALLOW. `transports/rest._is_loopback_egress_host` is **hoisted** to -`tls_policy.is_loopback_hop_host` (literal `127.0.0.0/8`, `::1`, `localhost`, empty host) so the HTTP-egress +`tls_policy.is_loopback_hop_host` (literal `127.0.0.0/8`, `::1`, `localhost`; BACKLOG #5512 removed the empty host) so the HTTP-egress cell and the authority share **one** definition; it **never resolves DNS** — an unprovable name is REMOTE (fail-closed), so a hostname can't smuggle an off-box hop past the on-box carve-out. 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 fd3979a9d4..f5f5c9d932 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 @@ -533,7 +533,7 @@ Do not restate it as one. §6 names what would flip it. one keyed on a single host: it puts one leg on loopback and the other off-box, both ways round, and asserts that the off-box leg's own cell refuses. The WARN arm also sees both legs, one warning each. `::test_an_oidc_leg_with_no_host_is_refused_not_treated_as_loopback` pins that a leg whose - host cannot be read is refused, since the guard would otherwise treat an empty host as loopback. + host cannot be read is refused, whatever the posture. **AC-4 WAS PARTIAL UNTIL 2026-09-23, AND THE OIDC LEGS ARE NOW BUILT (BACKLOG #1887).** Under #1498 it covered two hops of the three, and this notice said the OIDC token and JWKS legs were not built. diff --git a/docs/adr/README.md b/docs/adr/README.md index 70b832b7b9..d0c4623f5c 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -130,7 +130,7 @@ what is withheld and what you can request. | [0094](0094-granular-expiry-only-tls-relaxation.md) | Granular expiry-only TLS relaxation per connection (BACKLOG #129) — a per-connection opt-in `tls_allow_expired` (default off = byte-identical) that honours a partner **server cert whose validity period has lapsed** while STILL validating the chain's signatures + hostname + EKU; at least the intermediates' and the trust anchor's validity periods, and a CRL's own window, go unchecked too (CORRECTED 2026-11-03, BACKLOG #5089: this said the chain was still validated, unqualified). It replaces the blunt MITM-able `tls_verify=false` for the narrow expired-cert case. Mechanism: OR OpenSSL's `X509_V_FLAG_NO_CHECK_TIME` (`0x200000`, stable public constant; not a named `ssl.VerifyFlags` member but `verify_flags` accepts the raw int) onto an already-**verifying** context via the shared `config/tls_policy.py:relax_verify_expiry(ctx, *, host)` — a guarded no-op on `CERT_NONE`, logs a PHI-free construction WARN. Threaded on the **verify path only** through `_mllp_ssl_context` / `_ftps_ssl_context` / `_client_ssl_context` (DICOM-SCU) + the urllib HTTP family (`_expiry_relaxed_opener` in rest.py, reused by soap.py incl. mTLS + fhir.py); factories `MLLP`/`Rest`/`FHIR`/`Soap`/`DICOM`/`Ftp` expose it, `connections.toml` carries it as a plain setting. NEVER disables verification, so it composes with (never weakens) the fail-closed no-CA / `tls_verify=false` / [ADR 0092](0092-posture-keyed-transport-hop-refusal-refuse-the-insecure-phi-hop.md) cleartext/verify-off refusals — an expiry-relaxed hop stays a *verified* hop, so the #200 refusal never keys on it. Chose the context-level OpenSSL flag over post-handshake `cryptography.x509.verification` `.time()` pinning (available but needs `CERT_NONE`-then-reverify, only cleanly reachable for asyncio MLLP — not ftplib/pynetdicom/urllib). Trade-off: relaxes both validity bounds (a not-yet-valid cert is also accepted); WARN fires at construction, not per accepted cert. Extends [ADR 0002](0002-phase2-transport-security-and-strong-auth.md)/[ADR 0092](0092-posture-keyed-transport-hop-refusal-refuse-the-insecure-phi-hop.md)/[ADR 0093](0093-pinned-internal-ca-trust-anchor.md) | Accepted (2026-07-12) — built (#129) | | [0095](0095-connection-lifecycle-scheduler-and-credential-fault-stop.md) | Connection lifecycle seam: active-window scheduler (BACKLOG #147) + credential-fault lane stop (BACKLOG #109) — one seam in `RegistryRunner`/`stage_dispatcher`, two behaviours, both reusing the EXISTING per-connection start/stop path. **#147**: a declarative pydantic `Schedule` (`config/models.py`) = a list of `ActiveWindow`s (`datetime.weekday()` day-set + local `start`/`end` time-of-day + IANA `timezone`, default UTC) + an `invert` flag (availability windows UP-inside vs maintenance windows DOWN-inside); same-day span `[start,end)`, `start>end` wraps past midnight anchored on the start weekday, `start==end` rejected. `schedule=None` = always-on, byte-identical (no task). The runner spawns ONE cooperatively-cancellable asyncio scheduler task per scheduled connection that every `schedule_tick_seconds` reconciles live listen/deliver state against the calendar via the SAME `start_inbound`/`stop_inbound` (or `start_outbound`/`stop_outbound`) the API uses — an inbound park unbinds the listener (workers keep draining), an outbound park PAUSEs delivery RETAINING queued rows; clock INJECTABLE (`schedule_clock`, mirrors dry-run `ingest_time`). Threaded code-first AND connections.toml. **#109**: a permanent auth failure is marked `credential_fault` (FTP login-refused / SFTP auth-failed sites only — NOT operation-level `error_perm`/no-such-dir) on `_RemoteError`→`NegativeAckError`; under `credential_fault_policy="stop"` (default) `_process_delivery_item` STOPs the lane IMMEDIATELY (reusing the ADR 0070/InternalErrorPolicy STOP muscle + `connection_stopped` alert) and RETAINS the claimed row UN-ERRORED via `store.release_claimed` (back to PENDING, no backoff/last_error) — no dead-letter of the backlog, no re-auth storm that could lock out the partner account; `"dead_letter"` keeps the historical fail-fast. A content-permanent reject (AR/CR) still dead-letters just that one message; a transient fault still retries. Distinct stop-reason logging keeps schedule-park vs credential-stop vs content-STOP legible. No channel element (§1); reliability + count-and-log invariants preserved by reusing proven machinery | Accepted (2026-07-12) — both built — Amended 2026-09-29 (Amendment A, BACKLOG #2083, batch 178): a third permanent-fault class, the configuration fault (`config_fault`: a refused FTP greeting, `AUTH TLS` or `PBSZ`/`PROT P`, or a TLS demand at a plain-FTP login), STOPs the lane and retains the queue under the same `credential_fault_policy`; the credential fault narrows to a refused login, and a 5xx naming a connection limit is transient, while a 4xx login refusal naming the credential now becomes a credential fault; AC-5 now excludes both classes and AC-6 is added. Also records the scheduler holds: an operator-required STOP, a DR-filtered connection and a latched #122 log halt are left alone, and a reload replaces every scheduler task — Amended 2026-10-04 (Amendment B, BACKLOG #2323, batch 191): an HTTP Digest challenge the engine refuses at send time is a configuration fault too, code `auth-challenge-refused`, on the REST, SOAP, FHIR and DICOMweb destinations — Amended 2026-10-11 (B.1, BACKLOG #2989, batch 250): the owner kept the lane stop (R4); a challenge with no realm or nonce or an unsupported `qop`, and the token hop's refusal, raise the same fault; a send-time hop refusal is a configuration fault, code `insecure-hop-refused`; a truncated or misframed 2xx reply follows the over-cap rule, codes `reply-truncated` and `reply-misframed` — Amended 2026-11-14 (B.1, BACKLOG #2989 item 11): an OAuth2 or SMART token hop whose `https://` token endpoint meets a web proxy set up for Digest is refused when it is built, and the send-time `CONNECT` 407 match is removed — Amended 2026-11-17 (B.1, BACKLOG #2989 items 20 and 21): on some REST and FHIR outbounds that refusal runs before the proxy credential's hop is judged — Amended 2026-11-18 (B.2, BACKLOG #5910, PR 3069): an OAuth2 or SMART token endpoint's coded 2xx reply, as B.2 scopes it, is a configuration fault, code `token-reply-coded`, so the class now covers the endpoint a connection names as well as its settings | | [0096](0096-cluster-leader-preference-and-non-promotable-standby.md) | Cluster leader preference & non-promotable standby (BACKLOG #101) — two per-node `[cluster]` knobs evaluated in the **expired-lease branch** of `_claim_or_renew_lease` (both `pipeline/cluster.py` Postgres + `pipeline/cluster_sqlserver.py`): **`acquire_delay_seconds`** handicaps ONLY take-over of an EXPIRED lease (`lease_expires_at + delay < DB_now` — the delay is on the *expiry side*, a strictly stricter predicate → claim LATER never earlier → **no two-leader window**; the `owner = me` renew branch is never delayed), and **`promotable = false`** short-circuits to not-held BEFORE the DB (never inserts/takes-over/renews, so a warm DR node can never become or remain leader; a somehow-already-leader node steps down cleanly on its next tick, fence as backstop). Governs take-over of an EXPIRED lease only (routine transitions); the empty-table first election stays a plain race (use `promotable`/operator ordering for cold bring-up). Surfaced per-node in `GET /cluster/nodes` (additive `nodes.acquire_delay_seconds`/`promotable` columns, `ADD COLUMN IF NOT EXISTS`/`COL_LENGTH` migrations). Default `(0.0, True)` = behaviourally byte-identical. **Rider:** a `ServiceSettings` cross-section guard REFUSES `[dr].enabled` or `[dr].activate` + `[cluster].enabled` (the DR run-profile gates connections, not lease acquisition — the warm-DR posture is a non-promotable cluster member, not a lease-contending `[dr]` box). At least one promotable node required (all-non-promotable = no leader, documented). Preserves the self-fencing lease + at-least-once + FIFO invariants. Builds on Workstream A2; relates [ADR 0048](0048-third-tier-disaster-recovery-standby.md) | Accepted (2026-07-12) — built (#101) | -| [0092](0092-posture-keyed-transport-hop-refusal-refuse-the-insecure-phi-hop.md) | Posture-keyed transport-hop refusal — refuse the insecure PHI hop (BACKLOG #200) — one **pure authority** (`config/tls_policy.py`) every insecure-egress cell consumes so all decide identically: `HopDisposition` + `insecure_hop_disposition(*, is_phi, production, is_loopback_hop, hop_attested, audited_opt_out)` with explicit early-return precedence (loopback→ALLOW; attested→ALLOW; synthetic→ALLOW; audited-opt-out→WARN; production→REFUSE; else non-prod-PHI→WARN) + thin `enforce_insecure_hop` (raise `InsecureHopRefused`/loud-log+audit/no-op). `_is_loopback_egress_host` hoisted to `is_loopback_hop_host` (literal `127.0.0.0/8`/`::1`/`localhost`/empty — **never DNS**; unprovable = remote/fail-closed). **Escape clamp:** `MEFOR_ALLOW_INSECURE_TLS` may only downgrade REFUSE→WARN on **non-prod** — it can NEVER satisfy a prod-PHI hop (behaviour change). **Per-hop attestation:** load-validated per-connection `tls_hop_attested` (+ reason), audited when it suppresses a prod refusal, replacing the blunt global escape for prod. **Layering:** construction-time gate (ENFORCED at `messagefoundry check`/dry-run/reload via `active_hop_posture` stamping) + a zero-I/O send-time assertion at the byte-crossing. **No-loosen:** keeps REFUSE for both staging AND prod PHI on cells that already refuse. Posture threaded from `[ai]` (declared, not strictest-by-default) through `Engine`→`RegistryRunner`→`build_check_registry`. Deferred: API request-time PHI-read hop guard (`require_secure_hop`; #906 start-gate covers meanwhile). Extends ADR 0083/0078/0002 §4 | Accepted (2026-07-11) — owner-ratified; CORE authority built (#200), transport cells follow | +| [0092](0092-posture-keyed-transport-hop-refusal-refuse-the-insecure-phi-hop.md) | Posture-keyed transport-hop refusal — refuse the insecure PHI hop (BACKLOG #200) — one **pure authority** (`config/tls_policy.py`) every insecure-egress cell consumes so all decide identically: `HopDisposition` + `insecure_hop_disposition(*, is_phi, production, is_loopback_hop, hop_attested, audited_opt_out)` with explicit early-return precedence (loopback→ALLOW; attested→ALLOW; synthetic→ALLOW; audited-opt-out→WARN; production→REFUSE; else non-prod-PHI→WARN) + thin `enforce_insecure_hop` (raise `InsecureHopRefused`/loud-log+audit/no-op). `_is_loopback_egress_host` hoisted to `is_loopback_hop_host` (literal `127.0.0.0/8`/`::1`/`localhost`, and since BACKLOG #5512 not the empty host — **never DNS**; unprovable = remote). **Escape clamp:** `MEFOR_ALLOW_INSECURE_TLS` may only downgrade REFUSE→WARN on **non-prod** — it can NEVER satisfy a prod-PHI hop (behaviour change). **Per-hop attestation:** load-validated per-connection `tls_hop_attested` (+ reason), audited when it suppresses a prod refusal, replacing the blunt global escape for prod. **Layering:** construction-time gate (ENFORCED at `messagefoundry check`/dry-run/reload via `active_hop_posture` stamping) + a zero-I/O send-time assertion at the byte-crossing. **No-loosen:** keeps REFUSE for both staging AND prod PHI on cells that already refuse. Posture threaded from `[ai]` (declared, not strictest-by-default) through `Engine`→`RegistryRunner`→`build_check_registry`. Deferred: API request-time PHI-read hop guard (`require_secure_hop`; #906 start-gate covers meanwhile). Extends ADR 0083/0078/0002 §4 | Accepted (2026-07-11) — owner-ratified; CORE authority built (#200), transport cells follow | | [0098](0098-store-side-scaling-levers-are-exhausted-transaction-amortization-is-the-only-path-to-45m-day.md) | **Four store-side scaling levers are measured dead ends** (the filename's "transaction amortization is the only path" title is WITHDRAWN as an over-read — see the H1 banner). Records the C5/C6/C7 rig outcome: **C5** per-shard ceiling `R ∈ [2,3)` < the 3.62/shard a cleared N=16 would need → **N-sizing insufficient alone** (decisive; engine peaked 59.7% max_core, load-gen 8.5%, so the co-constraint carve-out did not fire); **C6** convoy floor met in **0 of 288 samples**, max suspended group 2, max chain depth 1 → **no lock/latch/grant/spill CONVOY** (**CAUTION:** the detector is blind by construction to non-shared per-query costs — "no convoy" ≠ "nothing there"); **C7** DB-scoped `MAXDOP=1` made the collapse worse AND degraded a healthy rung → **parallelism is LOAD-BEARING**. Purely NEGATIVE: it closes four options and **endorses no lever**. The "therefore txn/event is the path" step was an **elimination inference** and is explicitly disclaimed. **CAUTION:** C4-derived numbers carry a rig caveat (C4 ran 16 shards on 8 vCPU and handed back **no artifacts**) | Accepted (2026-07-12) — closes options; authorizes no build | | [0099](0099-phase-4-group-commit-amortize-the-per-event-transaction-cost.md) | **Phase 4 reconciled: group-commit WITHDRAWN; the surviving lever gated behind a measurement** (filename title superseded by the H1). Resolves a **nine-day contradiction in the ledger**: [ADR 0055](0055-group-commit-durable-write.md) (2026-06-29) authorized a group-commit build as "a no-regret lever" while [ADR 0069](0069-durable-write-throughput-lever.md) (2026-07-03) measured that **durable-write is NOT the throughput wall** — and 0055 was never withdrawn. **Decision:** 0055 **SUPERSEDED** (its premise is measured false — the commit tier is ~9% utilised at ~2,416 c/s against a ~27–29k c/s ceiling — and delayed durability **breaks at-least-once on PHI**: ACK-before-log-flush = an ACKed message that does not exist); 0069 **RATIFIED**; [ADR 0057](0057-inline-step-a-fast-path.md) inline stage-fusion is the surviving mechanism — **already shipping in the tree and never once enabled in a rig run** — and is **gated behind a pre-registered P0 measurement** (ADR 0101) whose first job is to measure **`txn/s`, a number this programme has never counted**. Key code fact: `list_fifo_lanes` (~47.5% of N=16 store CPU) is **CLOCK-driven** (`_sweep_loop` on `pooled_sweep_interval`=0.25 s), so **no txn-reduction lever can touch it**. Counterexample kept on the table: pooled commits FEWER txns than `per_lane` and is ~2.8× slower | Accepted (2026-07-12) for the withdrawal + gate; the fusion build stays Proposed/unfunded until P0 clears | | [0101](0101-pre-registered-falsifier-discipline-for-performance-measurement.md) | **Pre-registered falsifier discipline for performance measurement** — moves into version control the method that finally worked, after this project **published and retracted two performance results** (status doc §5, "Why the measurement programme kept failing"). Every perf investigation informing a build decision SHALL be pre-registered as a falsifier: (1) a decision rule fixed **before** the run; (2) a stated **null band** — and a null is a SUCCESSFUL run; (3) a **manipulation check** (a failed one is VOID, not a null); (4) a **same-session control** (never a historical baseline — the N=8 slope is run-to-run variable +4…+13); (5) a mechanism named **ONLY by a convoy**, never by rank/share/growth; (6) a **matched PASS control** + the anti-adjacency guard (`WRITELOG` is rank-1 on the 100%-delivered *healthy* arm — the cleanest proof that rank ≠ cause); (7) **reproduce before claiming**. Plus binding instrument rules: gate on `result` never `exit_code`; apply the benign-exclusion set + capture fence; **never** quote `ceiling.sustained_events_per_s` from a collapsed arm; pin the engine build; RAW ≠ PUBLISHABLE (D4 0.5 derate). Five instances of one error class across four authors motivated it — C2 (retracted), C4 (WITHHELD), C5's handback, C5's reviewer, C7's hypothesis | Accepted (2026-07-12) — in force since C4; this ADR records it | diff --git a/messagefoundry/__main__.py b/messagefoundry/__main__.py index e19d366552..28736e7203 100644 --- a/messagefoundry/__main__.py +++ b/messagefoundry/__main__.py @@ -14877,7 +14877,7 @@ def _warn_on_an_unrevoked_store_hop(settings: ServiceSettings) -> None: context = _verifying_context(store) except (ValueError, OSError): return - _refuse_store_revocation(host=store.server or "", posture=posture, context=context) + _refuse_store_revocation(host=store.server, posture=posture, context=context) async def _open_store_or_refuse(opening: Awaitable[Store]) -> Store: diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 7cfbd752f7..d1c5726bbb 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -113,7 +113,7 @@ is_canonical_ipv4, upn_suffix_key, ) -from messagefoundry.hostlist import allow_entry_problem, parse_allow_entry +from messagefoundry.hostlist import allow_entry_problem, names_no_host, parse_allow_entry from messagefoundry.logging_setup import LOG_LEVELS # Moved to netaddr, the neutral leaf, so the HTTP listener reads them without importing private @@ -1233,6 +1233,16 @@ def _require_server_db_fields(self) -> StoreSettings: missing.append("username") # SQL login needs a user (+ MEFOR_STORE_PASSWORD) if missing: raise ValueError(f"{label} backend requires: " + ", ".join(missing)) + # BACKLOG #5512. No hop guard reads a SQL Server store's host, so one that names none + # would reach the driver as `SERVER=,1433`. On Postgres only spaces are refused: the + # `server` row of docs/CONFIGURATION.md says what an empty value means there. + server = self.server or "" # `missing` above already refused None + if self.backend is StoreBackend.SQLSERVER: + unnamed = names_no_host(server) + else: + unnamed = bool(server) and not server.strip() + if unnamed: + raise ValueError(f"[store].server names no host: name the {label} host") return self @field_validator("ssl_root_cert") @@ -5150,11 +5160,12 @@ def _names_this_host(host: str) -> bool: """Whether ``host`` is loopback or the unspecified address, for the #1966 gate. Stricter than :func:`is_loopback_hop_host`, which fails toward "remote" because it guards a CLEARTEXT hop, where "remote" is the cautious answer. Here "remote" is the permissive one, so ``0.0.0.0``, - ``::``, ``localhost.`` and the IPv4 shorthand ``127.1`` must all count as this host. No DNS. + ``::``, ``localhost.`` and the IPv4 shorthand ``127.1`` must all count as this host, and so must + a value that trims to nothing, which names no other system (BACKLOG #5512). No DNS. The host's own name and its own non-loopback addresses are :func:`_is_own_name_or_address`.""" h = _bare_host(host) - if is_loopback_hop_host(h) or h == "localhost" or h.endswith(".localhost"): + if not h or is_loopback_hop_host(h) or h.endswith(".localhost"): return True addr = _host_ip_literal(h) return addr is not None and (addr.is_loopback or addr.is_unspecified) @@ -5431,7 +5442,8 @@ def forward_hop_disposition(log: LoggingSettings, posture: HopPosture) -> HopDis the SAME authority the transports consume — so the forwarder decides identically to every other egress cell. A hop is treated as **secure** (and never gated) only when it is TLS *with verification on*; plaintext ``udp``/``tcp`` and the ``forward_tls_verify=false`` opt-out are both - MITM-able and go to the gradient: + MITM-able and go to the gradient. A forwarder with no host returns ALLOW before any of this: + ``serve`` builds none without a host, so there is no hop to judge (BACKLOG #5512). #. loopback collector → ALLOW — the ADR 0080 "point ``tcp``/``udp`` at ``127.0.0.1`` and let a local rsyslog/Vector agent add TLS" deployment is explicitly preserved, byte-identical. @@ -5451,15 +5463,16 @@ def forward_hop_disposition(log: LoggingSettings, posture: HopPosture) -> HopDis instance carrying patient data there is no instance left for it to fire on, so it is gone. A ``[logging]`` sibling of ``cleartext_accepted`` remains the recorded follow-up and is now the only way this cell could express an acceptance.""" + if not log.forward_host: + # An unconfigured forwarder: `serve` builds none without a host, so there is no hop to + # refuse. Said here because the shared predicate no longer reads "" as loopback (#5512). + return HopDisposition.ALLOW if log.forward_protocol is SyslogProtocol.TLS and log.forward_tls_verify: # Verified, CA-anchored TLS (ADR 0080) — an encrypted+authenticated hop, nothing to gate. return HopDisposition.ALLOW return insecure_hop_disposition( enforcing=posture.enforcing, - # An unset forward_host cannot happen with forwarding on (the validator requires it), and the - # empty string is treated as loopback by the shared predicate — so an unconfigured forwarder - # can never be refused. - is_loopback_hop=is_loopback_hop_host(log.forward_host or ""), + is_loopback_hop=is_loopback_hop_host(log.forward_host), hop_attested=log.forward_hop_attested, # The global escape keeps its arm HERE (same scope carve-out): it is the only expressible # relaxation this non-connection cell has. Clamped upstream to non-enforcing, so under ENFORCE @@ -5537,7 +5550,7 @@ def pinned_host_port(entry: str) -> tuple[str, int] | None: number = int(port) # A '%' is refused: urlsplit keeps an IPv6 zone ID still encoded, and urllib decodes it before # it dials, so `[::1%31]` would compare as one host here and be dialled as `::11`. - if not host or "%" in host or not 1 <= number <= 65535 or not is_loopback_hop_host(host): + if "%" in host or not 1 <= number <= 65535 or not is_loopback_hop_host(host): return None try: address = ipaddress.ip_address(host) diff --git a/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index 85236be0f0..3a5017ef5d 100644 --- a/messagefoundry/config/tls_policy.py +++ b/messagefoundry/config/tls_policy.py @@ -2313,9 +2313,9 @@ def _is_forward_secret(cipher: Mapping[str, object]) -> bool: # it carry PHI? is it production?) so every cell decides identically, and a legitimately-secure hop is # opted in per-connection (an AUDITED attestation) rather than via the blunt global escape. -#: Host tokens that name the local box (loopback) with no DNS resolution. ``""`` (empty host) is -#: treated as loopback (an on-box bind with no host component). -_LOOPBACK_HOP_HOST_NAMES = frozenset({"localhost", ""}) +#: Host names that name the local box (loopback) with no DNS resolution. The empty host is not one +#: (BACKLOG #5512): :func:`is_loopback_hop_host` says why. +_LOOPBACK_HOP_HOST_NAMES = frozenset({"localhost"}) class HopDisposition(enum.Enum): @@ -2426,27 +2426,34 @@ def is_loopback_hop_host(host: str) -> bool: this authority agree on exactly one definition. Covers all of ``127.0.0.0/8`` and ``::1`` via :mod:`ipaddress` (not just the literal - ``127.0.0.1``), plus the ``localhost`` name and an empty host. It **never resolves DNS**: any other - name cannot be *proven* loopback, so it is treated as remote, which fails closed at the cleartext - guards — a name that happens to resolve to a loopback address is still refused, because + ``127.0.0.1``), plus the ``localhost`` name. It **never resolves DNS**: any other + name cannot be *proven* loopback, so it is treated as remote and gets no on-box carve-out. A + name that happens to resolve to a loopback address is judged as any off-box hop is, because resolution is attacker-influenceable and would let a hostname smuggle an off-box hop past the - on-box carve-out. + carve-out. Judged off-box means the caller's gate applies: an enforcing instance refuses unless + a per-hop declaration covers the hop, and some transports only warn at + ``[security].enforcement = warn``. It does not mean always refused. + + **An empty host is not loopback (BACKLOG #5512).** It names no destination, so this predicate + cannot place it, and what it means belongs to the caller. A listener whose blank host binds a + local default reads that default before it asks. A feature with no host has no hop and returns + before it asks. A caller that cannot say where the hop goes lets this answer stand, so the hop + is judged off-box, as above. **A limit (vault BACKLOG #2706): apart from case, a name is read as written, and a host is an - address only where :mod:`ipaddress` reads it as one.** So at least ``localhost.``, ``127.0.0.1.`` - and ``%6cocalhost`` read as remote here, though a resolver may take the first two as this box, - and urllib decodes the third to ``localhost`` before it dials. The cleartext guards judge them - as they judge any remote hop, and a proxy that applies takes them with the connection's proxy - credential, so a hop spelled this way can leave the box through a proxy. This limit only ever - reads a spelling as remote, so it adds no hop to the ones judged on-box. Where remote is the + address only where :mod:`ipaddress` reads it as one.** So at least ``localhost.``, ``127.0.0.1.``, + ``[::1]`` and ``%6cocalhost`` read as remote here, though a resolver may take the first two as + this box, the Windows resolver takes ``[::1]`` as ``::1`` (measured on Windows 11, BACKLOG + #5512), and urllib decodes the last to ``localhost`` before it dials. The cleartext guards judge + them as they judge any remote hop, and a proxy that applies takes them with the connection's + proxy credential, so a hop spelled this way can leave the box through a proxy. This limit only + ever reads a spelling as remote, so it adds no hop to the ones judged on-box. Where remote is the permissive answer this reading is not enough, as ``config.settings._names_this_host`` records. ``transports.rest._proxy_bypasses`` strips a trailing dot and this does not, so a ``proxy_no_proxy`` entry ``localhost`` matches ``localhost.``, which still reads as remote here. The two disagree only toward "remote": that match opens no on-box carve-out, and - ``transports.rest.ProxyConfig.for_host`` says what it does to the route. A plain - ``rstrip(".")`` is not the fix, because the host of ``http://./x`` is ``.``, and stripping it - leaves the empty host, which reads as loopback.""" + ``transports.rest.ProxyConfig.for_host`` says what it does to the route.""" h = host.lower() if h in _LOOPBACK_HOP_HOST_NAMES: return True @@ -2465,11 +2472,10 @@ def hop_url_host(url: str, *, cell: str) -> str: Vault hop guard in ``transports.strict_requests`` reads its address another way on purpose: with the parser that requests dials by. - Each caller keys an on-box carve-out on :func:`is_loopback_hop_host`, which reads ``""`` as - loopback, and at least one caller elsewhere relies on that. So a site that wrote - ``hostname or ""`` let the one hop it cannot classify cross as on-box. What such a URL dials is - not knowable here: an empty host can resolve to this box's own network addresses rather than to - loopback. So the remedy is the URL, and no posture, attestation or acceptance crosses this. + Each caller keys an on-box carve-out on :func:`is_loopback_hop_host`. What a URL with no host + dials is not knowable here: an empty host can resolve to this box's own network addresses + rather than to loopback. So the remedy is the URL, and no posture, attestation or acceptance + crosses this, where the predicate alone would only judge the hop as remote (BACKLOG #5512). A plain ``ValueError`` and not :class:`InsecureHopRefused`: the token-endpoint and Digest seams re-raise that type with posture advice ("attest the hop", "declare cleartext_accepted") that @@ -3603,10 +3609,9 @@ def vault_client_verify_kwargs( # A malformed bracketed host, or an address that names no host (BACKLOG #2207). Not # raised here: the client build refuses a given address it cannot read as one URL, with # fixed text and the provider's own error type (BACKLOG #2317). An unset address does - # not reach here from a provider, which refuses it first (BACKLOG #2851). NOT "": - # is_loopback_hop_host("") is True, and a host this function cannot read must not count - # as on-box. - host = "(unreadable host)" + # not reach here from a provider, which refuses it first (BACKLOG #2851). The empty host + # is not on-box (BACKLOG #5512), so the anchor keeps what an off-box hop gets. + host = "" anchor = resolve_trust_anchor(connection_ca_file=ca_file, host=host, policy=TrustAnchorPolicy()) verify = requests_verify_from_anchor(anchor, cell=cell) return {} if verify is None else {"verify": verify} diff --git a/messagefoundry/hostlist.py b/messagefoundry/hostlist.py index 51e776f46d..32e3c812b9 100644 --- a/messagefoundry/hostlist.py +++ b/messagefoundry/hostlist.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """A ``host[:port]`` allowlist entry: how one is read, and how a host and a port compare against it -(BACKLOG #5915). +(BACKLOG #5915), and the reading of a database ``server`` that names no host (BACKLOG #5512). One parse serves both sides of the rule. :mod:`messagefoundry.transports.egress` matches with it, and :mod:`messagefoundry.config.settings` refuses at load every entry it cannot read, so an entry @@ -23,9 +23,11 @@ "HostKey", "allow_entry_problem", "canonical_host", + "names_no_host", "parse_allow_entry", "port_number", "port_or_zero", + "split_generic_server", ] #: A host as the allowlist compares it: an IP literal as an address, a name lowercased. @@ -190,3 +192,58 @@ def allow_entry_problem(entry: str) -> str | None: if port and not port_or_zero(port): return "its port is not a number from 1 to 65535" return None + + +def split_generic_server(server: str) -> tuple[str, str]: + """Split a generic-dialect ``server`` into its host and the text after a port separator, which + is ``""`` when it carries none and is not necessarily a port (:func:`port_or_zero` decides). + + ``host:port`` and ``[v6]:port`` are split. A bare IPv6 literal carries more than one colon and + is left whole. A comma is NOT split on (BACKLOG #4874): libpq reads a comma in a host as a list + of hosts, so the text before it need not be the only host dialled. Each caller deals with a + comma before it gets here: the egress reading refuses it, and ``generic_hop_endpoint`` in + :mod:`messagefoundry.transports.db_endpoint` reads it as its docstring says.""" + host = server.strip() + in_server = "" + if host.startswith("["): # a bracketed IPv6 literal, optionally followed by ":port" + close = host.find("]") + if close != -1: + host, rest = host[1:close], host[close + 1 :] + in_server = rest[1:] if rest.startswith(":") else "" + elif host.count(":") == 1: # "host:port" — a bare IPv6 literal carries more than one colon + host, _, in_server = host.partition(":") + return host.strip(), in_server.strip() + + +_ONLY_PUNCTUATION_AND_DIGITS = frozenset("[]:0123456789") + + +def _entry_names_no_host(entry: str) -> bool: + host = split_generic_server(entry)[0] + if not host: + return True + # Text made only of brackets, colons and digits is a host only as an IPv6 literal or a plain + # number, so `[`, `]` and `:1433:` name none. `::1` and `fe80::1` are literals and stay. + if not set(host) <= _ONLY_PUNCTUATION_AND_DIGITS or host.isdigit(): + return False + try: + ipaddress.IPv6Address(host) + except ValueError: + return True + return False + + +def names_no_host(server: str) -> bool: + """Whether ``server`` names no host (BACKLOG #5512): it is blank, or an entry on either side + of a comma is. An entry names none when it is empty, a bare port such as ``:1433``, empty + brackets such as ``[]`` or ``[]:1433``, or a host (the text before a ``:port``, brackets + removed) made only of brackets, colons and digits that is neither all digits nor an IPv6 literal, + such as ``[``, ``]`` or ``:1433:``. A driver has to pick such a destination itself, so no + reading here can place the hop. + + **At least these are accepted.** A plain number, bare, bracketed or before a port, such as + ``1433``, ``[1433]``, ``1:2`` or ``12:34``, reads as a digits-only host name. ``::`` and ``[::]`` + are IPv6 literals. A single colon reads as ``host:port``, so a protocol prefix + with nothing after it, such as ``tcp:``, counts as naming the host ``tcp``. Other text that is + no host name is not judged either.""" + return any(_entry_names_no_host(entry) for entry in server.split(",")) diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index 45070a4da3..d836a3bcd5 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -312,7 +312,7 @@ from messagefoundry.transports.egress import warn_url_query_credentials_before_build from messagefoundry.transports.fhir import FhirLookupExecutor from messagefoundry.transports.framing import FRAMING_CODE, MULTIPLE_MESSAGES_CODE -from messagefoundry.transports.http_listener import reply_seconds +from messagefoundry.transports.http_listener import DEFAULT_BIND_HOST, reply_seconds from messagefoundry.transports.mllp import build_ack from messagefoundry.transports.receipt import IngressReceipt, RefusalKind, receipt_handler @@ -16422,10 +16422,11 @@ def check_http_intake_auth(source: Source, name: str, *, posture: HopPosture | N """ if source.type is not ConnectorType.HTTP: return - host = str(source.settings.get("host", "127.0.0.1")) - # CIDR-aware, and it treats an empty host as loopback — which matches HttpSource's own - # `s.get("host") or "127.0.0.1"` fallback. Reused rather than minting another _LOOPBACK_HOSTS - # frozenset; the tree already carries five same-named copies across two distinct contents. + # A blank host binds HttpSource's own default, so the gate judges that address: the shared + # predicate does not take "" as loopback (BACKLOG #5512). + host = str(source.settings.get("host", DEFAULT_BIND_HOST)) or DEFAULT_BIND_HOST + # CIDR-aware. Reused rather than minting another _LOOPBACK_HOSTS frozenset; the tree already + # carries five same-named copies across two distinct contents. if is_loopback_hop_host(host): return if _has_effective_peer_control(source.settings): diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 285d23c039..b4b770340c 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -1784,8 +1784,6 @@ def _build_ssl(settings: StoreSettings, *, posture: HopPosture | None = None) -> # verifying store hop unless revocation is really checked on it. Byte-identical when the posture is # unstamped / non-prod / loopback / CRL-checked; composes with (never loosens) the weakened-TLS # refusal above, which fires first. - # settings.server is str | None; an empty host reads as loopback (is_loopback_hop_host) → ALLOW, so a - # missing server (a Postgres config that would fail elsewhere) never trips the revocation refusal. ctx = _verifying_context_at_open(settings) # The guard runs LAST and takes the FINISHED context, which is the whole point of `context=`: an # ssl_crl_file that really loaded sets VERIFY_CRL_CHECK_LEAF on the context, and the guard reads @@ -1793,7 +1791,7 @@ def _build_ssl(settings: StoreSettings, *, posture: HopPosture | None = None) -> # same builder (`_per_connection_ssl_connect`). With ssl_crl_file set it either sets the flag or # raises; unset, it leaves the flag clear. Either way the verdict reached here holds for every # connection the pool opens. - _refuse_store_revocation(host=settings.server or "", posture=posture, context=ctx) + _refuse_store_revocation(host=settings.server, posture=posture, context=ctx) return ctx @@ -2017,7 +2015,7 @@ async def connect(*args: Any, **kwargs: Any) -> Any: def _refuse_store_revocation( - *, host: str, posture: HopPosture | None, context: ssl.SSLContext | None = None + *, host: str | None, posture: HopPosture | None, context: ssl.SSLContext | None = None ) -> None: """Refuse a VERIFYING engine->store TLS hop that does no certificate revocation checking (#201). @@ -2058,7 +2056,10 @@ def _refuse_store_revocation( returned ``True`` and passed ``None`` here, because asyncpg built that context and a CRL had nowhere to load.""" RevocationHopGuard.capture( - host=host, + # An empty server is legal here (docs/CONFIGURATION.md, the `server` row), but the guard + # cannot place it, so it judges the hop off-box (BACKLOG #5512). The stand-in names the + # setting. + host=host or "(no [store].server)", cell="[store] Postgres TLS (verified TLS, no revocation check)", description=( "carries the PHI message store over verified TLS but performs no certificate revocation " diff --git a/messagefoundry/transports/bounded_read.py b/messagefoundry/transports/bounded_read.py index 634e32bce9..2b6de5c882 100644 --- a/messagefoundry/transports/bounded_read.py +++ b/messagefoundry/transports/bounded_read.py @@ -838,8 +838,8 @@ def is_never_proxied_host(host: str | None) -> bool: :class:`LoopbackDirectProxyHandler`. Pass the host as ``urlsplit(url).hostname`` gives it, which is how the guards read it. A missing - or empty host is not on the box. The shared predicate reads ``""`` as loopback, but the guards - refuse a URL that names no host before they ask it (``transports.rest._hop_guard_host``). + or empty host is not on the box, and the guards refuse a URL that names no host before they ask + (``transports.rest._hop_guard_host``). """ if not host: return False diff --git a/messagefoundry/transports/database.py b/messagefoundry/transports/database.py index 25634c95ae..bb29204bc7 100644 --- a/messagefoundry/transports/database.py +++ b/messagefoundry/transports/database.py @@ -108,6 +108,7 @@ from messagefoundry.config.wiring import _is_text_codec from messagefoundry.connection_names import db_lookup_record_name, inbound_record_name from messagefoundry.controlchars import has_control_char +from messagefoundry.hostlist import names_no_host from messagefoundry.keywrap import KeyWrapRefused, refuse_weak_key_wrap from messagefoundry.odbc_call_gate import ( CallGate, @@ -263,7 +264,8 @@ def _build_dsn( It refuses settings under which the driver might not read ``SERVER={server},{port}`` as one host and its port (:func:`~messagefoundry.transports.db_endpoint.sqlserver_preset_refusal`, - BACKLOG #4873). + BACKLOG #4873), and a ``server`` that :func:`~messagefoundry.hostlist.names_no_host` reads, + whatever the posture or declaration (BACKLOG #5512). Quoting and the TLS tail: :mod:`messagefoundry.odbc_dsn` (BACKLOG #3714). It sends no ``ServerCertificate`` pin. A weakened TLS posture is **refused** (:func:`_weakened_tls_permitted`, @@ -283,9 +285,23 @@ def _build_dsn( actually refuses a write is the privilege of the account this DSN dials, which only the operator can set (``docs/CONNECTIONS.md``, BACKLOG #1574).""" where = hop_name_prefix(connection) + # BACKLOG #5512: `str(None)` is the host name `None`, which no check below reads as unnamed, + # and the DatabaseRef path has no required-setting check ahead of this build. + if s.get("server", "") is None: + raise InsecureHopRefused( + f"{where}DATABASE server names no host; name the host to connect to" + ) refusal = sqlserver_preset_refusal(s) if refusal is not None: raise ValueError(f"{where}DATABASE {refusal}") + # BACKLOG #5512: after the preset's refusals, so a value holding a comma keeps their remedy, + # and before the weakened-TLS check, at every posture, as on the generic dialect. `,{port}` is + # added to whatever `server` holds, so one that names no host reaches the driver as + # `SERVER=,1433`. No declaration speaks for a hop with no named destination. + if names_no_host(str(s.get("server", ""))): + raise InsecureHopRefused( + f"{where}DATABASE server names no host; name the host to connect to" + ) encrypt = bool_setting(s, "encrypt", default=True) trust = bool(s.get("trust_server_certificate", False)) if (trust or not encrypt) and not _weakened_tls_permitted(attested=attested): @@ -1994,7 +2010,9 @@ def _build_odbc_dsn(s: dict[str, Any], *, connection: str | None = None) -> str: Every value must be printable ASCII (STORE-5 injection guard). ``database``, ``username`` and every ``odbc_params`` value are sent WITHOUT braces (:func:`_odbc_literal`, BACKLOG #2705), so they refuse at least ``;``, ``{``, ``}``, ``=``, a quote, an empty or blank value and a leading - or trailing space. ``server`` and every ``odbc_params`` value also refuse ``None``, an + or trailing space. ``server`` and every ``odbc_params`` value also refuse ``None``, a ``server`` + that :func:`~messagefoundry.hostlist.names_no_host` reads is refused whatever the + posture or declaration (BACKLOG #5512), an ``odbc_params`` value refuses a boolean, and ``sslmode`` takes only the spellings :func:`_refuse_unread_sslmode` accepts for the driver. ``odbc_driver`` is braced and refuses ``;``, ``{`` and ``}``, and must be on the generic driver allowlist. ``password`` is @@ -2030,6 +2048,12 @@ def _build_odbc_dsn(s: dict[str, Any], *, connection: str | None = None) -> str: f"{where}DATABASE server must not contain ';', '{{', '}}', '=', a quote, a control " "character or a non-ASCII character (ODBC injection risk)" ) + # BACKLOG #5512: here and not in the cleartext guard, which stands down on a TLS mode. Neither + # tls_hop_attested nor cleartext_accepted can speak for a hop with no named destination. + if names_no_host(server): + raise InsecureHopRefused( + f"{where}DATABASE server names no host; name the host to connect to" + ) # The driver name stays braced: names hold spaces and parentheses, and no probe found a driver # manager that reads a braced DRIVER wrongly. The delimiters are still refused, not escaped. _refuse_unsafe_text(driver, what="odbc_driver", connection=connection, refused=";{}") @@ -2249,7 +2273,9 @@ def _build_connection( meant "this hop is safe" — it means "this preset's TLS keywords are not what governs it". The generic arm's own refusal is :func:`generic_cleartext_hop_guard`, called by the connectors beside this dispatcher rather than from inside it, so a direct DSN-shape caller (tests, checks) still gets - a string back without a hop decision it did not ask for. + a string back without a hop decision it did not ask for. The exception is a generic ``server`` + that :func:`~messagefoundry.hostlist.names_no_host` matches, which + :func:`_build_odbc_dsn` refuses at every posture (BACKLOG #5512). ``connection`` names the declaring connection in that WARNING (#333); it is used on the generic path only, since the SQL Server preset refuses rather than warns.""" diff --git a/messagefoundry/transports/db_endpoint.py b/messagefoundry/transports/db_endpoint.py index 0506a52a25..f333cac963 100644 --- a/messagefoundry/transports/db_endpoint.py +++ b/messagefoundry/transports/db_endpoint.py @@ -26,7 +26,7 @@ from types import MappingProxyType from typing import Any, NamedTuple -from messagefoundry.hostlist import port_or_zero +from messagefoundry.hostlist import port_or_zero, split_generic_server #: The port the SQL Server preset's connection string uses when ``port`` is not set. SQLSERVER_DEFAULT_PORT = 1433 @@ -68,35 +68,14 @@ def _preset_port(value: object) -> int | None: return port if 1 <= port <= 65535 else None -def split_generic_server(server: str) -> tuple[str, str]: - """Split a generic-dialect ``server`` into its host and the text after a port separator, which - is ``""`` when it carries none and is not necessarily a port (:func:`port_or_zero` decides). - - ``host:port`` and ``[v6]:port`` are split. A bare IPv6 literal carries more than one colon and - is left whole. A comma is NOT split on (BACKLOG #4874): libpq reads a comma in a host as a list - of hosts, so the text before it need not be the only host dialled. Both callers deal with a - comma before they get here: the egress reading refuses it, and :func:`generic_hop_endpoint` - reads it as its docstring says.""" - host = server.strip() - in_server = "" - if host.startswith("["): # a bracketed IPv6 literal, optionally followed by ":port" - close = host.find("]") - if close != -1: - host, rest = host[1:close], host[close + 1 :] - in_server = rest[1:] if rest.startswith(":") else "" - elif host.count(":") == 1: # "host:port" — a bare IPv6 literal carries more than one colon - host, _, in_server = host.partition(":") - return host.strip(), in_server.strip() - - def _exact_split(text: str) -> tuple[str, str] | None: """:func:`split_generic_server` of ``text``, or ``None`` unless ``text`` is a host, ``host:port`` or ``[v6]:port`` written exactly, with a usable port where it carries one. Anything else, at least ``[::1]remote``, ``[::1]:5432x``, ``127.0.0.1 : 5432`` and ``[]``, gets ``None``, so no text the split would drop can sit behind a loopback host. An empty host - from a non-empty ``text`` is refused because the loopback check reads an empty host as on-box, - while the driver is handed the text, not an empty one.""" + from a non-empty ``text`` gets ``None`` too, so a refusal names the text the driver is handed + rather than an empty host.""" host, in_server = split_generic_server(text) written = (f"[{host}]" if text.startswith("[") else host) + ( f":{in_server}" if in_server else "" diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 2b4edd1923..d0e0d62d99 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -115,6 +115,7 @@ from messagefoundry.pki import IssuerIndex __all__ = [ + "DEFAULT_BIND_HOST", "DEFAULT_MAX_BODY_BYTES", "DEFAULT_MAX_HANDSHAKES_PER_HOST", "DEFAULT_MAX_HEADER_BYTES", @@ -126,6 +127,9 @@ logger = logging.getLogger(__name__) +#: The address a listener with a missing or blank ``host`` binds. The runner's peer-control gate +#: (``check_http_intake_auth``) reads it for a missing or blank host too. +DEFAULT_BIND_HOST = "127.0.0.1" # Resource caps (DoS guards), HTTP analogs of the MLLP frame/connection/idle caps. All overridable per # connection via Http() settings; None/0 (in any spelling) disables a cap explicitly where noted. @@ -966,7 +970,7 @@ def __init__(self, config: Source) -> None: # host on an inbound). Fall back to loopback for a missing/None value — never bind all # interfaces (0.0.0.0) by accident. The runner's exposed-gate refuses a non-loopback bind # without TLS (check_http_tls_exposure). See docs/CONNECTIONS.md. - self.host: str = s.get("host") or "127.0.0.1" + self.host: str = s.get("host") or DEFAULT_BIND_HOST self.port: int = port_setting(s["port"], transport="HTTP source") #: How this source names itself in a log line. self._log_name: str = config.name or f"{self.host}:{self.port}" diff --git a/messagefoundry/transports/rest.py b/messagefoundry/transports/rest.py index 6cd79753ab..3acbd778e8 100644 --- a/messagefoundry/transports/rest.py +++ b/messagefoundry/transports/rest.py @@ -496,9 +496,8 @@ def http_family_trust_anchor( :data:`~messagefoundry.config.tls_policy.SYSTEM_TRUST_ANCHOR`, which is the same value the shipped default resolves to, so callers have ONE "nothing configured" value to handle rather than two. - A ``url`` that names no host raises ``ValueError`` (:func:`hop_url_host`, BACKLOG #2207). Read as - ``""`` it took the loopback arm, which drops the instance CA and the CRL from a hop nobody can - place. ``cell`` leads that refusal. The two token-endpoint factories resolve the anchor before + A ``url`` that names no host raises ``ValueError`` (:func:`hop_url_host`, BACKLOG #2207). + ``cell`` leads that refusal. The two token-endpoint factories resolve the anchor before their provider checks the URL, so they pass the setting's name and the operator learns which URL to fix.""" ca = settings.get("tls_ca_file") @@ -813,8 +812,9 @@ class InsecureHopGuard: def assert_send(self, host: str, redacted_url: str) -> None: """Re-assert (zero I/O) that ``host`` is still a permitted hop under the captured posture. - An empty ``host`` is refused whatever the posture (BACKLOG #2207): the authority below reads - ``""`` as loopback and would ALLOW it. The text is fixed and names no part of the URL.""" + An empty ``host`` is refused whatever the posture (BACKLOG #2207), where the authority below + could still let an attested or accepted hop cross. The text is fixed and names no part of + the URL.""" if not host: raise InsecureHopRefused( f"{hop_name_prefix(self.connection)}{self.cell}: send-time refusal: the URL names " diff --git a/messagefoundry/transports/strict_requests.py b/messagefoundry/transports/strict_requests.py index 61d1698062..bbc19d096a 100644 --- a/messagefoundry/transports/strict_requests.py +++ b/messagefoundry/transports/strict_requests.py @@ -906,9 +906,8 @@ def _stays_on_the_box(host: str, proxy: str | None) -> bool: One rule for the cleartext refusal and the revocation refusal: a loopback host, by ``tls_policy.is_loopback_hop_host``, which never resolves DNS, reached with no proxy. A loopback address behind a proxy is not on the box, because the proxy carries it elsewhere. - A blank host is not either: that function counts ``""`` as loopback, and here it names no - hop at all.""" - return not proxy and bool(host) and is_loopback_hop_host(host) + A blank host is not either, because it names no hop at all.""" + return not proxy and is_loopback_hop_host(host) def _refuse_a_cleartext_vault_hop(url: str, proxy: str | None, *, connector: str) -> None: @@ -1497,7 +1496,7 @@ def _refuse_an_unrevoked_proxy_leg( if _crossed_unrevoked( connector=connector, # The leg ends at the proxy, so only the proxy's own host decides it, without DNS. - on_box=bool(host := (proxy_host or "").strip("[]")) and is_loopback_hop_host(host), + on_box=is_loopback_hop_host((proxy_host or "").strip("[]")), checks_revocation=lambda: crl_credited(context), revocation_attested=revocation_attested, attestation_section=attestation_section, diff --git a/tests/test_b629_5512_loopback_empty_host.py b/tests/test_b629_5512_loopback_empty_host.py new file mode 100644 index 0000000000..e0bd79b090 --- /dev/null +++ b/tests/test_b629_5512_loopback_empty_host.py @@ -0,0 +1,512 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""An empty host is not loopback (BACKLOG #5512). + +``tls_policy.is_loopback_hop_host("")`` used to answer True, so a caller that passed an unset host +as ``""`` took the on-box carve-out on its cleartext, revocation and trust-anchor checks. An empty +host means different things to different callers, so the predicate no longer answers for them. +Each caller here says what empty means where it stands: + +* an unconfigured feature: no log forwarder is built, so there is no hop to judge; +* a gate where "remote" is the permissive answer: empty still counts as this host; +* an unknown destination: a Postgres store, and every shared guard and trust anchor. It is judged + off-box, so the caller's gate applies as it does to any remote hop; +* no destination at all: a generic ODBC ``server`` naming no host and a blank SQL Server store are + refused whatever the posture or declaration. + +One more meaning, a default that really is local, is the HTTP listener's: a blank host binds +loopback. ``test_offloopback_without_effective_peer_control_refused_by_posture`` in +``tests/test_inbound_http_intake_auth.py`` pins it. The predicate's own answer is in +``tests/test_tls_policy.py``, and ``is_never_proxied_host`` in +``tests/test_loopback_hop_never_proxied.py``. + +Every case pairs the empty host with a control on a real host, so a site that refused everything, +or allowed everything, would fail too. Nothing here touches the network. +""" + +from __future__ import annotations + +import os +import subprocess +import sys +from collections.abc import Callable +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest +from pydantic import ValidationError + +from messagefoundry.__main__ import _warn_on_an_unrevoked_store_hop +from messagefoundry.auth.trust_anchors import smtp_hop_anchor_spec +from messagefoundry.config.models import ConnectorType, Destination, Source +from messagefoundry.config.settings import ( + INSECURE_TLS_ESCAPE_ENV, + AiSettings, + AlertsSettings, + AuthSettings, + EgressSettings, + LoggingSettings, + SecurityEnforcement, + StoreBackend, + StoreSettings, + TlsSettings, + _names_this_host, + forward_hop_disposition, + pinned_host_port, +) +from messagefoundry.config.tls_policy import ( + TLS_REVOCATION_ATTESTED_ENV, + HopDisposition, + HopPosture, + InsecureHopRefused, + TrustAnchorPolicy, + active_hop_posture, + is_loopback_hop_host, + resolve_trust_anchor, +) +from messagefoundry.pipeline.reference_sync import database_source_dsn +from messagefoundry.restricted_file import _loopback_share_problem +from messagefoundry.store.postgres import _build_ssl +from messagefoundry.transports.database import ( + DatabaseDestination, + DatabaseLookupExecutor, + DatabaseSource, +) +from messagefoundry.transports.mllp import InsecureHopGuard +from messagefoundry.transports.tcp import TcpDestination +from tests.test_hop_refusal_db_inbound import _GENERIC_CONNECTORS, _generic_dest, _generic_source +from tests.test_hop_refusal_rawtcp import tcp_cfg +from tests.test_hop_refusal_revocation import _guard, _pg + +ENFORCING = HopPosture(enforcing=True) +REMOTE = "192.0.2.10" # RFC 5737 TEST-NET-1: never routed +LOOPBACK = "127.0.0.1" + + +@pytest.fixture(autouse=True) +def _no_escape_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Neither relaxation may mask a refusal these tests expect.""" + monkeypatch.delenv(TLS_REVOCATION_ATTESTED_ENV, raising=False) + monkeypatch.delenv(INSECURE_TLS_ESCAPE_ENV, raising=False) + + +# --- an unconfigured feature: the log forwarder ----------------------------------------------- + + +@pytest.mark.parametrize("host", [None, ""]) +def test_an_unconfigured_forwarder_is_never_refused(host: str | None) -> None: + """With no host, ``serve`` builds no forwarder, so there is no hop to refuse. Built with + ``model_copy`` because the validator refuses ``forward_enabled`` with no host.""" + log = LoggingSettings().model_copy(update={"forward_host": host, "forward_enabled": True}) + assert forward_hop_disposition(log, ENFORCING) is HopDisposition.ALLOW + + +def test_a_configured_plaintext_forwarder_is_still_refused() -> None: + log = LoggingSettings(forward_host=REMOTE, forward_enabled=True) + assert forward_hop_disposition(log, ENFORCING) is HopDisposition.REFUSE + + +# --- a gate where remote is the permissive answer ---------------------------------------------- + + +@pytest.mark.parametrize("host", ["", " ", ".", " . "]) +def test_a_host_that_trims_to_nothing_is_not_a_separate_collector(host: str) -> None: + """The forwarding gate and the share check ask whether a host is this one, and there "remote" + passes. A value that trims to nothing names no other system, so it keeps counting as this one.""" + assert _names_this_host(host) is True + + +@pytest.mark.parametrize("host", ["localhost", "LOCALHOST.", "app.localhost"]) +def test_names_this_host_still_reads_the_localhost_names(host: str) -> None: + assert _names_this_host(host) is True + + +def test_names_this_host_still_reads_a_real_remote_as_remote() -> None: + assert _names_this_host(REMOTE) is False + + +def test_a_key_share_whose_server_trims_to_nothing_is_still_refused() -> None: + """The share check reads ``_names_this_host``, and a share it cannot tell from this host is + refused. CONTROL: a share on a named remote server is not.""" + assert _loopback_share_problem("\\\\ \\share\\key.pem", "thishost", lambda _: None) is not None + assert ( + _loopback_share_problem("\\\\files.example\\share\\key.pem", "thishost", lambda _: None) + is None + ) + + +# --- an unknown destination: the store --------------------------------------------------------- + + +def _store_with_server(server: str | None) -> StoreSettings: + # model_copy: the validator refuses a None server, so the None case cannot be built through it. + return _pg(LOOPBACK).model_copy(update={"server": server}) + + +@pytest.mark.parametrize("server", ["", None]) +def test_a_store_with_no_server_is_not_judged_on_box(server: str | None) -> None: + with pytest.raises(InsecureHopRefused, match=r"to \(no \[store\]\.server\):"): + _build_ssl(_store_with_server(server), posture=ENFORCING) + + +def test_a_store_on_loopback_is_still_on_box() -> None: + assert _build_ssl(_store_with_server(LOOPBACK), posture=ENFORCING) is not None + + +@pytest.mark.parametrize( + ("server", "warned"), [("", True), (None, True), (LOOPBACK, False)], ids=str +) +def test_a_cli_store_open_at_warn_warns_on_a_store_with_no_server( + server: str | None, warned: bool, caplog: pytest.LogCaptureFixture +) -> None: + """The CLI's own run of the store guard, at ``warn``, where a refusal becomes a WARNING.""" + settings = SimpleNamespace( + ai=AiSettings(), + security=SimpleNamespace(enforcement=SecurityEnforcement.WARN), + store=_store_with_server(server), + ) + with caplog.at_level("WARNING"): + _warn_on_an_unrevoked_store_hop(settings) # type: ignore[arg-type] + assert ("(no [store].server)" in caplog.text) is warned + + +# --- an unknown destination: a generic ODBC server ----------------------------------------------- + + +#: Each passes the required-setting check, and each leaves a host unnamed. +_GENERIC_SERVERS_NAMING_NO_HOST = [ + " ", + ":5432", + "[]", + "[ ]:5432", + "[,]", + ":1433:", + ",1433", + " ,db.example", + "db.example,", + "db.example,,other.example", +] + + +@pytest.mark.parametrize("server", _GENERIC_SERVERS_NAMING_NO_HOST) +@pytest.mark.parametrize("posture", [ENFORCING, HopPosture(enforcing=False), None], ids=str) +@pytest.mark.parametrize(("connector", "config"), _GENERIC_CONNECTORS) +def test_a_generic_server_naming_no_host_is_refused_at_every_posture( + connector: Callable[[Any], object], + config: Callable[..., Any], + posture: HopPosture | None, + server: str, +) -> None: + """The driver is handed that text, so where it dials is not known here. CONTROL: real loopback + builds at the same posture.""" + with active_hop_posture(posture), pytest.raises(InsecureHopRefused, match="names no host"): + connector(config(server=server)) + with active_hop_posture(posture): + assert connector(config(server=LOOPBACK)) + + +_ATTESTED = {"tls_hop_attested": True, "tls_hop_attested_reason": "a segment the engine cannot see"} +_ACCEPTED = {"cleartext_accepted": True, "cleartext_reason": "a hop accepted as cleartext"} +_TLS_MODE = {"odbc_params": {"sslmode": "verify-full"}} + + +@pytest.mark.parametrize( + ("connector", "config", "declared"), + [ + (DatabaseDestination, _generic_dest, _ATTESTED), + (DatabaseDestination, _generic_dest, _ACCEPTED), + (DatabaseDestination, _generic_dest, _TLS_MODE), + (DatabaseSource, _generic_source, _ATTESTED), + ], + ids=["outbound-attested", "outbound-accepted", "outbound-tls-mode", "inbound-attested"], +) +def test_nothing_declared_covers_a_generic_hop_with_no_named_host( + connector: Callable[[Any], object], config: Callable[..., Any], declared: dict[str, Any] +) -> None: + """A declaration is about a hop, and this one has no destination to be about. The cleartext + guard stands down on a TLS mode, so the refusal sits in front of it. CONTROL: the same + declaration still builds on a named remote host.""" + with active_hop_posture(ENFORCING), pytest.raises(InsecureHopRefused, match="names no host"): + connector(config(server=" ", **declared)) + with active_hop_posture(ENFORCING): + assert connector(config(server=REMOTE, **declared)) + + +# --- the SQL Server preset: Database, DatabasePoll, DatabaseLookup, DatabaseRef --------------------- + +#: "" is left out: the connectors refuse it earlier, as a missing setting. A value holding a comma +#: is left out too: the preset refuses every comma first, with its own remedy. +_PRESET_NO_HOST = [" ", ":1433", "[]", ":1433:"] +_PRESET_BASE = {"database": "d", "statement": "INSERT INTO t (x) VALUES (:x)"} + + +def _preset_dest(**overrides: object) -> Destination: + attested = bool(overrides.pop("tls_hop_attested", False)) + return Destination( + name="OB_DB_PRE", + type=ConnectorType.DATABASE, + settings={**_PRESET_BASE, **overrides}, + tls_hop_attested=attested, + tls_hop_attested_reason="a segment the engine cannot see" if attested else None, + ) + + +def _preset_source(**overrides: object) -> Source: + settings = {"database": "d", "poll_statement": "SELECT 1", **overrides} + return Source(name="IB_DB_PRE", type=ConnectorType.DATABASE, settings=settings) + + +def _preset_lookup(**overrides: object) -> object: + settings = {"database": "d", **overrides} + return DatabaseLookupExecutor({"c": settings}, egress=EgressSettings(deny_by_default=False)) + + +def _preset_ref(**overrides: object) -> object: + return database_source_dsn({"database": "d", **overrides}) + + +_PRESET_ENTRY_POINTS = [ + (DatabaseDestination, _preset_dest), + (DatabaseSource, _preset_source), + (None, _preset_lookup), + (None, _preset_ref), +] + + +@pytest.mark.parametrize("server", _PRESET_NO_HOST) +@pytest.mark.parametrize("posture", [ENFORCING, HopPosture(enforcing=False), None], ids=str) +@pytest.mark.parametrize(("connector", "config"), _PRESET_ENTRY_POINTS) +def test_a_sql_server_preset_server_naming_no_host_is_refused_at_every_posture( + connector: Callable[[Any], object] | None, + config: Callable[..., Any], + posture: HopPosture | None, + server: str, +) -> None: + """It would reach the driver as ``SERVER=,1433``. CONTROL: a named host builds at the same + posture.""" + + def build(**overrides: object) -> object: + made = config(**overrides) + return made if connector is None else connector(made) + + with active_hop_posture(posture), pytest.raises(InsecureHopRefused, match="names no host"): + build(server=server) + with active_hop_posture(posture): + assert build(server=LOOPBACK) + + +@pytest.mark.parametrize("declared", [{}, "attested"], ids=["plain", "attested"]) +@pytest.mark.parametrize("posture", [ENFORCING, HopPosture(enforcing=False), None], ids=str) +@pytest.mark.parametrize(("connector", "config"), _PRESET_ENTRY_POINTS) +def test_a_sql_server_preset_server_of_none_is_refused_whatever_is_declared( + connector: Callable[[Any], object] | None, + config: Callable[..., Any], + posture: HopPosture | None, + declared: object, +) -> None: + """``None`` must not become the host ``None`` and ``SERVER=None,1433``. The DatabaseRef path + has no required-setting check ahead of the build, so it is the one that sees ``None``; the + others are pinned too, so none can start sending it. CONTROL: a named host builds.""" + extra: dict[str, Any] = {"tls_hop_attested": True} if declared == "attested" else {} + if declared == "attested" and config is not _preset_dest: + extra = { + "tls_hop_attested": True, + "tls_hop_attested_reason": "a segment the engine cannot see", + } + + def build(**overrides: object) -> object: + made = config(**{**extra, **overrides}) + return made if connector is None else connector(made) + + with active_hop_posture(posture), pytest.raises(ValueError, match="server") as caught: + build(server=None) + assert "None,1433" not in str(caught.value) + with active_hop_posture(posture): + assert build(server=LOOPBACK) + + +def test_a_sql_server_preset_dsn_never_carries_the_host_none() -> None: + """The build itself, below every entry point.""" + from messagefoundry.transports.database import _build_dsn + + with pytest.raises(InsecureHopRefused, match="names no host"): + _build_dsn({"database": "d", "server": None}) + + +def test_a_database_ref_with_an_empty_server_is_refused() -> None: + """The DatabaseRef path has no required-setting check ahead of the build.""" + with active_hop_posture(None), pytest.raises(InsecureHopRefused, match="names no host"): + database_source_dsn({"database": "d", "server": ""}) + + +@pytest.mark.parametrize("server", [" ", ":1433"]) +def test_an_attestation_does_not_cover_a_preset_server_with_no_host(server: str) -> None: + with active_hop_posture(ENFORCING), pytest.raises(InsecureHopRefused, match="names no host"): + DatabaseDestination(_preset_dest(server=server, tls_hop_attested=True)) + with active_hop_posture(ENFORCING): + assert DatabaseDestination(_preset_dest(server=REMOTE, tls_hop_attested=True)) + + +@pytest.mark.parametrize("server", ["1433", "1:2", "12:34", "[1433]", "::", "[::]", "::1", "db"]) +def test_names_no_host_accepts_a_plain_number_and_the_unspecified_literals(server: str) -> None: + """Pins what the docs say is accepted, so the stated rule cannot drift from the code.""" + from messagefoundry.hostlist import names_no_host + + assert names_no_host(server) is False + + +@pytest.mark.parametrize("server", ["[", "]", ":1433:", "[,]", "", ":1433", "[]"]) +def test_names_no_host_refuses_what_the_docs_say_it_refuses(server: str) -> None: + from messagefoundry.hostlist import names_no_host + + assert names_no_host(server) is True + + +# --- the leaf module: settings may not import the transports package ----------------------------- + + +def test_validating_a_sql_server_store_does_not_import_the_transports_package() -> None: + """In a subprocess, so another test's imports cannot mask it.""" + tree = Path(__file__).resolve().parents[1] + code = ( + "import sys\n" + "import messagefoundry\n" + "print(messagefoundry.__file__)\n" + "from messagefoundry.config.settings import StoreBackend, StoreSettings\n" + "StoreSettings(backend=StoreBackend.SQLSERVER, server='db.example', database='d'," + " username='u')\n" + "raise SystemExit(1 if 'messagefoundry.transports' in sys.modules else 0)\n" + ) + # PYTHONPATH and cwd name this tree, so an editable install pointing elsewhere cannot make + # the subprocess test another one; the imported module's path is asserted below. + env = {**os.environ, "PYTHONPATH": str(tree)} + done = subprocess.run( + [sys.executable, "-P", "-c", code], + capture_output=True, + text=True, + cwd=tree, + env=env, + timeout=120, + ) + imported = Path(done.stdout.splitlines()[0]).resolve() if done.stdout else None + assert imported is not None and imported.is_relative_to(tree), (imported, done.stderr) + assert done.returncode == 0, done.stderr + + +# --- what a blank [store].server means on each backend ------------------------------------------ + + +@pytest.mark.parametrize("server", ["", " ", "\t", ":1433", "[]", ",1433", "db.example,"]) +def test_a_sql_server_store_refuses_a_server_naming_no_host(server: str) -> None: + """It would reach the driver as ``SERVER=,1433`` or the like, and no hop guard reads the SQL + Server store's host.""" + with pytest.raises(ValidationError, match=r"\[store\]\.server names no host"): + _pg(server, backend=StoreBackend.SQLSERVER) + + +@pytest.mark.parametrize("server", ["db.example", "tcp:db.example", r".\SQLEXPRESS", "::1"]) +def test_a_sql_server_store_keeps_a_server_that_names_a_host(server: str) -> None: + assert _pg(server, backend=StoreBackend.SQLSERVER).server == server + + +@pytest.mark.parametrize("server", [" ", "\t"]) +def test_a_postgres_store_refuses_a_server_of_spaces_and_names_the_setting(server: str) -> None: + """Spaces are not empty to asyncpg: it would try them as a host name.""" + with pytest.raises(ValidationError, match=r"\[store\]\.server names no host"): + _pg(server) + + +def test_a_postgres_store_keeps_an_empty_server() -> None: + """Empty is legal here (docs/CONFIGURATION.md, the ``server`` row). The hop is still judged + off-box (``test_a_store_with_no_server_is_not_judged_on_box``).""" + assert _pg("").server == "" + + +@pytest.mark.parametrize("server", ["", " "]) +def test_a_sqlite_store_has_no_server_to_refuse(server: str) -> None: + assert StoreSettings(backend=StoreBackend.SQLITE, server=server).server == server + + +# --- an unknown destination: the shared guards and the trust anchor ----------------------------- + + +def test_the_cleartext_guard_refuses_an_empty_host() -> None: + def guard(host: str) -> InsecureHopGuard: + with active_hop_posture(ENFORCING): + return InsecureHopGuard.capture( + host=host, + port=2575, + cell="test", + description="test", + attested=False, + attested_reason=None, + connection=None, + ) + + with pytest.raises(InsecureHopRefused): + guard("").enforce_construction() + guard(LOOPBACK).enforce_construction() + + +def test_the_revocation_guard_refuses_an_empty_host() -> None: + with active_hop_posture(ENFORCING): + assert _guard("").disposition() is HopDisposition.REFUSE + assert _guard(LOOPBACK).disposition() is HopDisposition.ALLOW + + +def test_a_trust_anchor_on_an_empty_host_keeps_the_ca_and_the_crl() -> None: + """The loopback arm drops the instance CA and the CRL, so a hop nobody can place keeps both.""" + policy = TrustAnchorPolicy(internal_ca_file="internal.pem", mode="pinned", crl_file="org.crl") + empty = resolve_trust_anchor(connection_ca_file=None, host="", policy=policy) + assert (empty.cafile, empty.crl_file) == ("internal.pem", "org.crl") + on_box = resolve_trust_anchor(connection_ca_file=None, host=LOOPBACK, policy=policy) + assert (on_box.cafile, on_box.crl_file) == (None, None) + + +# --- callers that read the predicate's answer for an empty host ---------------------------------- + + +def test_a_vault_hop_with_a_blank_host_does_not_stay_on_the_box() -> None: + # strict_requests imports requests at module level and the harness leg lacks it. + pytest.importorskip("requests") + from messagefoundry.transports.strict_requests import _stays_on_the_box + + assert _stays_on_the_box("", None) is False + assert _stays_on_the_box(LOOPBACK, None) is True + + +@pytest.mark.parametrize("entry", [":8123", "[]:8123"]) +def test_a_sidecar_entry_with_no_host_is_not_pinned(entry: str) -> None: + assert pinned_host_port(entry) is None + assert pinned_host_port(f"{LOOPBACK}:8123") == (LOOPBACK, 8123) + + +def test_an_smtp_relay_with_no_host_reads_no_internal_ca() -> None: + alerts: dict[str, Any] = {"email_from": "a@example.org", "email_to": ["b@example.org"]} + tls = TlsSettings(internal_ca_file="internal.pem", trust_anchor_mode="pinned") + assert smtp_hop_anchor_spec(AlertsSettings(**alerts), AuthSettings(), tls) is None + relay = AlertsSettings(**alerts, email_smtp_host="smtp.example.org") + assert smtp_hop_anchor_spec(relay, AuthSettings(), tls) is not None + + +# --- row item 1: a bracketed literal reads as remote --------------------------------------------- + + +def test_a_bracketed_loopback_literal_reads_as_remote() -> None: + """Not a defect (row item 1). The predicate reads a host as written, and ``[::1]`` is not an + address to :mod:`ipaddress`. Reading it as remote can only refuse, so it adds no hop to those + judged on-box. The HTTP family never meets the spelling: ``urlsplit`` strips the brackets.""" + assert is_loopback_hop_host("[::1]") is False + assert is_loopback_hop_host("::1") is True + + +@pytest.mark.parametrize(("host", "refused"), [("[::1]", True), ("::1", False)]) +def test_a_bracketed_loopback_tcp_hop_is_refused_when_enforcing(host: str, refused: bool) -> None: + config: Destination = tcp_cfg(host) + with active_hop_posture(ENFORCING): + if refused: + with pytest.raises(InsecureHopRefused): + TcpDestination(config) + else: + assert TcpDestination(config) diff --git a/tests/test_hop_refusal_db_inbound.py b/tests/test_hop_refusal_db_inbound.py index 5c3bf94df7..104a215082 100644 --- a/tests/test_hop_refusal_db_inbound.py +++ b/tests/test_hop_refusal_db_inbound.py @@ -953,7 +953,7 @@ def test_generic_guard_is_none_off_the_arm() -> None: ("[::1]remote.example", {}, ("[::1]remote.example", 0)), ("[::1]:5432x", {}, ("[::1]:5432x", 0)), ("127.0.0.1 : 5432", {}, ("127.0.0.1 : 5432", 0)), - # An empty bracketed host is read whole: the loopback check reads an empty host as on-box. + # An empty bracketed host is read whole, so a refusal names the text the driver is handed. ("[]", {}, ("[]", 0)), ("[]:5432", {}, ("[]:5432", 0)), ], diff --git a/tests/test_hop_refusal_revocation.py b/tests/test_hop_refusal_revocation.py index 353daab008..042afa2210 100644 --- a/tests/test_hop_refusal_revocation.py +++ b/tests/test_hop_refusal_revocation.py @@ -1095,9 +1095,9 @@ def test_the_smart_revocation_attestation_comes_from_its_own_settings_key(smart_ # BACKLOG #1924. Each URL parses to NO hostname (`urlsplit(...).hostname is None`). The guard used to -# pass `hostname or ""`, and `is_loopback_hop_host("")` is True, so a hop it could not classify took -# the on-box carve-out and crossed an enforcing posture with no refusal. It is now refused outright, -# as a plain ValueError. `pytest.raises(ValueError)` alone would also catch a posture refusal, since +# pass `hostname or ""`, and `is_loopback_hop_host("")` was True until BACKLOG #5512, so a hop it +# could not classify took the on-box carve-out and crossed an enforcing posture with no refusal. It +# is now refused outright, as a plain ValueError. `pytest.raises(ValueError)` alone would also catch a posture refusal, since # InsecureHopRefused subclasses it, so every arm matches the message. _HOSTLESS_HTTPS = ("https:///token", "https://:443/token") @@ -1570,9 +1570,9 @@ async def test_the_blanket_env_does_not_cross_the_enforcing_oidc_legs( async def test_an_oidc_leg_with_no_host_is_refused_not_treated_as_loopback() -> None: - """FAIL-CLOSED on a host the guard cannot read. ``is_loopback_hop_host("")`` is True, so a guard - fed an empty host would take the on-box carve-out and ALLOW. The settings validator refuses a - missing URL, so only unvalidated settings reach this; ``model_copy`` builds them here.""" + """FAIL-CLOSED on a host the guard cannot read, whatever the posture, rather than leaving an + empty host to the guard's remote reading. The settings validator refuses a missing URL, so only + unvalidated settings reach this; ``model_copy`` builds them here.""" settings = _oidc_settings( oidc_issuer=f"https://{REMOTE}", oidc_authorization_endpoint=f"https://{REMOTE}/authorize", @@ -1582,8 +1582,11 @@ async def test_an_oidc_leg_with_no_host_is_refused_not_treated_as_loopback() -> ).model_copy(update={"oidc_jwks_uri": None}) store = await MessageStore.open(":memory:") try: - with pytest.raises(InsecureHopRefused, match="OIDC jwks_uri endpoint"): - AuthService(store, settings, ldap=_FakeLdap(), hop_posture=PROD_PHI) # type: ignore[arg-type] + for posture in (PROD_PHI, STAGING_PHI): + with pytest.raises( + InsecureHopRefused, match="OIDC jwks_uri endpoint: the URL names no host" + ): + AuthService(store, settings, ldap=_FakeLdap(), hop_posture=posture) # type: ignore[arg-type] finally: await store.close() diff --git a/tests/test_hop_url_with_no_host_is_refused.py b/tests/test_hop_url_with_no_host_is_refused.py index 74b4444bbd..b2e84e256b 100644 --- a/tests/test_hop_url_with_no_host_is_refused.py +++ b/tests/test_hop_url_with_no_host_is_refused.py @@ -2,10 +2,10 @@ # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """One refusal for a hop URL that names no host, at the sites BACKLOG #2207 names. -``tls_policy.is_loopback_hop_host("")`` is True. So a site that wrote ``hostname or ""`` took the -on-box carve-out for the one hop it could not classify. BACKLOG #1924 closed that in the four -construction guards in ``transports/rest.py``. This file covers the sites that still read an empty -host after it: +``tls_policy.is_loopback_hop_host("")`` was True until BACKLOG #5512. So a site that wrote +``hostname or ""`` took the on-box carve-out for the one hop it could not classify. BACKLOG #1924 +closed that in the four construction guards in ``transports/rest.py``. This file covers the sites +that still read an empty host after it: * the send-time re-check in ``_post`` and ``_probe`` of the four HTTP destinations, and in ``FhirLookupExecutor``; diff --git a/tests/test_loopback_hop_never_proxied.py b/tests/test_loopback_hop_never_proxied.py index 92fe9225b2..df6e68fea2 100644 --- a/tests/test_loopback_hop_never_proxied.py +++ b/tests/test_loopback_hop_never_proxied.py @@ -244,8 +244,8 @@ def test_the_rule_reads_a_host_exactly_as_the_cleartext_guard_does( def test_a_url_with_no_host_is_not_counted_as_on_box() -> None: - """The shared predicate reads an empty host as loopback, and the guard refuses a URL with no - host before it asks. This rule takes the guard's side: nothing unreadable goes direct.""" + """The guard refuses a URL with no host before it asks the shared predicate. This rule takes + the guard's side: nothing unreadable goes direct.""" assert is_never_proxied_host("127.0.0.1") assert not is_never_proxied_host("") assert not is_never_proxied_host(None) @@ -495,10 +495,8 @@ def test_a_percent_encoded_host_goes_to_this_box_on_a_direct_leg() -> None: assert _dialled(opener, "http://%6cocalhost:18080/x") == "localhost:18080" -def test_the_host_a_plain_rstrip_would_empty_stays_off_box() -> None: - """Why a plain ``rstrip`` is not the fix. ``http://./x`` names the host ``.``, which is remote - today; stripped, it would be the empty host, which the predicate reads as loopback.""" +def test_a_lone_dot_host_reads_as_remote() -> None: + """``http://./x`` names the host ``.``, which is remote.""" host = hop_url_host("http://./x", cell="test") assert host == "." assert not is_loopback_hop_host(host) - assert is_loopback_hop_host(host.rstrip(".")) diff --git a/tests/test_tls_policy.py b/tests/test_tls_policy.py index 1c371312ed..50cc8db540 100644 --- a/tests/test_tls_policy.py +++ b/tests/test_tls_policy.py @@ -419,7 +419,7 @@ def test_tls_revocation_attested_unset_is_false(monkeypatch: pytest.MonkeyPatch) ("::1", True), ("localhost", True), ("LOCALHOST", True), # case-insensitive - ("", True), # empty host = on-box bind with no host component + ("", False), # names no destination; each caller says what empty means (BACKLOG #5512) ("10.0.0.5", False), ("example.com", False), # A name that WOULD resolve to loopback is still remote — is_loopback_hop_host never resolves DNS. diff --git a/tests/test_tls_trust_anchor.py b/tests/test_tls_trust_anchor.py index 4976b63c05..871183800d 100644 --- a/tests/test_tls_trust_anchor.py +++ b/tests/test_tls_trust_anchor.py @@ -116,7 +116,7 @@ def test_unset_internal_ca_falls_back_to_system_even_in_pinned() -> None: assert anchor == TrustAnchor(cafile=None, load_system_roots=True) -@pytest.mark.parametrize("host", ["127.0.0.1", "localhost", "", "::1", "127.5.6.7"]) +@pytest.mark.parametrize("host", ["127.0.0.1", "localhost", "::1", "127.5.6.7"]) def test_loopback_hop_is_exempt(host: str) -> None: # An on-box hop needs no org-PKI anchor — the internal CA is for verifying internal NETWORK peers. anchor = resolve_trust_anchor(