From e8342b04eae786c39c3a0fb08452307160bb29d6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 01:58:48 -0600 Subject: [PATCH 01/12] An empty host is no longer loopback on the hop guards is_loopback_hop_host("") answered True, so a caller passing an unset host as "" took the on-box carve-out on its cleartext, revocation and trust-anchor checks. Each caller now says what empty means: the HTTP listener's local default, an unconfigured forwarder, a this-host gate that fails closed, or an unknown destination judged off-box. BACKLOG #5512 --- changelog.d/5512.security.md | 8 + docs/CONNECTIONS.md | 2 +- messagefoundry/config/settings.py | 14 +- messagefoundry/config/tls_policy.py | 45 +-- messagefoundry/pipeline/wiring_runner.py | 9 +- messagefoundry/store/postgres.py | 9 +- messagefoundry/transports/bounded_read.py | 4 +- messagefoundry/transports/db_endpoint.py | 4 +- messagefoundry/transports/rest.py | 10 +- messagefoundry/transports/strict_requests.py | 3 +- tests/test_b629_5512_loopback_empty_host.py | 295 ++++++++++++++++++ tests/test_hop_refusal_db_inbound.py | 2 +- tests/test_hop_refusal_revocation.py | 12 +- tests/test_hop_url_with_no_host_is_refused.py | 8 +- tests/test_loopback_hop_never_proxied.py | 6 +- tests/test_tls_policy.py | 2 +- 16 files changed, 372 insertions(+), 61 deletions(-) create mode 100644 changelog.d/5512.security.md create mode 100644 tests/test_b629_5512_loopback_empty_host.py diff --git a/changelog.d/5512.security.md b/changelog.d/5512.security.md new file mode 100644 index 0000000000..61e085b9f2 --- /dev/null +++ b/changelog.d/5512.security.md @@ -0,0 +1,8 @@ +- **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` and stays on-box, + a log forwarder with no host has no hop to judge, and the log-forwarding and key-share checks + still count a blank value as this host. A PostgreSQL store with a blank `server` and a generic + ODBC `server` of spaces are judged off-box, so each is refused under + `[security].enforcement = enforce` unless the hop is otherwise covered. (`BACKLOG #5512`) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 308cace66e..e381ce553a 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -4247,7 +4247,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/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 7cfbd752f7..d7ada277c4 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -5150,11 +5150,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 == "localhost" or h.endswith(".localhost"): return True addr = _host_ip_literal(h) return addr is not None and (addr.is_loopback or addr.is_unspecified) @@ -5451,15 +5452,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 diff --git a/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index 85236be0f0..9f2f4260bc 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,32 @@ 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 + ``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, which fails closed at the cleartext guards — a name that happens to resolve to a loopback address is still refused, because resolution is attacker-influenceable and would let a hostname smuggle an off-box hop past the on-box carve-out. + **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 as remote and fails closed. + **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 +2470,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,9 +3607,8 @@ 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. + # not reach here from a provider, which refuses it first (BACKLOG #2851). A host this + # function cannot read must not count as on-box, so it gets a name that never does. host = "(unreadable host)" anchor = resolve_trust_anchor(connection_ca_file=ca_file, host=host, policy=TrustAnchorPolicy()) verify = requests_verify_from_anchor(anchor, cell=cell) diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index 45070a4da3..781028df78 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -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 loopback: this is HttpSource's own `s.get("host") or "127.0.0.1"` fallback, + # read here because the shared predicate does not take "" as loopback (BACKLOG #5512). + host = str(source.settings.get("host", "127.0.0.1")) or "127.0.0.1" + # 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..a579123ff7 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -1784,8 +1784,9 @@ 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. + # settings.server is str | None, and the load refuses only None. A blank one names no host, so + # this guard cannot place the hop and judges it off-box (BACKLOG #5512); the stand-in names the + # setting in the refusal, where a bare "" would leave a gap in the text. 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 +1794,9 @@ 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 or "(no [store].server)", posture=posture, context=ctx + ) return ctx 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/db_endpoint.py b/messagefoundry/transports/db_endpoint.py index 0506a52a25..a1f26a25a6 100644 --- a/messagefoundry/transports/db_endpoint.py +++ b/messagefoundry/transports/db_endpoint.py @@ -95,8 +95,8 @@ def _exact_split(text: str) -> tuple[str, str] | None: 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/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..16a9f5e615 100644 --- a/messagefoundry/transports/strict_requests.py +++ b/messagefoundry/transports/strict_requests.py @@ -906,8 +906,7 @@ 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.""" + A blank host is not either, because it names no hop at all.""" return not proxy and bool(host) and is_loopback_hop_host(host) 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..09756a49d6 --- /dev/null +++ b/tests/test_b629_5512_loopback_empty_host.py @@ -0,0 +1,295 @@ +# 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: + +* a default that really is local: the HTTP listener binds ``127.0.0.1``, so it stays on-box; +* 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: the store, a generic ODBC ``server``, and every shared guard and trust + anchor. It is judged off-box, so it fails closed. + +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 + +from collections.abc import Callable +from typing import Any + +import pytest + +from messagefoundry.auth.trust_anchors import smtp_hop_anchor_spec +from messagefoundry.config.models import ConnectorType, Destination, Source +from messagefoundry.config.settings import ( + AlertsSettings, + AuthSettings, + LoggingSettings, + StoreBackend, + StoreSettings, + TlsSettings, + _names_this_host, + forward_hop_disposition, + pinned_host_port, +) +from messagefoundry.config.tls_policy import ( + HopDisposition, + HopPosture, + InsecureHopRefused, + RevocationHopGuard, + TrustAnchorPolicy, + active_hop_posture, + is_loopback_hop_host, + resolve_trust_anchor, +) +from messagefoundry.config.wiring import WiringError +from messagefoundry.pipeline.wiring_runner import check_http_intake_auth +from messagefoundry.restricted_file import _loopback_share_problem +from messagefoundry.store.postgres import _build_ssl +from messagefoundry.transports.bounded_read import is_never_proxied_host +from messagefoundry.transports.database import DatabaseDestination, DatabaseSource +from messagefoundry.transports.mllp import InsecureHopGuard +from messagefoundry.transports.strict_requests import _stays_on_the_box +from messagefoundry.transports.tcp import TcpDestination + +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("MEFOR_TLS_REVOCATION_ATTESTED", raising=False) + monkeypatch.delenv("MEFOR_ALLOW_INSECURE_TLS", raising=False) + + +# --- the predicate ---------------------------------------------------------------------------- + + +def test_an_empty_host_is_not_loopback() -> None: + assert is_loopback_hop_host("") is False + # CONTROL: the three shapes that really do name this box still do. + assert all(is_loopback_hop_host(h) for h in ("localhost", "127.0.0.1", "::1")) + + +# --- a default that really is local: the inbound HTTP listener -------------------------------- + + +def _http_source(host: str) -> Source: + return Source(type=ConnectorType.HTTP, settings={"host": host, "port": 8080}) + + +def test_a_blank_http_listener_host_binds_loopback_so_the_gate_passes_it() -> None: + """``HttpSource`` reads ``s.get("host") or "127.0.0.1"``, so a blank host binds loopback. The + gate has to read the same default, or it would refuse a listener that is not exposed.""" + check_http_intake_auth(_http_source(""), "IB_HTTP", posture=ENFORCING) + + +def test_the_http_listener_gate_still_refuses_an_exposed_bind() -> None: + with pytest.raises(WiringError, match="non-loopback host"): + check_http_intake_auth(_http_source("0.0.0.0"), "IB_HTTP", posture=ENFORCING) + + +# --- 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 + + +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 _pg(server: str | None) -> StoreSettings: + settings = StoreSettings( + backend=StoreBackend.POSTGRES, server=LOOPBACK, database="mefor", username="mefor" + ) + # model_copy: the validator refuses a None server, and a blank one is the case it lets through. + return settings.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="revocation"): + _build_ssl(_pg(server), posture=ENFORCING) + + +def test_a_store_on_loopback_is_still_on_box() -> None: + assert _build_ssl(_pg(LOOPBACK), posture=ENFORCING) is not None + + +# --- an unknown destination: a generic ODBC server ----------------------------------------------- + + +_GENERIC: dict[str, object] = { + "dialect": "generic", + "odbc_driver": "PostgreSQL Unicode", +} + + +def _generic_dest(server: str) -> Destination: + return Destination( + name="OB_DB_GEN", + type=ConnectorType.DATABASE, + settings={**_GENERIC, "server": server, "statement": "INSERT INTO t (x) VALUES (:x)"}, + ) + + +def _generic_source(server: str) -> Source: + return Source( + name="IB_DB_GEN", + type=ConnectorType.DATABASE, + settings={**_GENERIC, "server": server, "poll_statement": "SELECT 1"}, + ) + + +_GENERIC_CONNECTORS = [(DatabaseDestination, _generic_dest), (DatabaseSource, _generic_source)] + + +@pytest.mark.parametrize(("connector", "config"), _GENERIC_CONNECTORS) +def test_a_blank_generic_server_is_not_judged_on_box( + connector: Callable[[Any], object], config: Callable[[str], Any] +) -> None: + """A ``server`` of spaces passes the required-setting check and splits to an empty host. The + driver is handed that text, so where it dials is not known here. CONTROL: real loopback.""" + with active_hop_posture(ENFORCING), pytest.raises(InsecureHopRefused): + connector(config(" ")) + with active_hop_posture(ENFORCING): + assert connector(config(LOOPBACK)) + + +# --- 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: + def disposition(host: str) -> HopDisposition | None: + return RevocationHopGuard.capture( + host=host, + cell="test", + description="test", + attested=False, + posture=ENFORCING, + connection=None, + ).disposition() + + assert disposition("") is HopDisposition.REFUSE + assert disposition(LOOPBACK) 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 already answer for an empty host themselves ------------------------------------ + + +def test_the_never_proxied_reader_reads_no_host_as_off_box() -> None: + assert is_never_proxied_host("") is False + assert is_never_proxied_host(None) is False + assert is_never_proxied_host(LOOPBACK) is True + + +def test_a_vault_hop_with_a_blank_host_does_not_stay_on_the_box() -> None: + assert _stays_on_the_box("", None) is False + assert _stays_on_the_box(LOOPBACK, None) is True + + +def test_a_sidecar_entry_with_no_host_is_not_pinned() -> None: + assert pinned_host_port(":8123") 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, which fails closed ------------------------- + + +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_fails_closed(host: str, refused: bool) -> None: + config = Destination( + name="OB_TCP", + type=ConnectorType.TCP, + settings={"host": host, "port": 9100, "framing": "stx_etx"}, + ) + 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..c55d36f4ef 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", 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..14b16ee286 100644 --- a/tests/test_loopback_hop_never_proxied.py +++ b/tests/test_loopback_hop_never_proxied.py @@ -496,9 +496,9 @@ def test_a_percent_encoded_host_goes_to_this_box_on_a_direct_leg() -> None: 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.""" + """``http://./x`` names the host ``.``, which is remote. Stripped, it is the empty host, which + is remote too since BACKLOG #5512.""" host = hop_url_host("http://./x", cell="test") assert host == "." assert not is_loopback_hop_host(host) - assert is_loopback_hop_host(host.rstrip(".")) + assert not 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. From b20ecb2586999931fa20fba1e5959674a0b30c37 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 02:15:18 -0600 Subject: [PATCH 02/12] Give the empty-host rule one owner at each caller The store stand-in moves into its guard, so both callers word a blank server alike. The HTTP gate reads the listener's named default. Guards the predicate now covers go, and the new tests reuse existing helpers. BACKLOG #5512 --- messagefoundry/__main__.py | 2 +- messagefoundry/config/settings.py | 4 +- messagefoundry/pipeline/wiring_runner.py | 8 +- messagefoundry/store/postgres.py | 13 +- messagefoundry/transports/http_listener.py | 6 +- messagefoundry/transports/strict_requests.py | 4 +- tests/test_b629_5512_loopback_empty_host.py | 134 +++++-------------- tests/test_loopback_hop_never_proxied.py | 10 +- 8 files changed, 58 insertions(+), 123 deletions(-) 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 d7ada277c4..cf20ba5b7f 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -5155,7 +5155,7 @@ def _names_this_host(host: str) -> bool: The host's own name and its own non-loopback addresses are :func:`_is_own_name_or_address`.""" h = _bare_host(host) - if not h or 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) @@ -5539,7 +5539,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/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index 781028df78..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,9 +16422,9 @@ def check_http_intake_auth(source: Source, name: str, *, posture: HopPosture | N """ if source.type is not ConnectorType.HTTP: return - # A blank host binds loopback: this is HttpSource's own `s.get("host") or "127.0.0.1"` fallback, - # read here because the shared predicate does not take "" as loopback (BACKLOG #5512). - host = str(source.settings.get("host", "127.0.0.1")) or "127.0.0.1" + # 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): diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index a579123ff7..267b3918c2 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -1784,9 +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, and the load refuses only None. A blank one names no host, so - # this guard cannot place the hop and judges it off-box (BACKLOG #5512); the stand-in names the - # setting in the refusal, where a bare "" would leave a gap in the text. 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 @@ -1794,9 +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 "(no [store].server)", posture=posture, context=ctx - ) + _refuse_store_revocation(host=settings.server, posture=posture, context=ctx) return ctx @@ -2020,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). @@ -2061,7 +2056,9 @@ 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, + # The load refuses only a None server. A blank one names no host, so the guard cannot place + # the hop and judges it off-box (BACKLOG #5512); the stand-in names the setting in its text. + 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/http_listener.py b/messagefoundry/transports/http_listener.py index 2b4edd1923..b49c37a989 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 this too, so it judges the address that is really bound. +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/strict_requests.py b/messagefoundry/transports/strict_requests.py index 16a9f5e615..bbc19d096a 100644 --- a/messagefoundry/transports/strict_requests.py +++ b/messagefoundry/transports/strict_requests.py @@ -907,7 +907,7 @@ def _stays_on_the_box(host: str, proxy: str | None) -> bool: ``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, because it names no hop at all.""" - return not proxy and bool(host) and is_loopback_hop_host(host) + return not proxy and is_loopback_hop_host(host) def _refuse_a_cleartext_vault_hop(url: str, proxy: str | None, *, connector: str) -> None: @@ -1496,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 index 09756a49d6..8f3ff5a7ff 100644 --- a/tests/test_b629_5512_loopback_empty_host.py +++ b/tests/test_b629_5512_loopback_empty_host.py @@ -7,12 +7,17 @@ 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: -* a default that really is local: the HTTP listener binds ``127.0.0.1``, so it stays on-box; * 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: the store, a generic ODBC ``server``, and every shared guard and trust anchor. It is judged off-box, so it fails closed. +The fourth 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. """ @@ -25,12 +30,12 @@ import pytest from messagefoundry.auth.trust_anchors import smtp_hop_anchor_spec -from messagefoundry.config.models import ConnectorType, Destination, Source +from messagefoundry.config.models import Destination from messagefoundry.config.settings import ( + INSECURE_TLS_ESCAPE_ENV, AlertsSettings, AuthSettings, LoggingSettings, - StoreBackend, StoreSettings, TlsSettings, _names_this_host, @@ -38,24 +43,23 @@ pinned_host_port, ) from messagefoundry.config.tls_policy import ( + TLS_REVOCATION_ATTESTED_ENV, HopDisposition, HopPosture, InsecureHopRefused, - RevocationHopGuard, TrustAnchorPolicy, active_hop_posture, is_loopback_hop_host, resolve_trust_anchor, ) -from messagefoundry.config.wiring import WiringError -from messagefoundry.pipeline.wiring_runner import check_http_intake_auth from messagefoundry.restricted_file import _loopback_share_problem from messagefoundry.store.postgres import _build_ssl -from messagefoundry.transports.bounded_read import is_never_proxied_host -from messagefoundry.transports.database import DatabaseDestination, DatabaseSource from messagefoundry.transports.mllp import InsecureHopGuard from messagefoundry.transports.strict_requests import _stays_on_the_box from messagefoundry.transports.tcp import TcpDestination +from tests.test_hop_refusal_db_inbound import _GENERIC_CONNECTORS +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 @@ -65,35 +69,8 @@ @pytest.fixture(autouse=True) def _no_escape_env(monkeypatch: pytest.MonkeyPatch) -> None: """Neither relaxation may mask a refusal these tests expect.""" - monkeypatch.delenv("MEFOR_TLS_REVOCATION_ATTESTED", raising=False) - monkeypatch.delenv("MEFOR_ALLOW_INSECURE_TLS", raising=False) - - -# --- the predicate ---------------------------------------------------------------------------- - - -def test_an_empty_host_is_not_loopback() -> None: - assert is_loopback_hop_host("") is False - # CONTROL: the three shapes that really do name this box still do. - assert all(is_loopback_hop_host(h) for h in ("localhost", "127.0.0.1", "::1")) - - -# --- a default that really is local: the inbound HTTP listener -------------------------------- - - -def _http_source(host: str) -> Source: - return Source(type=ConnectorType.HTTP, settings={"host": host, "port": 8080}) - - -def test_a_blank_http_listener_host_binds_loopback_so_the_gate_passes_it() -> None: - """``HttpSource`` reads ``s.get("host") or "127.0.0.1"``, so a blank host binds loopback. The - gate has to read the same default, or it would refuse a listener that is not exposed.""" - check_http_intake_auth(_http_source(""), "IB_HTTP", posture=ENFORCING) - - -def test_the_http_listener_gate_still_refuses_an_exposed_bind() -> None: - with pytest.raises(WiringError, match="non-loopback host"): - check_http_intake_auth(_http_source("0.0.0.0"), "IB_HTTP", posture=ENFORCING) + monkeypatch.delenv(TLS_REVOCATION_ATTESTED_ENV, raising=False) + monkeypatch.delenv(INSECURE_TLS_ESCAPE_ENV, raising=False) # --- an unconfigured feature: the log forwarder ----------------------------------------------- @@ -122,6 +99,11 @@ def test_a_host_that_trims_to_nothing_is_not_a_separate_collector(host: str) -> 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 @@ -139,62 +121,34 @@ def test_a_key_share_whose_server_trims_to_nothing_is_still_refused() -> None: # --- an unknown destination: the store --------------------------------------------------------- -def _pg(server: str | None) -> StoreSettings: - settings = StoreSettings( - backend=StoreBackend.POSTGRES, server=LOOPBACK, database="mefor", username="mefor" - ) +def _store_with_server(server: str | None) -> StoreSettings: # model_copy: the validator refuses a None server, and a blank one is the case it lets through. - return settings.model_copy(update={"server": server}) + 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="revocation"): - _build_ssl(_pg(server), posture=ENFORCING) + 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(_pg(LOOPBACK), posture=ENFORCING) is not None + assert _build_ssl(_store_with_server(LOOPBACK), posture=ENFORCING) is not None # --- an unknown destination: a generic ODBC server ----------------------------------------------- -_GENERIC: dict[str, object] = { - "dialect": "generic", - "odbc_driver": "PostgreSQL Unicode", -} - - -def _generic_dest(server: str) -> Destination: - return Destination( - name="OB_DB_GEN", - type=ConnectorType.DATABASE, - settings={**_GENERIC, "server": server, "statement": "INSERT INTO t (x) VALUES (:x)"}, - ) - - -def _generic_source(server: str) -> Source: - return Source( - name="IB_DB_GEN", - type=ConnectorType.DATABASE, - settings={**_GENERIC, "server": server, "poll_statement": "SELECT 1"}, - ) - - -_GENERIC_CONNECTORS = [(DatabaseDestination, _generic_dest), (DatabaseSource, _generic_source)] - - @pytest.mark.parametrize(("connector", "config"), _GENERIC_CONNECTORS) def test_a_blank_generic_server_is_not_judged_on_box( - connector: Callable[[Any], object], config: Callable[[str], Any] + connector: Callable[[Any], object], config: Callable[..., Any] ) -> None: """A ``server`` of spaces passes the required-setting check and splits to an empty host. The driver is handed that text, so where it dials is not known here. CONTROL: real loopback.""" with active_hop_posture(ENFORCING), pytest.raises(InsecureHopRefused): - connector(config(" ")) + connector(config(server=" ")) with active_hop_posture(ENFORCING): - assert connector(config(LOOPBACK)) + assert connector(config(server=LOOPBACK)) # --- an unknown destination: the shared guards and the trust anchor ----------------------------- @@ -219,18 +173,9 @@ def guard(host: str) -> InsecureHopGuard: def test_the_revocation_guard_refuses_an_empty_host() -> None: - def disposition(host: str) -> HopDisposition | None: - return RevocationHopGuard.capture( - host=host, - cell="test", - description="test", - attested=False, - posture=ENFORCING, - connection=None, - ).disposition() - - assert disposition("") is HopDisposition.REFUSE - assert disposition(LOOPBACK) is HopDisposition.ALLOW + 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: @@ -242,13 +187,7 @@ def test_a_trust_anchor_on_an_empty_host_keeps_the_ca_and_the_crl() -> None: assert (on_box.cafile, on_box.crl_file) == (None, None) -# --- callers that already answer for an empty host themselves ------------------------------------ - - -def test_the_never_proxied_reader_reads_no_host_as_off_box() -> None: - assert is_never_proxied_host("") is False - assert is_never_proxied_host(None) is False - assert is_never_proxied_host(LOOPBACK) is True +# --- 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: @@ -256,8 +195,9 @@ def test_a_vault_hop_with_a_blank_host_does_not_stay_on_the_box() -> None: assert _stays_on_the_box(LOOPBACK, None) is True -def test_a_sidecar_entry_with_no_host_is_not_pinned() -> None: - assert pinned_host_port(":8123") is None +@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) @@ -282,11 +222,7 @@ def test_a_bracketed_loopback_literal_reads_as_remote() -> None: @pytest.mark.parametrize(("host", "refused"), [("[::1]", True), ("::1", False)]) def test_a_bracketed_loopback_tcp_hop_fails_closed(host: str, refused: bool) -> None: - config = Destination( - name="OB_TCP", - type=ConnectorType.TCP, - settings={"host": host, "port": 9100, "framing": "stx_etx"}, - ) + config: Destination = tcp_cfg(host) with active_hop_posture(ENFORCING): if refused: with pytest.raises(InsecureHopRefused): diff --git a/tests/test_loopback_hop_never_proxied.py b/tests/test_loopback_hop_never_proxied.py index 14b16ee286..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: - """``http://./x`` names the host ``.``, which is remote. Stripped, it is the empty host, which - is remote too since BACKLOG #5512.""" +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 not is_loopback_hop_host(host.rstrip(".")) From b5634ea2a9557c0f6e3598880c52be48a90abd53 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 03:06:08 -0600 Subject: [PATCH 03/12] Repair review round one on the empty-host change Drop the empty host from the trust-anchor loopback test, name the blank server in the generic refusal, pin the CLI warn path, and correct the changelog and two ADR lines. Net prose lines: 0. BACKLOG #5512 --- changelog.d/5512.security.md | 11 +++++---- ...hop-refusal-refuse-the-insecure-phi-hop.md | 2 +- ...ss-terminating-and-originating-surfaces.md | 2 +- messagefoundry/transports/database.py | 4 +++- messagefoundry/transports/http_listener.py | 2 +- tests/test_b629_5512_loopback_empty_host.py | 23 ++++++++++++++++++- tests/test_tls_trust_anchor.py | 2 +- 7 files changed, 35 insertions(+), 11 deletions(-) diff --git a/changelog.d/5512.security.md b/changelog.d/5512.security.md index 61e085b9f2..c038d64698 100644 --- a/changelog.d/5512.security.md +++ b/changelog.d/5512.security.md @@ -1,8 +1,9 @@ - **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` and stays on-box, - a log forwarder with no host has no hop to judge, and the log-forwarding and key-share checks - still count a blank value as this host. A PostgreSQL store with a blank `server` and a generic - ODBC `server` of spaces are judged off-box, so each is refused under - `[security].enforcement = enforce` unless the hop is otherwise covered. (`BACKLOG #5512`) + 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 PostgreSQL store + with a blank `server` and a generic ODBC `server` of spaces are judged off-box, so each is + refused under `[security].enforcement = enforce` unless the hop is otherwise covered. + (`BACKLOG #5512`) 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/messagefoundry/transports/database.py b/messagefoundry/transports/database.py index 25634c95ae..4a714b507d 100644 --- a/messagefoundry/transports/database.py +++ b/messagefoundry/transports/database.py @@ -2218,7 +2218,9 @@ def generic_cleartext_hop_guard( reads_comma_port=family in COMMA_PORT_FAMILIES, ) return InsecureHopGuard.capture( - host=host, + # A blank server names no host, so the guard judges it off-box (BACKLOG #5512). The stand-in + # names the setting in the refusal. + host=host or "(no server)", port=port, cell=cell, # The classifier's reason rides in the description so the refusal names WHAT is unset, not just diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index b49c37a989..d0e0d62d99 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -128,7 +128,7 @@ 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 this too, so it judges the address that is really bound. +#: (``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 diff --git a/tests/test_b629_5512_loopback_empty_host.py b/tests/test_b629_5512_loopback_empty_host.py index 8f3ff5a7ff..956f63a699 100644 --- a/tests/test_b629_5512_loopback_empty_host.py +++ b/tests/test_b629_5512_loopback_empty_host.py @@ -25,17 +25,21 @@ from __future__ import annotations from collections.abc import Callable +from types import SimpleNamespace from typing import Any import pytest +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 Destination from messagefoundry.config.settings import ( INSECURE_TLS_ESCAPE_ENV, + AiSettings, AlertsSettings, AuthSettings, LoggingSettings, + SecurityEnforcement, StoreSettings, TlsSettings, _names_this_host, @@ -136,6 +140,23 @@ 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 ----------------------------------------------- @@ -145,7 +166,7 @@ def test_a_blank_generic_server_is_not_judged_on_box( ) -> None: """A ``server`` of spaces passes the required-setting check and splits to an empty host. The driver is handed that text, so where it dials is not known here. CONTROL: real loopback.""" - with active_hop_posture(ENFORCING), pytest.raises(InsecureHopRefused): + with active_hop_posture(ENFORCING), pytest.raises(InsecureHopRefused, match="no server"): connector(config(server=" ")) with active_hop_posture(ENFORCING): assert connector(config(server=LOOPBACK)) 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( From f787fc33b997c5f4311989aa33c97e8817b406d0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 03:23:05 -0600 Subject: [PATCH 04/12] Pin the OIDC no-host refusal at both postures The guard now refuses an empty host itself, so the old match could not see the outright refusal go. Net prose lines: 0. The previous commit said 0 and was +3. BACKLOG #5512 PR title: An empty host is no longer loopback on the hop guards (BACKLOG #5512) Banner: PARTIAL. is_loopback_hop_host("") is False and each caller handles empty explicitly. Item 1 is not a bug: [::1] reads as remote, which fails closed. Stays open: item 2, the generic dialect's reading of ::1 and [::1], unmeasured because no allowlisted ODBC driver was available. --- messagefoundry/config/tls_policy.py | 6 +++--- tests/test_hop_refusal_revocation.py | 7 +++++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index 9f2f4260bc..10af816d9b 100644 --- a/messagefoundry/config/tls_policy.py +++ b/messagefoundry/config/tls_policy.py @@ -3607,9 +3607,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). A host this - # function cannot read must not count as on-box, so it gets a name that never does. - 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/tests/test_hop_refusal_revocation.py b/tests/test_hop_refusal_revocation.py index c55d36f4ef..042afa2210 100644 --- a/tests/test_hop_refusal_revocation.py +++ b/tests/test_hop_refusal_revocation.py @@ -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() From 0a81cf33b8c4c9abf010e8cff9d3ee569ac3a6a7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 03:53:21 -0600 Subject: [PATCH 05/12] Refuse a database or store server that names no host A generic ODBC server that names no host could still cross with tls_hop_attested or cleartext_accepted. It is now refused in the connection-string build, at every posture, because a declaration about a hop cannot cover a hop with no destination. A blank [store].server is refused at load on SQL Server, and a value of spaces on Postgres, naming the setting. An empty Postgres server stays: asyncpg 0.32.0 reads it as PGHOST and then its local default, and the revocation guard still judges that hop off-box. Docstrings no longer say a remote reading always fails closed, and the forward_hop_disposition docstring names its early ALLOW. BACKLOG #5512 --- changelog.d/5512.security.md | 9 +- docs/CONFIGURATION.md | 2 +- docs/CONNECTIONS.md | 2 +- docs/adr/README.md | 2 +- messagefoundry/config/settings.py | 13 +- messagefoundry/config/tls_policy.py | 10 +- messagefoundry/store/postgres.py | 7 +- messagefoundry/transports/database.py | 13 +- messagefoundry/transports/db_endpoint.py | 7 ++ tests/test_b629_5512_loopback_empty_host.py | 125 ++++++++++++++++++-- 10 files changed, 159 insertions(+), 31 deletions(-) diff --git a/changelog.d/5512.security.md b/changelog.d/5512.security.md index c038d64698..ca3448ea6b 100644 --- a/changelog.d/5512.security.md +++ b/changelog.d/5512.security.md @@ -3,7 +3,8 @@ 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 PostgreSQL store - with a blank `server` and a generic ODBC `server` of spaces are judged off-box, so each is - refused under `[security].enforcement = enforce` unless the hop is otherwise covered. - (`BACKLOG #5512`) + log-forwarding and key-share checks still count a blank value as this host. A generic ODBC + `server` that names no host is refused at every posture, and neither `tls_hop_attested` nor + `cleartext_accepted` crosses it. A blank `[store].server` is refused at load on SQL Server, and a + value of spaces on PostgreSQL. An empty PostgreSQL `server` still loads, because asyncpg reads it + as `PGHOST` and then its local default, and that hop is judged off-box. (`BACKLOG #5512`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5dc226a7e9..bd5ebc63b9 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 a blank value is refused at load; 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 e381ce553a..e26c3318af 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -2441,7 +2441,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 a value that names no host in front of its first comma (blank, a bare `:port`, `[]`), whatever the posture, `tls_hop_attested` or `cleartext_accepted` | | `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. 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/config/settings.py b/messagefoundry/config/settings.py index cf20ba5b7f..49e51d4b98 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -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. SQL Server would be sent `SERVER=,1433` with no hop guard reading it, + # and asyncpg would try spaces as a host name. An empty Postgres server stays: asyncpg + # reads it as PGHOST, then its local default, and the revocation guard judges that hop + # off-box because it cannot tell which one the driver picked. + if ( + self.server is not None + and not self.server.strip() + and (self.server or self.backend is StoreBackend.SQLSERVER) + ): + raise ValueError(f"[store].server is blank: name the {label} host") return self @field_validator("ssl_root_cert") @@ -5432,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. diff --git a/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index 10af816d9b..3a5017ef5d 100644 --- a/messagefoundry/config/tls_policy.py +++ b/messagefoundry/config/tls_policy.py @@ -2427,16 +2427,18 @@ def is_loopback_hop_host(host: str) -> bool: 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. 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 + 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 as remote and fails closed. + 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.``, diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 267b3918c2..d253d9c857 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -2056,9 +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( - # The load refuses only a None server. A blank one names no host, so the guard cannot place - # the hop and judges it off-box (BACKLOG #5512); the stand-in names the setting in its text. - host=host or "(no [store].server)", + # Empty is PGHOST or asyncpg's local default, and the guard cannot tell which, so it judges + # the hop off-box (BACKLOG #5512). The stand-in names the setting. A padded address keeps + # its padding: trimmed, it could read as loopback, which the driver is not handed. + host=host if host and host.strip() else "(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/database.py b/messagefoundry/transports/database.py index 4a714b507d..35f60b8969 100644 --- a/messagefoundry/transports/database.py +++ b/messagefoundry/transports/database.py @@ -160,6 +160,7 @@ generic_driver_family, generic_hop_endpoint, is_remote_spelling, + names_no_host, odbc_keyword_name, odbc_param, sqlserver_preset_refusal, @@ -1994,7 +1995,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.transports.db_endpoint.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 +2033,10 @@ 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 ValueError(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=";{}") @@ -2218,9 +2225,7 @@ def generic_cleartext_hop_guard( reads_comma_port=family in COMMA_PORT_FAMILIES, ) return InsecureHopGuard.capture( - # A blank server names no host, so the guard judges it off-box (BACKLOG #5512). The stand-in - # names the setting in the refusal. - host=host or "(no server)", + host=host, port=port, cell=cell, # The classifier's reason rides in the description so the refusal names WHAT is unset, not just diff --git a/messagefoundry/transports/db_endpoint.py b/messagefoundry/transports/db_endpoint.py index a1f26a25a6..bb2d508c02 100644 --- a/messagefoundry/transports/db_endpoint.py +++ b/messagefoundry/transports/db_endpoint.py @@ -89,6 +89,13 @@ def split_generic_server(server: str) -> tuple[str, str]: return host.strip(), in_server.strip() +def names_no_host(server: str) -> bool: + """Whether a generic-dialect ``server`` leaves its first host unnamed: blank, a bare port, empty + brackets, or nothing in front of its first comma (BACKLOG #5512). A driver has to pick such a + destination itself, so no reading here can place the hop.""" + return not split_generic_server(server.partition(",")[0])[0] + + 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. diff --git a/tests/test_b629_5512_loopback_empty_host.py b/tests/test_b629_5512_loopback_empty_host.py index 956f63a699..dd796a07c6 100644 --- a/tests/test_b629_5512_loopback_empty_host.py +++ b/tests/test_b629_5512_loopback_empty_host.py @@ -9,8 +9,10 @@ * 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: the store, a generic ODBC ``server``, and every shared guard and trust - anchor. It is judged off-box, so it fails closed. +* 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. The fourth 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 @@ -25,10 +27,12 @@ from __future__ import annotations from collections.abc import Callable +from contextlib import nullcontext 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 @@ -40,6 +44,7 @@ AuthSettings, LoggingSettings, SecurityEnforcement, + StoreBackend, StoreSettings, TlsSettings, _names_this_host, @@ -58,10 +63,11 @@ ) from messagefoundry.restricted_file import _loopback_share_problem from messagefoundry.store.postgres import _build_ssl +from messagefoundry.transports.database import DatabaseDestination, DatabaseSource from messagefoundry.transports.mllp import InsecureHopGuard from messagefoundry.transports.strict_requests import _stays_on_the_box from messagefoundry.transports.tcp import TcpDestination -from tests.test_hop_refusal_db_inbound import _GENERIC_CONNECTORS +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 @@ -160,18 +166,113 @@ def test_a_cli_store_open_at_warn_warns_on_a_store_with_no_server( # --- an unknown destination: a generic ODBC server ----------------------------------------------- +#: Each passes the required-setting check, and none names a host in front of its first comma. +_GENERIC_SERVERS_NAMING_NO_HOST = [" ", ":5432", "[]", "[ ]:5432", ",1433", " ,db.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_blank_generic_server_is_not_judged_on_box( - connector: Callable[[Any], object], config: Callable[..., Any] +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: - """A ``server`` of spaces passes the required-setting check and splits to an empty host. The - driver is handed that text, so where it dials is not known here. CONTROL: real loopback.""" - with active_hop_posture(ENFORCING), pytest.raises(InsecureHopRefused, match="no server"): - connector(config(server=" ")) - with active_hop_posture(ENFORCING): + """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) if posture else nullcontext(), + pytest.raises(ValueError, match="names no host"), + ): + connector(config(server=server)) + with active_hop_posture(posture) if posture else nullcontext(): assert connector(config(server=LOOPBACK)) +@pytest.mark.parametrize( + "declared", + [ + {"tls_hop_attested": True, "tls_hop_attested_reason": "a segment the engine cannot see"}, + {"cleartext_accepted": True, "cleartext_reason": "a hop accepted as cleartext"}, + ], + ids=["attested", "accepted"], +) +def test_no_declaration_covers_a_generic_hop_with_no_named_host(declared: dict[str, Any]) -> None: + """Either declaration is about a hop, and this one has no destination to be about. CONTROL: the + same declaration still crosses on a named remote host.""" + with active_hop_posture(ENFORCING), pytest.raises(ValueError, match="names no host"): + DatabaseDestination(_generic_dest(server=" ", **declared)) + with active_hop_posture(ENFORCING): + assert DatabaseDestination(_generic_dest(server=REMOTE, **declared)) + + +def test_an_attested_inbound_poll_with_no_named_host_is_refused() -> None: + declared: dict[str, Any] = { + "tls_hop_attested": True, + "tls_hop_attested_reason": "a segment the engine cannot see", + } + with active_hop_posture(ENFORCING), pytest.raises(ValueError, match="names no host"): + DatabaseSource(_generic_source(server=" ", **declared)) + with active_hop_posture(ENFORCING): + assert DatabaseSource(_generic_source(server=REMOTE, **declared)) + + +def test_a_tls_mode_does_not_stand_in_for_a_named_host() -> None: + """The cleartext guard stands down on a TLS mode, so the refusal has to sit in front of it.""" + params = {"odbc_params": {"sslmode": "verify-full"}} + with active_hop_posture(ENFORCING), pytest.raises(ValueError, match="names no host"): + DatabaseDestination(_generic_dest(server=" ", **params)) + with active_hop_posture(ENFORCING): + assert DatabaseDestination(_generic_dest(server=REMOTE, **params)) + + +# --- what a blank [store].server means on each backend ------------------------------------------ + + +def _store_on(backend: StoreBackend, server: str) -> StoreSettings: + return StoreSettings(backend=backend, server=server, database="d", username="u") + + +@pytest.mark.parametrize("server", ["", " ", "\t"]) +def test_a_sql_server_store_refuses_a_blank_server_and_names_the_setting(server: str) -> None: + """It would send ``SERVER=,1433``, and no hop guard reads the SQL Server store's host.""" + with pytest.raises(ValidationError, match=r"\[store\]\.server is blank"): + _store_on(StoreBackend.SQLSERVER, server) + assert _store_on(StoreBackend.SQLSERVER, "db.example").server == "db.example" + + +@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 is blank"): + _store_on(StoreBackend.POSTGRES, server) + + +def test_a_postgres_store_keeps_an_empty_server() -> None: + """Empty has a meaning here: asyncpg reads ``PGHOST``, then its local default. The hop is still + judged off-box (``test_a_store_with_no_server_is_not_judged_on_box``).""" + assert _store_on(StoreBackend.POSTGRES, "").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 + + +def test_the_store_guard_names_the_setting_for_a_server_of_spaces() -> None: + """Built past the load refusal, so the guard's own text is what is read.""" + with pytest.raises(InsecureHopRefused, match=r"to \(no \[store\]\.server\):"): + _build_ssl(_store_with_server(" "), posture=ENFORCING) + + +def test_the_store_guard_does_not_trim_a_padded_host_onto_loopback() -> None: + """The stand-in is for a value with nothing in it. A padded address is not loopback as written, + and trimming it here would open the on-box carve-out.""" + with pytest.raises(InsecureHopRefused, match="127"): + _build_ssl(_store_with_server(f" {LOOPBACK} "), posture=ENFORCING) + + # --- an unknown destination: the shared guards and the trust anchor ----------------------------- @@ -230,7 +331,7 @@ def test_an_smtp_relay_with_no_host_reads_no_internal_ca() -> None: assert smtp_hop_anchor_spec(relay, AuthSettings(), tls) is not None -# --- row item 1: a bracketed literal reads as remote, which fails closed ------------------------- +# --- row item 1: a bracketed literal reads as remote --------------------------------------------- def test_a_bracketed_loopback_literal_reads_as_remote() -> None: @@ -242,7 +343,7 @@ def test_a_bracketed_loopback_literal_reads_as_remote() -> None: @pytest.mark.parametrize(("host", "refused"), [("[::1]", True), ("::1", False)]) -def test_a_bracketed_loopback_tcp_hop_fails_closed(host: str, refused: bool) -> None: +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: From c9d2ef3c3a8b1c0b038c10faac31ad33ed24fb68 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 04:09:56 -0600 Subject: [PATCH 06/12] Simplify the no-host refusal and its tests The generic refusal now raises InsecureHopRefused, the type the start route and the existing no-host test already handle. The Postgres guard goes back to a plain stand-in for an empty host, since the load refuses a value of spaces. The tests reuse the shared store builder and one parametrized case. BACKLOG #5512 --- messagefoundry/store/postgres.py | 5 +- messagefoundry/transports/database.py | 4 +- tests/test_b629_5512_loopback_empty_host.py | 83 +++++++-------------- 3 files changed, 31 insertions(+), 61 deletions(-) diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index d253d9c857..780d7f9b4c 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -2057,9 +2057,8 @@ def _refuse_store_revocation( nowhere to load.""" RevocationHopGuard.capture( # Empty is PGHOST or asyncpg's local default, and the guard cannot tell which, so it judges - # the hop off-box (BACKLOG #5512). The stand-in names the setting. A padded address keeps - # its padding: trimmed, it could read as loopback, which the driver is not handed. - host=host if host and host.strip() else "(no [store].server)", + # 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/database.py b/messagefoundry/transports/database.py index 35f60b8969..6be5c861fe 100644 --- a/messagefoundry/transports/database.py +++ b/messagefoundry/transports/database.py @@ -2036,7 +2036,9 @@ def _build_odbc_dsn(s: dict[str, Any], *, connection: str | None = None) -> str: # 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 ValueError(f"{where}DATABASE server names no host; name the host to connect to") + 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=";{}") diff --git a/tests/test_b629_5512_loopback_empty_host.py b/tests/test_b629_5512_loopback_empty_host.py index dd796a07c6..3090b5fd21 100644 --- a/tests/test_b629_5512_loopback_empty_host.py +++ b/tests/test_b629_5512_loopback_empty_host.py @@ -27,7 +27,6 @@ from __future__ import annotations from collections.abc import Callable -from contextlib import nullcontext from types import SimpleNamespace from typing import Any @@ -181,78 +180,61 @@ def test_a_generic_server_naming_no_host_is_refused_at_every_posture( ) -> 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) if posture else nullcontext(), - pytest.raises(ValueError, match="names no host"), - ): + with active_hop_posture(posture), pytest.raises(InsecureHopRefused, match="names no host"): connector(config(server=server)) - with active_hop_posture(posture) if posture else nullcontext(): + 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( - "declared", + ("connector", "config", "declared"), [ - {"tls_hop_attested": True, "tls_hop_attested_reason": "a segment the engine cannot see"}, - {"cleartext_accepted": True, "cleartext_reason": "a hop accepted as cleartext"}, + (DatabaseDestination, _generic_dest, _ATTESTED), + (DatabaseDestination, _generic_dest, _ACCEPTED), + (DatabaseDestination, _generic_dest, _TLS_MODE), + (DatabaseSource, _generic_source, _ATTESTED), ], - ids=["attested", "accepted"], + ids=["outbound-attested", "outbound-accepted", "outbound-tls-mode", "inbound-attested"], ) -def test_no_declaration_covers_a_generic_hop_with_no_named_host(declared: dict[str, Any]) -> None: - """Either declaration is about a hop, and this one has no destination to be about. CONTROL: the - same declaration still crosses on a named remote host.""" - with active_hop_posture(ENFORCING), pytest.raises(ValueError, match="names no host"): - DatabaseDestination(_generic_dest(server=" ", **declared)) - with active_hop_posture(ENFORCING): - assert DatabaseDestination(_generic_dest(server=REMOTE, **declared)) - - -def test_an_attested_inbound_poll_with_no_named_host_is_refused() -> None: - declared: dict[str, Any] = { - "tls_hop_attested": True, - "tls_hop_attested_reason": "a segment the engine cannot see", - } - with active_hop_posture(ENFORCING), pytest.raises(ValueError, match="names no host"): - DatabaseSource(_generic_source(server=" ", **declared)) - with active_hop_posture(ENFORCING): - assert DatabaseSource(_generic_source(server=REMOTE, **declared)) - - -def test_a_tls_mode_does_not_stand_in_for_a_named_host() -> None: - """The cleartext guard stands down on a TLS mode, so the refusal has to sit in front of it.""" - params = {"odbc_params": {"sslmode": "verify-full"}} - with active_hop_posture(ENFORCING), pytest.raises(ValueError, match="names no host"): - DatabaseDestination(_generic_dest(server=" ", **params)) +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 DatabaseDestination(_generic_dest(server=REMOTE, **params)) + assert connector(config(server=REMOTE, **declared)) # --- what a blank [store].server means on each backend ------------------------------------------ -def _store_on(backend: StoreBackend, server: str) -> StoreSettings: - return StoreSettings(backend=backend, server=server, database="d", username="u") - - @pytest.mark.parametrize("server", ["", " ", "\t"]) def test_a_sql_server_store_refuses_a_blank_server_and_names_the_setting(server: str) -> None: """It would send ``SERVER=,1433``, and no hop guard reads the SQL Server store's host.""" with pytest.raises(ValidationError, match=r"\[store\]\.server is blank"): - _store_on(StoreBackend.SQLSERVER, server) - assert _store_on(StoreBackend.SQLSERVER, "db.example").server == "db.example" + _pg(server, backend=StoreBackend.SQLSERVER) + assert _pg("db.example", backend=StoreBackend.SQLSERVER).server == "db.example" @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 is blank"): - _store_on(StoreBackend.POSTGRES, server) + _pg(server) def test_a_postgres_store_keeps_an_empty_server() -> None: """Empty has a meaning here: asyncpg reads ``PGHOST``, then its local default. The hop is still judged off-box (``test_a_store_with_no_server_is_not_judged_on_box``).""" - assert _store_on(StoreBackend.POSTGRES, "").server == "" + assert _pg("").server == "" @pytest.mark.parametrize("server", ["", " "]) @@ -260,19 +242,6 @@ def test_a_sqlite_store_has_no_server_to_refuse(server: str) -> None: assert StoreSettings(backend=StoreBackend.SQLITE, server=server).server == server -def test_the_store_guard_names_the_setting_for_a_server_of_spaces() -> None: - """Built past the load refusal, so the guard's own text is what is read.""" - with pytest.raises(InsecureHopRefused, match=r"to \(no \[store\]\.server\):"): - _build_ssl(_store_with_server(" "), posture=ENFORCING) - - -def test_the_store_guard_does_not_trim_a_padded_host_onto_loopback() -> None: - """The stand-in is for a value with nothing in it. A padded address is not loopback as written, - and trimming it here would open the on-box carve-out.""" - with pytest.raises(InsecureHopRefused, match="127"): - _build_ssl(_store_with_server(f" {LOOPBACK} "), posture=ENFORCING) - - # --- an unknown destination: the shared guards and the trust anchor ----------------------------- From d54328f5e1f027a1e23e675b1e49dcb48c973531 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 04:27:29 -0600 Subject: [PATCH 07/12] Refuse every unnamed host on the generic and SQL Server readings Review round one found the refusal narrower than its reason. A generic server with an empty entry after a comma passed it, and a SQL Server store accepted `,1433`, `:1433` and `[]`. Both now use one predicate. An empty Postgres server still loads. Also corrects the _build_connection docstring and two test comments, and states the asyncpg reading once, in the CONFIGURATION server row. Net prose lines in docs and the changelog: 0. BACKLOG #5512 --- changelog.d/5512.security.md | 8 ++--- docs/CONFIGURATION.md | 2 +- docs/CONNECTIONS.md | 2 +- messagefoundry/config/settings.py | 23 +++++++------ messagefoundry/store/postgres.py | 5 +-- messagefoundry/transports/database.py | 3 +- messagefoundry/transports/db_endpoint.py | 8 ++--- tests/test_b629_5512_loopback_empty_host.py | 38 ++++++++++++++------- 8 files changed, 54 insertions(+), 35 deletions(-) diff --git a/changelog.d/5512.security.md b/changelog.d/5512.security.md index ca3448ea6b..5c48e5fd68 100644 --- a/changelog.d/5512.security.md +++ b/changelog.d/5512.security.md @@ -4,7 +4,7 @@ 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` that names no host is refused at every posture, and neither `tls_hop_attested` nor - `cleartext_accepted` crosses it. A blank `[store].server` is refused at load on SQL Server, and a - value of spaces on PostgreSQL. An empty PostgreSQL `server` still loads, because asyncpg reads it - as `PGHOST` and then its local default, and that hop is judged off-box. (`BACKLOG #5512`) + `server` that leaves a host unnamed is refused at every posture, and neither `tls_hop_attested` + nor `cleartext_accepted` crosses it. A SQL Server `[store].server` that names no host is refused + at load, and so is a PostgreSQL value of spaces. 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 bd5ebc63b9..6ae0f91257 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`, where a blank value is refused at load; 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) | +| `server`, `port` | str/int | — / 1433 | server DBs (required for `sqlserver`, where a value that names no host, such as a blank one, `:1433` or `[]`, is refused at load; 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 e26c3318af..2a38842715 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -2441,7 +2441,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, and so is a value that names no host in front of its first comma (blank, a bare `:port`, `[]`), whatever the posture, `tls_hop_attested` or `cleartext_accepted` | +| `server` | plain | printable ASCII, and none of `;`, `{`, `}`, `=`, `"`, `'`; `None` is refused, and so is a value that leaves a host unnamed (blank, a bare `:port`, `[]`, an empty entry on either side of a comma), whatever the posture, `tls_hop_attested` or `cleartext_accepted` | | `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. diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 49e51d4b98..76ee704911 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -1233,16 +1233,19 @@ 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. SQL Server would be sent `SERVER=,1433` with no hop guard reading it, - # and asyncpg would try spaces as a host name. An empty Postgres server stays: asyncpg - # reads it as PGHOST, then its local default, and the revocation guard judges that hop - # off-box because it cannot tell which one the driver picked. - if ( - self.server is not None - and not self.server.strip() - and (self.server or self.backend is StoreBackend.SQLSERVER) - ): - raise ValueError(f"[store].server is blank: name the {label} host") + # 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: + # Here, not at module level: importing the transports package loads this module. + from messagefoundry.transports.db_endpoint import names_no_host + + 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") diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 780d7f9b4c..b4b770340c 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -2056,8 +2056,9 @@ def _refuse_store_revocation( returned ``True`` and passed ``None`` here, because asyncpg built that context and a CRL had nowhere to load.""" RevocationHopGuard.capture( - # Empty is PGHOST or asyncpg's local default, and the guard cannot tell which, so it judges - # the hop off-box (BACKLOG #5512). The stand-in names the setting. + # 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=( diff --git a/messagefoundry/transports/database.py b/messagefoundry/transports/database.py index 6be5c861fe..d9c79cf0e3 100644 --- a/messagefoundry/transports/database.py +++ b/messagefoundry/transports/database.py @@ -2258,7 +2258,8 @@ 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 names no host, 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 bb2d508c02..6b0ed1dace 100644 --- a/messagefoundry/transports/db_endpoint.py +++ b/messagefoundry/transports/db_endpoint.py @@ -90,10 +90,10 @@ def split_generic_server(server: str) -> tuple[str, str]: def names_no_host(server: str) -> bool: - """Whether a generic-dialect ``server`` leaves its first host unnamed: blank, a bare port, empty - brackets, or nothing in front of its first comma (BACKLOG #5512). A driver has to pick such a - destination itself, so no reading here can place the hop.""" - return not split_generic_server(server.partition(",")[0])[0] + """Whether ``server`` leaves a host unnamed: blank, a bare port, empty brackets, or an empty + entry on either side of a comma (BACKLOG #5512). A driver has to pick such a destination + itself, so no reading here can place the hop.""" + return not all(split_generic_server(entry)[0] for entry in server.split(",")) def _exact_split(text: str) -> tuple[str, str] | None: diff --git a/tests/test_b629_5512_loopback_empty_host.py b/tests/test_b629_5512_loopback_empty_host.py index 3090b5fd21..8b7dfc5417 100644 --- a/tests/test_b629_5512_loopback_empty_host.py +++ b/tests/test_b629_5512_loopback_empty_host.py @@ -14,7 +14,7 @@ * no destination at all: a generic ODBC ``server`` naming no host and a blank SQL Server store are refused whatever the posture or declaration. -The fourth meaning, a default that really is local, is the HTTP listener's: a blank host binds +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 @@ -131,7 +131,7 @@ def test_a_key_share_whose_server_trims_to_nothing_is_still_refused() -> None: def _store_with_server(server: str | None) -> StoreSettings: - # model_copy: the validator refuses a None server, and a blank one is the case it lets through. + # 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}) @@ -165,8 +165,17 @@ def test_a_cli_store_open_at_warn_warns_on_a_store_with_no_server( # --- an unknown destination: a generic ODBC server ----------------------------------------------- -#: Each passes the required-setting check, and none names a host in front of its first comma. -_GENERIC_SERVERS_NAMING_NO_HOST = [" ", ":5432", "[]", "[ ]:5432", ",1433", " ,db.example"] +#: Each passes the required-setting check, and each leaves a host unnamed. +_GENERIC_SERVERS_NAMING_NO_HOST = [ + " ", + ":5432", + "[]", + "[ ]:5432", + ",1433", + " ,db.example", + "db.example,", + "db.example,,other.example", +] @pytest.mark.parametrize("server", _GENERIC_SERVERS_NAMING_NO_HOST) @@ -216,24 +225,29 @@ def test_nothing_declared_covers_a_generic_hop_with_no_named_host( # --- what a blank [store].server means on each backend ------------------------------------------ -@pytest.mark.parametrize("server", ["", " ", "\t"]) -def test_a_sql_server_store_refuses_a_blank_server_and_names_the_setting(server: str) -> None: - """It would send ``SERVER=,1433``, and no hop guard reads the SQL Server store's host.""" - with pytest.raises(ValidationError, match=r"\[store\]\.server is blank"): +@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) - assert _pg("db.example", backend=StoreBackend.SQLSERVER).server == "db.example" + + +@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 is blank"): + with pytest.raises(ValidationError, match=r"\[store\]\.server names no host"): _pg(server) def test_a_postgres_store_keeps_an_empty_server() -> None: - """Empty has a meaning here: asyncpg reads ``PGHOST``, then its local default. The hop is still - judged off-box (``test_a_store_with_no_server_is_not_judged_on_box``).""" + """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 == "" From a0cac52ab43ec70c3ed1e51ba3a3b40a98fb2648 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 04:42:11 -0600 Subject: [PATCH 08/12] Say which unnamed-host spellings the refusal catches Review round two showed the docs and changelog claiming more than the predicate does: a protocol prefix with no host, such as `tcp:`, reads as naming the host `tcp`. The claims now list what is refused and name that gap. No behaviour changes. Net prose lines in docs and the changelog: +1. BACKLOG #5512 Proposed PR title: An empty host is no longer loopback on the hop guards (BACKLOG #5512) Proposed ledger banner: PARTIAL. is_loopback_hop_host("") is False and each caller handles an empty host. A generic ODBC server that is blank, a bare port, empty brackets or has an empty comma entry is refused at every posture. The same values are refused at load on a SQL Server store, and spaces on Postgres. An empty Postgres server still loads, judged off-box. Row item 1 (bracketed [::1]) is not a defect: it reads as remote. STAYS OPEN: row item 2 (generic ::1 reading, unmeasured); #6617's 127.0.0.1:1433 colon half; the SQL Server DATABASE preset still sends a server naming no host; a bare protocol prefix (tcp:) counts as a host; the store takes a comma port or instance name in server; Postgres accepts :5432 and []; check_http_tls_exposure reads a blank listener host as non-loopback (fails closed); explicit host=None on a direct HTTP Source; validating a SQL Server store imports the transports package. --- changelog.d/5512.security.md | 9 +++++---- docs/CONFIGURATION.md | 2 +- docs/CONNECTIONS.md | 2 +- messagefoundry/transports/database.py | 3 ++- messagefoundry/transports/db_endpoint.py | 9 ++++++--- 5 files changed, 15 insertions(+), 10 deletions(-) diff --git a/changelog.d/5512.security.md b/changelog.d/5512.security.md index 5c48e5fd68..64ca1b2696 100644 --- a/changelog.d/5512.security.md +++ b/changelog.d/5512.security.md @@ -4,7 +4,8 @@ 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` that leaves a host unnamed is refused at every posture, and neither `tls_hop_attested` - nor `cleartext_accepted` crosses it. A SQL Server `[store].server` that names no host is refused - at load, and so is a PostgreSQL value of spaces. An empty PostgreSQL `server` still loads, and - that hop is judged off-box. (`BACKLOG #5512`) + `server` that is blank, a bare `:port` or `[]`, or has an empty entry beside a comma is refused + at every posture, and neither `tls_hop_attested` nor `cleartext_accepted` crosses it. 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 6ae0f91257..d963fb0a7a 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`, where a value that names no host, such as a blank one, `:1433` or `[]`, is refused at load; 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) | +| `server`, `port` | str/int | — / 1433 | server DBs (required for `sqlserver`, where a blank value, a bare `:1433`, `[]` or an empty entry beside a comma is refused at load, 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 2a38842715..1b00f6c79e 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -2441,7 +2441,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, and so is a value that leaves a host unnamed (blank, a bare `:port`, `[]`, an empty entry on either side of a comma), whatever the posture, `tls_hop_attested` or `cleartext_accepted` | +| `server` | plain | printable ASCII, and none of `;`, `{`, `}`, `=`, `"`, `'`; `None` is refused, and so is a blank value, a bare `:port`, `[]`, or an empty entry on either side of a comma, whatever the posture, `tls_hop_attested` or `cleartext_accepted`. 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. diff --git a/messagefoundry/transports/database.py b/messagefoundry/transports/database.py index d9c79cf0e3..97873877e6 100644 --- a/messagefoundry/transports/database.py +++ b/messagefoundry/transports/database.py @@ -2259,7 +2259,8 @@ def _build_connection( 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. The exception is a generic ``server`` - that names no host, which :func:`_build_odbc_dsn` refuses at every posture (BACKLOG #5512). + that :func:`~messagefoundry.transports.db_endpoint.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 6b0ed1dace..d973a65f70 100644 --- a/messagefoundry/transports/db_endpoint.py +++ b/messagefoundry/transports/db_endpoint.py @@ -90,9 +90,12 @@ def split_generic_server(server: str) -> tuple[str, str]: def names_no_host(server: str) -> bool: - """Whether ``server`` leaves a host unnamed: blank, a bare port, empty brackets, or an empty - entry on either side of a comma (BACKLOG #5512). A driver has to pick such a destination - itself, so no reading here can place the hop.""" + """Whether ``server`` is blank, a bare port or empty brackets, or has an empty entry on either + side of a comma (BACKLOG #5512). A driver has to pick such a destination itself, so no reading + here can place the hop. + + **Not every value with no host.** A single colon reads as ``host:port``, so a protocol prefix + with nothing after it, such as ``tcp:``, counts as naming the host ``tcp``.""" return not all(split_generic_server(entry)[0] for entry in server.split(",")) From c54681e360475d2e30ad554180be0e2ad657a34a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 05:09:10 -0600 Subject: [PATCH 09/12] Refuse a SQL Server preset server naming no host; move the host reading to hostlist BACKLOG #5512. Three repairs to the empty-host work. 1. names_no_host and split_generic_server move to the leaf messagefoundry.hostlist module, so StoreSettings no longer imports the transports package when it validates a SQL Server store. A subprocess test pins that. 2. The SQL Server preset (Database, DatabasePoll, DatabaseLookup, DatabaseRef) refuses a server that names no host, at every posture and whatever an attestation says, in _build_dsn, which all four entry points reach. 3. names_no_host also refuses text made only of brackets, colons and digits that is no IPv6 literal, such as [,] and :1433:. The refused spellings are now stated as "at least" in the docstring, docs/CONFIGURATION.md, docs/CONNECTIONS.md and the changelog; a protocol prefix such as tcp: is still named as not caught. Proposed PR title: An empty host is no longer loopback on the hop guards (BACKLOG #5512) Proposed banner: PARTIAL. Open: a SQL Server store still accepts \SQLEXPRESS and host,1444; Postgres still accepts :5432 and []; check_http_tls_exposure; an explicit host=None; row item 2 (the generic ::1 and [::1] reading); the colon half of #6617 item 7; bare protocol prefixes such as tcp: are not caught. --- changelog.d/5512.security.md | 11 +- docs/CONFIGURATION.md | 2 +- docs/CONNECTIONS.md | 2 +- messagefoundry/config/settings.py | 5 +- messagefoundry/hostlist.py | 56 ++++++++++- messagefoundry/transports/database.py | 17 +++- messagefoundry/transports/db_endpoint.py | 33 +----- tests/test_b629_5512_loopback_empty_host.py | 106 +++++++++++++++++++- 8 files changed, 183 insertions(+), 49 deletions(-) diff --git a/changelog.d/5512.security.md b/changelog.d/5512.security.md index 64ca1b2696..8dc8b8a24a 100644 --- a/changelog.d/5512.security.md +++ b/changelog.d/5512.security.md @@ -4,8 +4,11 @@ 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` that is blank, a bare `:port` or `[]`, or has an empty entry beside a comma is refused - at every posture, and neither `tls_hop_attested` nor `cleartext_accepted` crosses it. 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. + `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. At least a blank value, a bare `:port`, + `[]`, an empty entry beside a comma, and text made only of brackets, colons and digits that is + no IPv6 literal, such as `[,]` or `:1433:`, name no host. 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 d963fb0a7a..d2dbb26f75 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`, where a blank value, a bare `:1433`, `[]` or an empty entry beside a comma is refused at load, 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) | +| `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 text made only of brackets, colons and digits that is no IPv6 literal (such as `[,]` or `:1433:`) are refused at load, 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 1b00f6c79e..e4a009908e 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -2441,7 +2441,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, and so is a blank value, a bare `:port`, `[]`, or an empty entry on either side of a comma, whatever the posture, `tls_hop_attested` or `cleartext_accepted`. A protocol prefix with no host after it, such as `tcp:`, is not caught | +| `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 text made only of brackets, colons and digits that is no IPv6 literal (such as `[,]` or `:1433:`), whatever the posture, `tls_hop_attested` or `cleartext_accepted`; the SQL Server preset (`Database`, `DatabasePoll`, `DatabaseLookup`, `DatabaseRef`) refuses the same spellings the same way. 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. diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 76ee704911..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 @@ -1238,9 +1238,6 @@ def _require_server_db_fields(self) -> StoreSettings: # `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: - # Here, not at module level: importing the transports package loads this module. - from messagefoundry.transports.db_endpoint import names_no_host - unnamed = names_no_host(server) else: unnamed = bool(server) and not server.strip() diff --git a/messagefoundry/hostlist.py b/messagefoundry/hostlist.py index 51e776f46d..d95fa84475 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,55 @@ 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 text made only of brackets, colons and digits that + is not 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 not caught.** 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/transports/database.py b/messagefoundry/transports/database.py index 97873877e6..78a3cf6e7b 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, @@ -160,7 +161,6 @@ generic_driver_family, generic_hop_endpoint, is_remote_spelling, - names_no_host, odbc_keyword_name, odbc_param, sqlserver_preset_refusal, @@ -264,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`, @@ -284,6 +285,14 @@ 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: before the preset's own refusals and the weakened-TLS check, and 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" + ) refusal = sqlserver_preset_refusal(s) if refusal is not None: raise ValueError(f"{where}DATABASE {refusal}") @@ -1996,7 +2005,7 @@ def _build_odbc_dsn(s: dict[str, Any], *, connection: str | None = None) -> str: 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``, a ``server`` - that :func:`~messagefoundry.transports.db_endpoint.names_no_host` reads is refused whatever the + 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 @@ -2259,7 +2268,7 @@ def _build_connection( 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. The exception is a generic ``server`` - that :func:`~messagefoundry.transports.db_endpoint.names_no_host` matches, which + 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 diff --git a/messagefoundry/transports/db_endpoint.py b/messagefoundry/transports/db_endpoint.py index d973a65f70..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,37 +68,6 @@ 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 names_no_host(server: str) -> bool: - """Whether ``server`` is blank, a bare port or empty brackets, or has an empty entry on either - side of a comma (BACKLOG #5512). A driver has to pick such a destination itself, so no reading - here can place the hop. - - **Not every value with no host.** A single colon reads as ``host:port``, so a protocol prefix - with nothing after it, such as ``tcp:``, counts as naming the host ``tcp``.""" - return not all(split_generic_server(entry)[0] for entry in server.split(",")) - - 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. diff --git a/tests/test_b629_5512_loopback_empty_host.py b/tests/test_b629_5512_loopback_empty_host.py index 8b7dfc5417..8fb8132f83 100644 --- a/tests/test_b629_5512_loopback_empty_host.py +++ b/tests/test_b629_5512_loopback_empty_host.py @@ -26,6 +26,8 @@ from __future__ import annotations +import subprocess +import sys from collections.abc import Callable from types import SimpleNamespace from typing import Any @@ -35,12 +37,13 @@ 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 Destination +from messagefoundry.config.models import ConnectorType, Destination, Source from messagefoundry.config.settings import ( INSECURE_TLS_ESCAPE_ENV, AiSettings, AlertsSettings, AuthSettings, + EgressSettings, LoggingSettings, SecurityEnforcement, StoreBackend, @@ -60,9 +63,14 @@ 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, DatabaseSource +from messagefoundry.transports.database import ( + DatabaseDestination, + DatabaseLookupExecutor, + DatabaseSource, +) from messagefoundry.transports.mllp import InsecureHopGuard from messagefoundry.transports.strict_requests import _stays_on_the_box from messagefoundry.transports.tcp import TcpDestination @@ -171,6 +179,8 @@ def test_a_cli_store_open_at_warn_warns_on_a_store_with_no_server( ":5432", "[]", "[ ]:5432", + "[,]", + ":1433:", ",1433", " ,db.example", "db.example,", @@ -222,6 +232,98 @@ def test_nothing_declared_covers_a_generic_hop_with_no_named_host( 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. +_PRESET_NO_HOST = [" ", ":1433", "[]", ",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) + + +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)) + + +# --- 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.""" + code = ( + "import sys\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" + ) + done = subprocess.run([sys.executable, "-P", "-c", code], capture_output=True, text=True) + assert done.returncode == 0, done.stderr + + # --- what a blank [store].server means on each backend ------------------------------------------ From 2bdb0f1374ebabde8e2f0e6174743b720df860d3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 05:22:31 -0600 Subject: [PATCH 10/12] Run the SQL Server preset no-host refusal after the preset's comma refusal BACKLOG #5512. The previous commit put the new refusal ahead of sqlserver_preset_refusal, so a server such as "db.test.invalid," got "names no host" instead of the comma remedy, and four tests in tests/test_sqlserver_preset_driver.py failed. The check now runs right after the preset's refusals and still before the weakened-TLS check, at every posture. A value holding a comma meets the preset's comma refusal first, so the test list of preset no-host spellings drops the two comma ones; CONNECTIONS.md says so. Proposed PR title: An empty host is no longer loopback on the hop guards (BACKLOG #5512) Proposed banner: PARTIAL. Open: a SQL Server store still accepts \SQLEXPRESS and host,1444; Postgres still accepts :5432 and []; check_http_tls_exposure; an explicit host=None; row item 2 (the generic ::1 and [::1] reading); the colon half of #6617 item 7; bare protocol prefixes such as tcp: are not caught; a None preset server on DatabaseRef reads as the host None; names_no_host accepts a plain number, host:port with digits only, and :: . --- docs/CONNECTIONS.md | 2 +- messagefoundry/transports/database.py | 14 +++++++------- tests/test_b629_5512_loopback_empty_host.py | 5 +++-- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index e4a009908e..08cf40a14e 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -2441,7 +2441,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, and so is at least a blank value, a bare `:port`, `[]`, an empty entry on either side of a comma, and text made only of brackets, colons and digits that is no IPv6 literal (such as `[,]` or `:1433:`), whatever the posture, `tls_hop_attested` or `cleartext_accepted`; the SQL Server preset (`Database`, `DatabasePoll`, `DatabaseLookup`, `DatabaseRef`) refuses the same spellings the same way. A protocol prefix with no host after it, such as `tcp:`, is not caught | +| `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 text made only of brackets, colons and digits that is no IPv6 literal (such as `[,]` or `:1433:`), whatever the posture, `tls_hop_attested` or `cleartext_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. diff --git a/messagefoundry/transports/database.py b/messagefoundry/transports/database.py index 78a3cf6e7b..cef5df3419 100644 --- a/messagefoundry/transports/database.py +++ b/messagefoundry/transports/database.py @@ -285,17 +285,17 @@ 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: before the preset's own refusals and the weakened-TLS check, and 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. + 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" ) - refusal = sqlserver_preset_refusal(s) - if refusal is not None: - raise ValueError(f"{where}DATABASE {refusal}") 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): diff --git a/tests/test_b629_5512_loopback_empty_host.py b/tests/test_b629_5512_loopback_empty_host.py index 8fb8132f83..10b455bf22 100644 --- a/tests/test_b629_5512_loopback_empty_host.py +++ b/tests/test_b629_5512_loopback_empty_host.py @@ -234,8 +234,9 @@ def test_nothing_declared_covers_a_generic_hop_with_no_named_host( # --- the SQL Server preset: Database, DatabasePoll, DatabaseLookup, DatabaseRef --------------------- -#: "" is left out: the connectors refuse it earlier, as a missing setting. -_PRESET_NO_HOST = [" ", ":1433", "[]", ",1433", "[,]", ":1433:"] +#: "" 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)"} From 6591d904543254654ee3f8c1c95a0f373522dba1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 05:39:55 -0600 Subject: [PATCH 11/12] Refuse a None SQL Server preset server; state the no-host rule as the code reads it An empty host is no longer loopback on the hop guards (BACKLOG #5512) _build_dsn read the preset server as str(s.get("server", "")), so a None server on the DatabaseRef path (no required-setting check ahead of the build) became the host name "None" and SERVER=None,1433. It is now refused at every posture and whatever an attestation says. Tests cover each preset entry point (Database, DatabasePoll, DatabaseLookup, DatabaseRef) and the build itself. The changelog, CONFIGURATION.md, CONNECTIONS.md and the names_no_host docstring now state the real rule: a host made only of brackets, colons and digits that is neither all digits nor an IPv6 literal names no host, while a plain number (1433, [1433]), a digits-only host with a port (1:2, 12:34) and the literals :: and [::] are accepted. Pinned by tests. The preset section of CONNECTIONS.md now carries the refusal in its server rules. The subprocess import test now sets cwd and PYTHONPATH to this tree, a timeout, and asserts the imported module comes from this tree. PARTIAL banner: SHIPPED for is_loopback_hop_host reading an empty host as loopback and the callers' empty-host meanings, and for the generic and SQL Server preset no-host refusals. Still open: names_no_host logic beyond this, the duplicated raise, a SQL Server store accepting \SQLEXPRESS or host,1444, Postgres :5432 and [], check_http_tls_exposure, explicit host=None, row item 2, and #6617's colon half. BACKLOG #5512 --- changelog.d/5512.security.md | 11 ++-- docs/CONFIGURATION.md | 2 +- docs/CONNECTIONS.md | 8 ++- messagefoundry/hostlist.py | 13 ++-- messagefoundry/transports/database.py | 6 ++ tests/test_b629_5512_loopback_empty_host.py | 72 ++++++++++++++++++++- 6 files changed, 100 insertions(+), 12 deletions(-) diff --git a/changelog.d/5512.security.md b/changelog.d/5512.security.md index 8dc8b8a24a..1f9eb49f67 100644 --- a/changelog.d/5512.security.md +++ b/changelog.d/5512.security.md @@ -6,9 +6,12 @@ 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. At least a blank value, a bare `:port`, - `[]`, an empty entry beside a comma, and text made only of brackets, colons and digits that is - no IPv6 literal, such as `[,]` or `:1433:`, name no host. A protocol prefix with nothing after - it, such as `tcp:`, is not caught. The same values are refused at load in a SQL Server + `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 d2dbb26f75..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`, where at least a blank value, a bare `:1433`, `[]`, an empty entry beside a comma, and text made only of brackets, colons and digits that is no IPv6 literal (such as `[,]` or `:1433:`) are refused at load, 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) | +| `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 08cf40a14e..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, and so is at least a blank value, a bare `:port`, `[]`, an empty entry on either side of a comma, and text made only of brackets, colons and digits that is no IPv6 literal (such as `[,]` or `:1433:`), whatever the posture, `tls_hop_attested` or `cleartext_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 | +| `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. diff --git a/messagefoundry/hostlist.py b/messagefoundry/hostlist.py index d95fa84475..32e3c812b9 100644 --- a/messagefoundry/hostlist.py +++ b/messagefoundry/hostlist.py @@ -236,11 +236,14 @@ def _entry_names_no_host(entry: str) -> bool: 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 text made only of brackets, colons and digits that - is not 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 not caught.** A single colon reads as ``host:port``, so a protocol prefix + 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/transports/database.py b/messagefoundry/transports/database.py index cef5df3419..bb29204bc7 100644 --- a/messagefoundry/transports/database.py +++ b/messagefoundry/transports/database.py @@ -285,6 +285,12 @@ 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}") diff --git a/tests/test_b629_5512_loopback_empty_host.py b/tests/test_b629_5512_loopback_empty_host.py index 10b455bf22..c51e73be28 100644 --- a/tests/test_b629_5512_loopback_empty_host.py +++ b/tests/test_b629_5512_loopback_empty_host.py @@ -26,9 +26,11 @@ 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 @@ -295,6 +297,44 @@ def build(**overrides: object) -> object: 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"): @@ -309,19 +349,49 @@ def test_an_attestation_does_not_cover_a_preset_server_with_no_host(server: str) 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" ) - done = subprocess.run([sys.executable, "-P", "-c", code], capture_output=True, text=True) + # 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 From d1d3c844eb1d3791e4d2ef0fd6bd470713d4d424 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 09:53:27 -0600 Subject: [PATCH 12/12] Test: skip only the strict_requests case when requests is absent The repo harness leg installs no requests, and the module-level import of strict_requests failed collection of the whole file. Import it inside the one test that needs it, behind pytest.importorskip, so the other cases still run. BACKLOG #5512 --- tests/test_b629_5512_loopback_empty_host.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_b629_5512_loopback_empty_host.py b/tests/test_b629_5512_loopback_empty_host.py index c51e73be28..e0bd79b090 100644 --- a/tests/test_b629_5512_loopback_empty_host.py +++ b/tests/test_b629_5512_loopback_empty_host.py @@ -74,7 +74,6 @@ DatabaseSource, ) from messagefoundry.transports.mllp import InsecureHopGuard -from messagefoundry.transports.strict_requests import _stays_on_the_box 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 @@ -469,6 +468,10 @@ def test_a_trust_anchor_on_an_empty_host_keeps_the_ca_and_the_crl() -> None: 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