From 9306cb4e89f2b3f2d52b497b307b54bcd09a0d93 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:03:31 -0600 Subject: [PATCH 01/35] [cluster.vip] refuses every address in 0.0.0.0/8, not only 0.0.0.0 (BACKLOG #5132) _vip_address_problems tested ip.is_unspecified, which is true for 0.0.0.0 alone, so 0.1.2.3 loaded as a floating address that no host can bind. The check now refuses the whole "this network" block (RFC 1122, section 3.2.1). Tests add 0.0.0.0, 0.1.2.3 and 0.255.255.254. Verified-by: tests --- messagefoundry/config/settings.py | 13 ++++++++++++- tests/test_settings.py | 4 ++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 944b98e146..8048e22616 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -6791,6 +6791,9 @@ def _vault_revocation_attestation_pair(self) -> SecretsSettings: return self +_THIS_NETWORK_V4 = ipaddress.IPv4Network("0.0.0.0/8") + + def _vip_address_problems(address: str | None, mask: str | None) -> list[str]: if address is None: return ["address is required"] @@ -6798,7 +6801,15 @@ def _vip_address_problems(address: str | None, mask: str | None) -> list[str]: ip = ipaddress.IPv4Address(address) except ValueError: return [f"address must be an IPv4 address (IPv6 is deferred), got {address!r}"] - if ip.is_unspecified or ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved: + # `is_unspecified` is 0.0.0.0 alone; the whole of 0.0.0.0/8 is "this network" (RFC 1122, + # section 3.2.1) and no host can bind an address in it, so the block is refused, not one address. + if ( + ip in _THIS_NETWORK_V4 + or ip.is_loopback + or ip.is_link_local + or ip.is_multicast + or ip.is_reserved + ): return [ f"address {address!r} cannot float between nodes: it is unspecified, loopback, " "link-local, multicast or reserved" diff --git a/tests/test_settings.py b/tests/test_settings.py index 4bd872c43b..e21297adfe 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -1973,6 +1973,10 @@ def test_vip_switched_off_block_is_a_no_op( ('address = "169.254.10.10"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), ('address = "224.0.0.251"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), ('address = "255.255.255.255"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), + # All of 0.0.0.0/8 is "this network" (RFC 1122, section 3.2.1), not only 0.0.0.0 (BACKLOG #5132). + ('address = "0.0.0.0"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), + ('address = "0.1.2.3"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), + ('address = "0.255.255.254"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), ('address = "192.0.2.0"\ninterface = "Ethernet0"\nprefix = 24\n', "network or broadcast"), ('address = "192.0.2.255"\ninterface = "Ethernet0"\nprefix = 24\n', "network or broadcast"), (_VIP_USABLE + "prefix = 0\n", "prefix must be 1-32"), From d51b3c9977fc7632ac163cd823d6c306dfa04a4d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:04:50 -0600 Subject: [PATCH 02/35] docs: [cluster.vip] refusal list names 0.0.0.0/8, not "unspecified" (BACKLOG #5132) CONFIGURATION.md said an unspecified address is refused; the check now refuses the whole 0.0.0.0/8 block, which is wider. Proposed PR title: [cluster.vip] refuses every address in 0.0.0.0/8 (BACKLOG #5132) Proposed vault banner: CLOSED by engine PR : _vip_address_problems refuses all of 0.0.0.0/8, with tests for 0.0.0.0, 0.1.2.3 and 0.255.255.254; CONFIGURATION.md names the block. Verified-by: none --- docs/CONFIGURATION.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3f248b43e6..f2aef6e67d 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3407,8 +3407,8 @@ With `enabled = true` the engine **refuses to load** when: - `[cluster].enabled` is not `true`, or `[store].backend` is not `postgres` or `sqlserver`; - both `prefix` and `netmask` are set, or neither is; -- `address` is missing, is not IPv4, or is unspecified, loopback, link-local, multicast, reserved, or the - network or broadcast address of its own subnet; +- `address` is missing, is not IPv4, or is in 0.0.0.0/8, loopback, link-local, multicast, reserved, or + the network or broadcast address of its own subnet; - `interface` is missing or blank, or has leading or trailing spaces, a double quote, or a non-printable character; - `release_grace_seconds` is below 0, or is not below `[cluster].leader_fence_timeout_seconds`. From c72d5384f98d50d6c31f29a041b84c317e83d44a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:16:27 -0600 Subject: [PATCH 03/35] [cluster.vip] 0.0.0.0/8 refusal uses netaddr's helper and names the block (BACKLOG #5132) Review round 1. The check now calls netaddr.not_a_host_address, the existing helper for 0.0.0.0/8, multicast and reserved, rather than a second copy of the block. The refusal names 0.0.0.0/8, so 0.1.2.3 is no longer refused as "unspecified". The comment's reason was false (Linux can bind most of the block); the reason is that the block is not valid as a destination. A boundary test shows the first address past the block still loads. Verified-by: tests --- messagefoundry/config/settings.py | 18 +++++------------- tests/test_settings.py | 18 ++++++++++++++---- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 8048e22616..3221cc0abf 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -6791,9 +6791,6 @@ def _vault_revocation_attestation_pair(self) -> SecretsSettings: return self -_THIS_NETWORK_V4 = ipaddress.IPv4Network("0.0.0.0/8") - - def _vip_address_problems(address: str | None, mask: str | None) -> list[str]: if address is None: return ["address is required"] @@ -6801,17 +6798,12 @@ def _vip_address_problems(address: str | None, mask: str | None) -> list[str]: ip = ipaddress.IPv4Address(address) except ValueError: return [f"address must be an IPv4 address (IPv6 is deferred), got {address!r}"] - # `is_unspecified` is 0.0.0.0 alone; the whole of 0.0.0.0/8 is "this network" (RFC 1122, - # section 3.2.1) and no host can bind an address in it, so the block is refused, not one address. - if ( - ip in _THIS_NETWORK_V4 - or ip.is_loopback - or ip.is_link_local - or ip.is_multicast - or ip.is_reserved - ): + # `is_unspecified` is 0.0.0.0 alone. The shared helper refuses the whole 0.0.0.0/8 block, which + # is not valid as a destination, so clients could not reach a VIP there (BACKLOG #5132), as well + # as multicast and reserved. + if _not_a_host_address(str(ip)) or ip.is_loopback or ip.is_link_local: return [ - f"address {address!r} cannot float between nodes: it is unspecified, loopback, " + f"address {address!r} cannot float between nodes: it is in 0.0.0.0/8, or is loopback, " "link-local, multicast or reserved" ] if mask is not None: diff --git a/tests/test_settings.py b/tests/test_settings.py index e21297adfe..d01e3b071e 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -4,6 +4,7 @@ from __future__ import annotations +import ipaddress import json import os import re @@ -1973,10 +1974,10 @@ def test_vip_switched_off_block_is_a_no_op( ('address = "169.254.10.10"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), ('address = "224.0.0.251"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), ('address = "255.255.255.255"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), - # All of 0.0.0.0/8 is "this network" (RFC 1122, section 3.2.1), not only 0.0.0.0 (BACKLOG #5132). - ('address = "0.0.0.0"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), - ('address = "0.1.2.3"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), - ('address = "0.255.255.254"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), + # The whole 0.0.0.0/8 block, not only 0.0.0.0 (BACKLOG #5132). + ('address = "0.0.0.0"\ninterface = "Ethernet0"\nprefix = 24\n', "it is in 0.0.0.0/8"), + ('address = "0.1.2.3"\ninterface = "Ethernet0"\nprefix = 24\n', "it is in 0.0.0.0/8"), + ('address = "0.255.255.254"\ninterface = "Ethernet0"\nprefix = 24\n', "it is in 0.0.0.0/8"), ('address = "192.0.2.0"\ninterface = "Ethernet0"\nprefix = 24\n', "network or broadcast"), ('address = "192.0.2.255"\ninterface = "Ethernet0"\nprefix = 24\n', "network or broadcast"), (_VIP_USABLE + "prefix = 0\n", "prefix must be 1-32"), @@ -2003,6 +2004,15 @@ def test_vip_enabled_block_refuses_what_could_not_be_bound( load_settings(config_path=cfg, environ={}) +def test_vip_first_address_past_the_this_network_block_loads(tmp_path: Path) -> None: + # The boundary control for the 0.0.0.0/8 refusals above (BACKLOG #5132): a check wider than the + # one block would refuse this too. Built from its integer, so no routable literal sits in the tree. + first_past = str(ipaddress.IPv4Address(1 << 24 | 1)) + lines = f'address = "{first_past}"\ninterface = "Ethernet0"\nprefix = 24\n' + cfg = _write(tmp_path / "messagefoundry.toml", _VIP_ON + lines) + assert load_settings(config_path=cfg, environ={}).cluster.vip.address == first_past + + def test_vip_release_grace_must_end_inside_the_fence_timeout(tmp_path: Path) -> None: # A grace at the fence timeout (20s by default) could outlast the promoting node's own term. base = _VIP_ON + _VIP_USABLE + "prefix = 24\n" From aaf08a19e754adc32ea400b36017b4ed5ad367c5 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:17:36 -0600 Subject: [PATCH 04/35] docs: [cluster.vip] refusal lists name 0.0.0.0/8; CHANGELOG entry (BACKLOG #5132) Review round 1. CONFIGURATION.md's list read "is in ... loopback"; ADR 0056's still said "unspecified". Both now name the block. The CHANGELOG records the tightening, since 0.5.3 loads such an address. Proposed PR title: [cluster.vip] refuses every address in 0.0.0.0/8 (BACKLOG #5132) Proposed vault banner: CLOSED by engine PR : _vip_address_problems refuses all of 0.0.0.0/8 through netaddr.not_a_host_address, with tests for 0.0.0.0, 0.1.2.3, 0.255.255.254 and a boundary control. Verified-by: none --- CHANGELOG.md | 3 +++ docs/CONFIGURATION.md | 4 ++-- docs/adr/0056-engine-managed-vip-failover.md | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc7e9dd4c1..acc049be6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,9 @@ All notable changes to MessageFoundry are documented here. The format follows `LIN` or `PAT` in a 270), was kept in `X12SegmentError.segment_id` and `message`, as the 0.5.3 notes said. It is now `None`, shown as `?`, and `line` still locates it. Sender text the walk accepts as a segment at that point is still kept. (`BACKLOG #5370`) +- **`[cluster.vip].address` refuses every address in `0.0.0.0/8`.** Only `0.0.0.0` was refused, + so an address such as `0.1.2.3`, which is not valid as a destination, loaded as the floating + address. A config that 0.5.3 loads with such an address now fails to load. (`BACKLOG #5132`) ## [0.5.3] — 2026-11-27 — Early Access diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index f2aef6e67d..acb35fa344 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3407,8 +3407,8 @@ With `enabled = true` the engine **refuses to load** when: - `[cluster].enabled` is not `true`, or `[store].backend` is not `postgres` or `sqlserver`; - both `prefix` and `netmask` are set, or neither is; -- `address` is missing, is not IPv4, or is in 0.0.0.0/8, loopback, link-local, multicast, reserved, or - the network or broadcast address of its own subnet; +- `address` is missing, is not IPv4, is in 0.0.0.0/8, is loopback, link-local, multicast or reserved, + or is the network or broadcast address of its own subnet; - `interface` is missing or blank, or has leading or trailing spaces, a double quote, or a non-printable character; - `release_grace_seconds` is below 0, or is not below `[cluster].leader_fence_timeout_seconds`. diff --git a/docs/adr/0056-engine-managed-vip-failover.md b/docs/adr/0056-engine-managed-vip-failover.md index 7e1586d7c3..815f435978 100644 --- a/docs/adr/0056-engine-managed-vip-failover.md +++ b/docs/adr/0056-engine-managed-vip-failover.md @@ -248,8 +248,8 @@ refused, as in every section. With `enabled = true`, the engine refuses to load: `postgres` or `sqlserver`. The store half is the existing `[cluster]` gate, `ServiceSettings._cluster_requires_server_db`, which any clustered node on SQLite already fails; - with both `prefix` and `netmask`, or with neither; -- with an `address` that is not IPv4, or is unspecified, loopback, link-local, multicast, reserved, or - the network or broadcast address of its own subnet; +- with an `address` that is not IPv4, is in 0.0.0.0/8 (BACKLOG #5132), is loopback, link-local, + multicast or reserved, or is the network or broadcast address of its own subnet; - with a missing or blank `interface`, or one with surrounding whitespace, a double quote, or a non-printable character; - with `release_grace_seconds` below zero, or not below `[cluster].leader_fence_timeout_seconds` From ec581933bfe4200f4a51439b914d8e38f6cf35e3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:29:59 -0600 Subject: [PATCH 05/35] [cluster.vip] address refusal names its own reason (BACKLOG #5132) Review round 2. The check no longer leans on netaddr's helper, whose "at least" blocks serve the navigation lists and could narrow under the VIP unseen. Each class is tested explicitly, 0.0.0.0/8 by its first octet, and the refusal names the one that fired. Tests match each reason, escape the 0.0.0.0/8 pattern, and the boundary control is now 1.0.0.0 itself, as a /32. Verified-by: tests --- messagefoundry/config/settings.py | 20 ++++++++++++-------- tests/test_settings.py | 23 +++++++++++++---------- 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 3221cc0abf..581837918c 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -6798,14 +6798,18 @@ def _vip_address_problems(address: str | None, mask: str | None) -> list[str]: ip = ipaddress.IPv4Address(address) except ValueError: return [f"address must be an IPv4 address (IPv6 is deferred), got {address!r}"] - # `is_unspecified` is 0.0.0.0 alone. The shared helper refuses the whole 0.0.0.0/8 block, which - # is not valid as a destination, so clients could not reach a VIP there (BACKLOG #5132), as well - # as multicast and reserved. - if _not_a_host_address(str(ip)) or ip.is_loopback or ip.is_link_local: - return [ - f"address {address!r} cannot float between nodes: it is in 0.0.0.0/8, or is loopback, " - "link-local, multicast or reserved" - ] + # `is_unspecified` is 0.0.0.0 alone, so the whole 0.0.0.0/8 block is tested by its first octet. + # RFC 1122 forbids an address there as a destination, even where an OS can be set to bind one, + # so a VIP there is not one clients should be sent to (BACKLOG #5132). + for refused, reason in ( + (ip.packed[0] == 0, "in 0.0.0.0/8"), + (ip.is_loopback, "loopback"), + (ip.is_link_local, "link-local"), + (ip.is_multicast, "multicast"), + (ip.is_reserved, "reserved"), + ): + if refused: + return [f"address {address!r} cannot float between nodes: it is {reason}"] if mask is not None: net = ipaddress.IPv4Network(f"{address}/{mask}", strict=False) # A /31 or /32 has no network or broadcast address; every address in it is a host. diff --git a/tests/test_settings.py b/tests/test_settings.py index d01e3b071e..b428a90e35 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -1877,6 +1877,7 @@ def test_cluster_acquire_delay_accepts_the_bound_itself() -> None: _VIP_PG = '[store]\nbackend = "postgres"\nserver = "pg"\ndatabase = "d"\nusername = "u"\n' _VIP_ON = _VIP_PG + "[cluster]\nenabled = true\n[cluster.vip]\nenabled = true\n" _VIP_USABLE = 'address = "192.0.2.50"\ninterface = "Ethernet0"\n' +_IN_THIS_NETWORK = re.escape("cannot float between nodes: it is in 0.0.0.0/8") def test_vip_absent_section_is_off(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: @@ -1970,14 +1971,14 @@ def test_vip_switched_off_block_is_a_no_op( ('interface = "Ethernet0"\nprefix = 24\n', "address is required"), ('address = "192.0.2"\ninterface = "Ethernet0"\nprefix = 24\n', "IPv4 address"), ('address = "2001:db8::50"\ninterface = "Ethernet0"\nprefix = 24\n', "IPv4 address"), - ('address = "127.0.0.1"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), - ('address = "169.254.10.10"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), - ('address = "224.0.0.251"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), - ('address = "255.255.255.255"\ninterface = "Ethernet0"\nprefix = 24\n', "cannot float"), + ('address = "127.0.0.1"\ninterface = "Ethernet0"\nprefix = 24\n', "float.*it is loopback"), + ('address = "169.254.10.10"\ninterface = "Ethernet0"\nprefix = 24\n', "it is link-local"), + ('address = "224.0.0.251"\ninterface = "Ethernet0"\nprefix = 24\n', "it is multicast"), + ('address = "255.255.255.255"\ninterface = "Ethernet0"\nprefix = 24\n', "it is reserved"), # The whole 0.0.0.0/8 block, not only 0.0.0.0 (BACKLOG #5132). - ('address = "0.0.0.0"\ninterface = "Ethernet0"\nprefix = 24\n', "it is in 0.0.0.0/8"), - ('address = "0.1.2.3"\ninterface = "Ethernet0"\nprefix = 24\n', "it is in 0.0.0.0/8"), - ('address = "0.255.255.254"\ninterface = "Ethernet0"\nprefix = 24\n', "it is in 0.0.0.0/8"), + ('address = "0.0.0.0"\ninterface = "Ethernet0"\nprefix = 24\n', _IN_THIS_NETWORK), + ('address = "0.1.2.3"\ninterface = "Ethernet0"\nprefix = 24\n', _IN_THIS_NETWORK), + ('address = "0.255.255.254"\ninterface = "Ethernet0"\nprefix = 24\n', _IN_THIS_NETWORK), ('address = "192.0.2.0"\ninterface = "Ethernet0"\nprefix = 24\n', "network or broadcast"), ('address = "192.0.2.255"\ninterface = "Ethernet0"\nprefix = 24\n', "network or broadcast"), (_VIP_USABLE + "prefix = 0\n", "prefix must be 1-32"), @@ -2006,9 +2007,11 @@ def test_vip_enabled_block_refuses_what_could_not_be_bound( def test_vip_first_address_past_the_this_network_block_loads(tmp_path: Path) -> None: # The boundary control for the 0.0.0.0/8 refusals above (BACKLOG #5132): a check wider than the - # one block would refuse this too. Built from its integer, so no routable literal sits in the tree. - first_past = str(ipaddress.IPv4Address(1 << 24 | 1)) - lines = f'address = "{first_past}"\ninterface = "Ethernet0"\nprefix = 24\n' + # one block would refuse this too. A /32 has no network address to refuse, so the true first + # address past the block is the control. Built from its integer, so no routable literal sits in + # the tree. + first_past = str(ipaddress.IPv4Address(1 << 24)) + lines = f'address = "{first_past}"\ninterface = "Ethernet0"\nprefix = 32\n' cfg = _write(tmp_path / "messagefoundry.toml", _VIP_ON + lines) assert load_settings(config_path=cfg, environ={}).cluster.vip.address == first_past From 0e5ff8c33bcbffcfc99594b6e9ba9886202da6ce Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:31:14 -0600 Subject: [PATCH 06/35] docs: ADR 0056 records the 0.0.0.0/8 refusal as a dated amendment (BACKLOG #5132) Review round 2. ADRs are append-only history, so the ratified bullet keeps its words and carries a dated amendment note instead of being rewritten. Proposed PR title: [cluster.vip] refuses every address in 0.0.0.0/8 (BACKLOG #5132) Proposed vault banner: CLOSED by engine PR : _vip_address_problems refuses all of 0.0.0.0/8 and names the reason that fired, with tests for 0.0.0.0, 0.1.2.3, 0.255.255.254 and a 1.0.0.0 boundary control. Verified-by: none --- docs/adr/0056-engine-managed-vip-failover.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/adr/0056-engine-managed-vip-failover.md b/docs/adr/0056-engine-managed-vip-failover.md index 815f435978..a38e6f4af8 100644 --- a/docs/adr/0056-engine-managed-vip-failover.md +++ b/docs/adr/0056-engine-managed-vip-failover.md @@ -248,8 +248,9 @@ refused, as in every section. With `enabled = true`, the engine refuses to load: `postgres` or `sqlserver`. The store half is the existing `[cluster]` gate, `ServiceSettings._cluster_requires_server_db`, which any clustered node on SQLite already fails; - with both `prefix` and `netmask`, or with neither; -- with an `address` that is not IPv4, is in 0.0.0.0/8 (BACKLOG #5132), is loopback, link-local, - multicast or reserved, or is the network or broadcast address of its own subnet; +- with an `address` that is not IPv4, or is unspecified, loopback, link-local, multicast, reserved, or + the network or broadcast address of its own subnet (amended 2026-12-01, BACKLOG #5132: the + unspecified test now covers the whole 0.0.0.0/8 block, not only 0.0.0.0); - with a missing or blank `interface`, or one with surrounding whitespace, a double quote, or a non-printable character; - with `release_grace_seconds` below zero, or not below `[cluster].leader_fence_timeout_seconds` From 760d9657c4a395183748ed8bcb5e6520c0ec4668 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:48:43 -0600 Subject: [PATCH 07/35] [auth] oidc_allowed_username_domains of only blanks refuses in both forms (BACKLOG #5131) A blank MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS over a real TOML list loaded as the empty default, so the UPN suffix check moved to [auth].ad_domain with no output; the same blanks as a TOML list disabled that fallback instead. The setting now has its own claim-compared list validator: both forms are stripped with blanks dropped, and a value that names something but holds only blanks is refused at load, without quoting it. The unset default still falls back to ad_domain. Step 1 took the refusal arm, so no ruling is owed. Verified-by: tests --- messagefoundry/config/settings.py | 23 ++++++++++--- tests/test_auth_oidc.py | 56 ++++++++++++++++++++++++++----- tests/test_settings.py | 5 ++- 3 files changed, 68 insertions(+), 16 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 581837918c..09d7872148 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -4378,7 +4378,6 @@ def _check_recovery_count(cls, value: int) -> int: "oidc_allowed_endpoints", "oidc_scopes", "oidc_signing_algorithms", - "oidc_allowed_username_domains", mode="before", ) @classmethod @@ -4389,6 +4388,23 @@ def _split_oidc_lists(cls, v: object) -> object: # list-form cleanup to the claim-value lists below). return _normalise_claim_value_list(v) if isinstance(v, str) else v + @field_validator("oidc_allowed_username_domains", mode="before") + @classmethod + def _username_domains_name_a_suffix(cls, v: object) -> object: + # Compared with a token claim, so both forms are normalised as the claim-value lists are + # (BACKLOG #2325). BACKLOG #5131: a value that names something but holds only blanks is + # refused in both forms. Dropped, it would read as the empty default and move the check to + # [auth].ad_domain, a suffix the value never named; kept, it disabled that fallback in the + # TOML form only. The default empty list still falls back. The value is not quoted. + out = _normalise_claim_value_list(v) + if out == [] and (isinstance(v, str) or (isinstance(v, list | tuple) and v)): + raise ValueError( + "[auth].oidc_allowed_username_domains holds only blank entries, so it names no UPN " + "suffix; list at least one suffix, or leave the setting unset to fall back to " + "[auth].ad_domain" + ) + return out + @field_validator( "oidc_mfa_amr_values", "oidc_required_acr_values", @@ -5032,9 +5048,8 @@ def effective_oidc_username_domains(self) -> tuple[str, ...]: # name the engine resolves, and a UPN suffix may be non-ASCII or hold an underscore, # both of which the shared rule refuses. upn_suffix_key is the form the claim is compared # in, so a change to one side of this compare cannot stop or start a match on its own. - # A TOML list of only blanks still takes this arm: it gives () and keeps ad_domain out, so - # with OIDC enabled and stripping on the load refusal above fires even when ad_domain is - # set. The env string form lost its blanks at the split, so it falls back instead. + # A list of only blanks, in either form, is refused at its field (BACKLOG #5131), so a + # non-empty list here names a suffix. The blank filter stays for a model built past that. if self.oidc_allowed_username_domains: return tuple( upn_suffix_key(d.strip()) for d in self.oidc_allowed_username_domains if d.strip() diff --git a/tests/test_auth_oidc.py b/tests/test_auth_oidc.py index 79959b3be7..b22dca6f64 100644 --- a/tests/test_auth_oidc.py +++ b/tests/test_auth_oidc.py @@ -21,17 +21,19 @@ from dataclasses import replace from decimal import Decimal from fractions import Fraction +from pathlib import Path from types import MappingProxyType, SimpleNamespace from typing import Any import pytest from cryptography.hazmat.primitives.asymmetric import ec, rsa +from pydantic import ValidationError from messagefoundry.auth import oidc from messagefoundry.auth.oidc import claims as claims_mod from messagefoundry.auth.oidc.jwks import JwksRefreshBusy from messagefoundry.config.models import SignatureAlgorithm -from messagefoundry.config.settings import AuthSettings +from messagefoundry.config.settings import AuthSettings, load_settings from messagefoundry.transports.signing import CompactJwtSigner # --- helpers --------------------------------------------------------------------------------------- @@ -368,16 +370,52 @@ def test_a_blank_ad_domain_is_no_suffix_source(blank: str) -> None: assert AuthSettings(ad_domain=blank).effective_oidc_username_domains == () -def test_a_list_of_only_blanks_keeps_the_fallback_out_and_its_env_form_does_not() -> None: - """A pin of the stated difference, so that changing it is a decision: the TOML form is truthy, - so it suppresses ``ad_domain``, and the env string form loses its blanks at the split. +@pytest.mark.parametrize( + "value", + [[" "], ["", " "], ("\t",), "", " ", " , ,"], + ids=["toml-one-blank", "toml-blanks", "tuple-blank", "env-empty", "env-blank", "env-commas"], +) +def test_a_value_of_only_blanks_refuses_in_both_forms(value: object) -> None: + """BACKLOG #5131. The TOML list of blanks disabled the ``ad_domain`` fallback while the same + blanks in the env string fell back to it, so a blank variable over a real TOML list moved the + check to a suffix the setting never named. Both forms now refuse at load, OIDC on or off. + + Mutation: drop the refusal from ``_username_domains_name_a_suffix``. Red: every id.""" + with pytest.raises(ValidationError, match=r"oidc_allowed_username_domains holds only blank"): + AuthSettings.model_validate( + {"ad_domain": "corp.example", "oidc_allowed_username_domains": value} + ) + + +def test_a_blank_env_value_over_a_real_toml_list_refuses_at_load(tmp_path: Path) -> None: + """The row's own case, end to end: the env layer replaces the TOML list, and a blank variable + no longer loads as the empty default with the check moved to ``ad_domain``. The refusal quotes + nothing of the value, so a canary in it stays out of the error. + + Mutation: drop the refusal. Red: DID NOT RAISE.""" + cfg = tmp_path / "messagefoundry.toml" + cfg.write_text( + '[auth]\nad_domain = "corp.example"\noidc_allowed_username_domains = ["corp.example"]\n', + encoding="utf-8", + ) + canary = " ,\t" + with pytest.raises(ValidationError) as caught: + load_settings(config_path=cfg, environ={"MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS": canary}) + assert "holds only blank entries" in str(caught.value) + assert repr(canary) not in str(caught.value) + + +def test_the_default_empty_list_still_falls_back_and_blanks_beside_a_suffix_drop() -> None: + """The controls for the refusal above: the unset default still takes ``ad_domain``, and a + blank beside a real suffix is dropped in both forms, as the claim-value lists drop it. - Mutation: test the stripped entries, not the list, in the property. Red: the first assertion.""" + Mutation: refuse any list holding a blank. Red: the mixed cases.""" fields = {"ad_domain": "corp.example"} - toml = AuthSettings.model_validate({**fields, "oidc_allowed_username_domains": [" "]}) - assert toml.effective_oidc_username_domains == () - env = AuthSettings.model_validate({**fields, "oidc_allowed_username_domains": " "}) - assert env.effective_oidc_username_domains == ("corp.example",) + assert AuthSettings.model_validate(fields).effective_oidc_username_domains == ("corp.example",) + for value in ([" ", " Other.Example "], " , Other.Example"): + settings = AuthSettings.model_validate({**fields, "oidc_allowed_username_domains": value}) + assert settings.oidc_allowed_username_domains == ["Other.Example"] + assert settings.effective_oidc_username_domains == ("other.example",) def test_the_ad_domain_fallback_keeps_a_non_ascii_suffix_as_written() -> None: diff --git a/tests/test_settings.py b/tests/test_settings.py index b428a90e35..5e4a594a4f 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -1314,9 +1314,8 @@ def test_auth_oidc_disabled_is_default(tmp_path: Path) -> None: _OIDC_ENV, "oidc_allowed_username_domains", ), - # a list of only blanks keeps a real ad_domain out, so this refusal fires with it set, as - # docs/CONFIGURATION.md says. Mutation: skip the refusal while the list is non-empty. - # Red: DID NOT RAISE. + # a list of only blanks is refused at its field with a real ad_domain set (BACKLOG #5131), + # as docs/CONFIGURATION.md says. Mutation: drop that refusal. Red: DID NOT RAISE. ( _OIDC_AD + _OIDC_BLOCK + 'oidc_allowed_username_domains = [" "]\n', _OIDC_ENV, From a20178b8932d318adc6a774a5d7781ee777426e4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:50:18 -0600 Subject: [PATCH 08/35] docs: oidc_allowed_username_domains blanks-only refusal; CHANGELOG (BACKLOG #5131) CONFIGURATION.md described the old split, a TOML list of blanks refusing while the env form fell back. It now states the refusal in both forms. Proposed PR title: [auth] oidc_allowed_username_domains of only blanks refuses in both forms (BACKLOG #5131) Proposed vault banner: CLOSED by engine PR : a blanks-only value refuses at load as a TOML list and as the env string, and the setting moved to its own claim-compared list validator; tests pin both forms, the row's env-over-TOML case and the default fallback. Verified-by: none --- CHANGELOG.md | 4 ++++ docs/CONFIGURATION.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index acc049be6c..afbe270a5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ All notable changes to MessageFoundry are documented here. The format follows - **`[cluster.vip].address` refuses every address in `0.0.0.0/8`.** Only `0.0.0.0` was refused, so an address such as `0.1.2.3`, which is not valid as a destination, loaded as the floating address. A config that 0.5.3 loads with such an address now fails to load. (`BACKLOG #5132`) +- **`[auth].oidc_allowed_username_domains` holding only blanks refuses at load, in both forms.** + A blank `MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS` over a real TOML list loaded as empty and + moved the UPN suffix check to `[auth].ad_domain`. Leave the variable unset to fall back. + (`BACKLOG #5131`) ## [0.5.3] — 2026-11-27 — Early Access diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index acb35fa344..92b99cb442 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -938,7 +938,7 @@ document ([SECURITY-DOCS-POLICY.md](SECURITY-DOCS-POLICY.md)). | `oidc_scopes` | list[str] | `["openid","profile"]` | no `email`, no `offline_access` | | `oidc_signing_algorithms` | list[str] | `["RS256"]` | coerced through the closed JWS algorithm enum | | `oidc_username_claim` / `oidc_username_strip_domain` | str / bool | `preferred_username` / `true` | strip the UPN suffix at the first `@`. The result is a hint only: since ADR 0184 the bound (issuer, sub) pair selects the account | -| `oidc_allowed_username_domains` | list[str] | `[]` | **defence in depth on the username claim.** Since ADR 0184 the bound (issuer, sub) pair selects the account, and the username claim selects none. The suffix is still checked because `preferred_username` is neither unique nor stable (OIDC Core §5.7) and is operator- or even self-editable on many IdPs. Before ADR 0184 this list was the control: without it a guest presenting `Administrator@attacker.example` stripped to `Administrator` and signed in as the on-prem Domain Admin. When `oidc_username_strip_domain` is on, the claim's UPN suffix **must** match one of these. An ASCII suffix matches without regard to case. A suffix with any non-ASCII character matches only as written, capitals included, so copy it from the claim your identity provider sends (BACKLOG #3765). Empty falls back to `ad_domain`; with neither set while stripping is on, `oidc_enabled` is **refused at load** rather than stripping unchecked, and a blank `ad_domain` counts as not set. A TOML list holding only blanks is not empty: it keeps `ad_domain` out, so that refusal fires even with `ad_domain` set, while the same blanks in the env string are dropped and the fallback applies. List the alternate UPN suffixes of a multi-domain forest here | +| `oidc_allowed_username_domains` | list[str] | `[]` | **defence in depth on the username claim.** Since ADR 0184 the bound (issuer, sub) pair selects the account, and the username claim selects none. The suffix is still checked because `preferred_username` is neither unique nor stable (OIDC Core §5.7) and is operator- or even self-editable on many IdPs. Before ADR 0184 this list was the control: without it a guest presenting `Administrator@attacker.example` stripped to `Administrator` and signed in as the on-prem Domain Admin. When `oidc_username_strip_domain` is on, the claim's UPN suffix **must** match one of these. An ASCII suffix matches without regard to case. A suffix with any non-ASCII character matches only as written, capitals included, so copy it from the claim your identity provider sends (BACKLOG #3765). Empty falls back to `ad_domain`; with neither set while stripping is on, `oidc_enabled` is **refused at load** rather than stripping unchecked, and a blank `ad_domain` counts as not set. Both forms are stripped with blanks dropped, and a value holding only blanks, as a TOML list or as the env string (an empty variable included), is **refused at load** rather than read as empty, so a blank variable never moves the check to `ad_domain` (BACKLOG #5131). List the alternate UPN suffixes of a multi-domain forest here | | `oidc_clock_skew_seconds` | int | `60` | wall-clock skew tolerance (0–300) | | `oidc_require_mfa_claim` | bool | `true` | **#99(g) control** — refuse a token with no configured `amr`/`acr`. The engine verifies what the IdP **asserts**, not what it enforced | | `oidc_mfa_amr_values` / `oidc_required_acr_values` | list[str] | `["mfa"]` / `[]` | either family satisfies the gate; both empty with the gate on is refused. Each value is stripped at load and a blank one dropped, in a TOML list as in an env string, so a list of blanks counts as empty ([BACKLOG #2325](BACKLOG.md)) | From 8b57cdce30bbea2be4b2390c57208b1c9a1766e7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:05:00 -0600 Subject: [PATCH 09/35] [auth] blanks-only username domains refuse only with OIDC on, after the type check (BACKLOG #5131) Review round 1. The refusal stopped an engine with OIDC off over a setting nothing reads, unlike the sibling lists; it now fires only with oidc_enabled, and loads as empty otherwise. It runs after the type check, so a set or other iterable pydantic coerces is caught too. The message names the variable, since the TOML file holds a real suffix, and says the fallback needs the setting unset in both places. Tests pin an explicit empty list and OIDC off. Verified-by: tests --- messagefoundry/config/settings.py | 31 ++++++++++----- tests/test_auth_oidc.py | 65 +++++++++++++++++++++++-------- 2 files changed, 70 insertions(+), 26 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 09d7872148..62cc0c94a8 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -4390,18 +4390,29 @@ def _split_oidc_lists(cls, v: object) -> object: @field_validator("oidc_allowed_username_domains", mode="before") @classmethod - def _username_domains_name_a_suffix(cls, v: object) -> object: - # Compared with a token claim, so both forms are normalised as the claim-value lists are - # (BACKLOG #2325). BACKLOG #5131: a value that names something but holds only blanks is - # refused in both forms. Dropped, it would read as the empty default and move the check to - # [auth].ad_domain, a suffix the value never named; kept, it disabled that fallback in the - # TOML form only. The default empty list still falls back. The value is not quoted. - out = _normalise_claim_value_list(v) - if out == [] and (isinstance(v, str) or (isinstance(v, list | tuple) and v)): + def _split_username_domains(cls, v: object) -> object: + # The env string is comma-split with its blanks kept, so the check below can tell a blank + # value from an empty one. + return v.split(",") if isinstance(v, str) else v + + @field_validator("oidc_allowed_username_domains") + @classmethod + def _username_domains_name_a_suffix(cls, v: list[str], info: ValidationInfo) -> list[str]: + # Compared with a token claim, so every form is stripped with blanks dropped, as the + # claim-value lists are (BACKLOG #2325). Run after the type check, so any iterable pydantic + # accepts arrives here as a list. BACKLOG #5131: a value that names something but holds + # only blanks used to disable the [auth].ad_domain fallback as a TOML list, and to fall + # back to it as the env string, so a blank variable over a real TOML list moved the check + # to a suffix the value never named. With OIDC on it now refuses in every form. With OIDC + # off nothing reads the setting, so it loads as empty, as the sibling lists do. Only an + # unset setting or an explicit empty list falls back. The value is not quoted. + out = [item.strip() for item in v if item.strip()] + if v and not out and info.data.get("oidc_enabled", False): raise ValueError( "[auth].oidc_allowed_username_domains holds only blank entries, so it names no UPN " - "suffix; list at least one suffix, or leave the setting unset to fall back to " - "[auth].ad_domain" + "suffix. A blank MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS replaces the TOML list. " + "List at least one suffix, or remove the blank value; to fall back to " + "[auth].ad_domain, leave the setting unset in both places" ) return out diff --git a/tests/test_auth_oidc.py b/tests/test_auth_oidc.py index b22dca6f64..7ea14493a6 100644 --- a/tests/test_auth_oidc.py +++ b/tests/test_auth_oidc.py @@ -370,48 +370,81 @@ def test_a_blank_ad_domain_is_no_suffix_source(blank: str) -> None: assert AuthSettings(ad_domain=blank).effective_oidc_username_domains == () +_OIDC_ON = {"ad_domain": "corp.example", "oidc_enabled": True} + + @pytest.mark.parametrize( "value", - [[" "], ["", " "], ("\t",), "", " ", " , ,"], - ids=["toml-one-blank", "toml-blanks", "tuple-blank", "env-empty", "env-blank", "env-commas"], + [[" "], ["", " "], (" ",), frozenset({" "}), "", " ", " , ,"], + ids=[ + "toml-one-blank", + "toml-blanks", + "tuple-blank", + "frozenset-blank", + "env-empty", + "env-blank", + "env-commas", + ], ) def test_a_value_of_only_blanks_refuses_in_both_forms(value: object) -> None: """BACKLOG #5131. The TOML list of blanks disabled the ``ad_domain`` fallback while the same blanks in the env string fell back to it, so a blank variable over a real TOML list moved the - check to a suffix the setting never named. Both forms now refuse at load, OIDC on or off. + check to a suffix the setting never named. With OIDC on, every form now refuses at load; the + check runs after the type check, so an iterable pydantic coerces is caught too. Mutation: drop the refusal from ``_username_domains_name_a_suffix``. Red: every id.""" with pytest.raises(ValidationError, match=r"oidc_allowed_username_domains holds only blank"): - AuthSettings.model_validate( - {"ad_domain": "corp.example", "oidc_allowed_username_domains": value} - ) + AuthSettings.model_validate({**_OIDC_ON, "oidc_allowed_username_domains": value}) def test_a_blank_env_value_over_a_real_toml_list_refuses_at_load(tmp_path: Path) -> None: """The row's own case, end to end: the env layer replaces the TOML list, and a blank variable - no longer loads as the empty default with the check moved to ``ad_domain``. The refusal quotes - nothing of the value, so a canary in it stays out of the error. + no longer loads as empty with the check moved to ``ad_domain``. The refusal names the variable, + since the TOML file the operator opens holds a real suffix. Mutation: drop the refusal. Red: DID NOT RAISE.""" cfg = tmp_path / "messagefoundry.toml" cfg.write_text( - '[auth]\nad_domain = "corp.example"\noidc_allowed_username_domains = ["corp.example"]\n', + '[auth]\nad_domain = "corp.example"\noidc_enabled = true\n' + 'oidc_allowed_username_domains = ["corp.example"]\n', encoding="utf-8", ) - canary = " ,\t" with pytest.raises(ValidationError) as caught: - load_settings(config_path=cfg, environ={"MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS": canary}) + load_settings(config_path=cfg, environ={"MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS": " "}) assert "holds only blank entries" in str(caught.value) - assert repr(canary) not in str(caught.value) + assert "MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS" in str(caught.value) + + +@pytest.mark.parametrize("value", [[" "], ""], ids=["toml-blank", "env-empty"]) +def test_with_oidc_off_a_blank_value_loads_as_empty(value: object) -> None: + """Nothing reads the setting with OIDC off, so a blank template variable does not stop the + engine, as an empty ``MEFOR_AUTH_OIDC_SCOPES`` does not. + + Mutation: refuse whatever ``oidc_enabled`` holds. Red: both ids.""" + settings = AuthSettings.model_validate( + {"ad_domain": "corp.example", "oidc_allowed_username_domains": value} + ) + assert settings.oidc_allowed_username_domains == [] + +def test_an_unset_or_empty_list_still_falls_back_and_blanks_beside_a_suffix_drop() -> None: + """The controls for the refusal above: the unset default and an explicit empty list still + take ``ad_domain``, and a blank beside a real suffix is dropped in both forms, as the + claim-value lists drop it. -def test_the_default_empty_list_still_falls_back_and_blanks_beside_a_suffix_drop() -> None: - """The controls for the refusal above: the unset default still takes ``ad_domain``, and a - blank beside a real suffix is dropped in both forms, as the claim-value lists drop it. + With OIDC on, this bare section still fails the whole-model OIDC checks, so each value is + read for the field refusal alone: it must not be among the errors. - Mutation: refuse any list holding a blank. Red: the mixed cases.""" + Mutation: refuse every empty result. Red: the explicit empty list. Mutation: refuse any list + holding a blank. Red: the mixed cases.""" + for value in ([], [" ", " Other.Example "], " , Other.Example"): + with pytest.raises(ValidationError) as caught: + AuthSettings.model_validate({**_OIDC_ON, "oidc_allowed_username_domains": value}) + assert "holds only blank" not in str(caught.value) fields = {"ad_domain": "corp.example"} assert AuthSettings.model_validate(fields).effective_oidc_username_domains == ("corp.example",) + explicit = AuthSettings.model_validate({**fields, "oidc_allowed_username_domains": []}) + assert explicit.effective_oidc_username_domains == ("corp.example",) for value in ([" ", " Other.Example "], " , Other.Example"): settings = AuthSettings.model_validate({**fields, "oidc_allowed_username_domains": value}) assert settings.oidc_allowed_username_domains == ["Other.Example"] From 371b92262d3df455b6bebb870ba9d9372fd0ba7f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:05:45 -0600 Subject: [PATCH 10/35] docs: username-domains refusal scoped to OIDC on; fallback needs it unset (BACKLOG #5131) Review round 1. CONFIGURATION.md said "Empty falls back" beside a refusal of an empty variable; it now says unset or an explicit empty list falls back, and scopes the refusal to oidc_enabled. The CHANGELOG says the same and notes TOML entries are now stripped. Proposed PR title: [auth] oidc_allowed_username_domains of only blanks refuses in both forms (BACKLOG #5131) Proposed vault banner: CLOSED by engine PR : with OIDC on, a blanks-only value refuses at load as a TOML list and as the env string, and the setting has its own claim-compared list validator; tests pin both forms, the row's env-over-TOML case, OIDC off and the fallback. Verified-by: none --- CHANGELOG.md | 9 +++++---- docs/CONFIGURATION.md | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index afbe270a5f..ed1fc3b132 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,10 +15,11 @@ All notable changes to MessageFoundry are documented here. The format follows - **`[cluster.vip].address` refuses every address in `0.0.0.0/8`.** Only `0.0.0.0` was refused, so an address such as `0.1.2.3`, which is not valid as a destination, loaded as the floating address. A config that 0.5.3 loads with such an address now fails to load. (`BACKLOG #5132`) -- **`[auth].oidc_allowed_username_domains` holding only blanks refuses at load, in both forms.** - A blank `MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS` over a real TOML list loaded as empty and - moved the UPN suffix check to `[auth].ad_domain`. Leave the variable unset to fall back. - (`BACKLOG #5131`) +- **`[auth].oidc_allowed_username_domains` holding only blanks refuses at load, in both forms, + while `oidc_enabled` is on.** A blank `MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS` over a real TOML + list loaded as empty and moved the UPN suffix check to `[auth].ad_domain`. To fall back to + `ad_domain`, leave the setting unset in the file and the environment. Entries are now stripped + at load, in the TOML form too. (`BACKLOG #5131`) ## [0.5.3] — 2026-11-27 — Early Access diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 92b99cb442..4a499083af 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -938,7 +938,7 @@ document ([SECURITY-DOCS-POLICY.md](SECURITY-DOCS-POLICY.md)). | `oidc_scopes` | list[str] | `["openid","profile"]` | no `email`, no `offline_access` | | `oidc_signing_algorithms` | list[str] | `["RS256"]` | coerced through the closed JWS algorithm enum | | `oidc_username_claim` / `oidc_username_strip_domain` | str / bool | `preferred_username` / `true` | strip the UPN suffix at the first `@`. The result is a hint only: since ADR 0184 the bound (issuer, sub) pair selects the account | -| `oidc_allowed_username_domains` | list[str] | `[]` | **defence in depth on the username claim.** Since ADR 0184 the bound (issuer, sub) pair selects the account, and the username claim selects none. The suffix is still checked because `preferred_username` is neither unique nor stable (OIDC Core §5.7) and is operator- or even self-editable on many IdPs. Before ADR 0184 this list was the control: without it a guest presenting `Administrator@attacker.example` stripped to `Administrator` and signed in as the on-prem Domain Admin. When `oidc_username_strip_domain` is on, the claim's UPN suffix **must** match one of these. An ASCII suffix matches without regard to case. A suffix with any non-ASCII character matches only as written, capitals included, so copy it from the claim your identity provider sends (BACKLOG #3765). Empty falls back to `ad_domain`; with neither set while stripping is on, `oidc_enabled` is **refused at load** rather than stripping unchecked, and a blank `ad_domain` counts as not set. Both forms are stripped with blanks dropped, and a value holding only blanks, as a TOML list or as the env string (an empty variable included), is **refused at load** rather than read as empty, so a blank variable never moves the check to `ad_domain` (BACKLOG #5131). List the alternate UPN suffixes of a multi-domain forest here | +| `oidc_allowed_username_domains` | list[str] | `[]` | **defence in depth on the username claim.** Since ADR 0184 the bound (issuer, sub) pair selects the account, and the username claim selects none. The suffix is still checked because `preferred_username` is neither unique nor stable (OIDC Core §5.7) and is operator- or even self-editable on many IdPs. Before ADR 0184 this list was the control: without it a guest presenting `Administrator@attacker.example` stripped to `Administrator` and signed in as the on-prem Domain Admin. When `oidc_username_strip_domain` is on, the claim's UPN suffix **must** match one of these. An ASCII suffix matches without regard to case. A suffix with any non-ASCII character matches only as written, capitals included, so copy it from the claim your identity provider sends (BACKLOG #3765). Unset, or an explicit empty list, falls back to `ad_domain`; with neither set while stripping is on, `oidc_enabled` is **refused at load** rather than stripping unchecked, and a blank `ad_domain` counts as not set. Both forms are stripped with blanks dropped. With `oidc_enabled` on, a value holding only blanks, as a TOML list or as the env string (an empty variable included), is **refused at load** rather than read as empty, so a blank variable over a real TOML list never moves the check to `ad_domain`; with OIDC off it loads as empty (BACKLOG #5131). List the alternate UPN suffixes of a multi-domain forest here | | `oidc_clock_skew_seconds` | int | `60` | wall-clock skew tolerance (0–300) | | `oidc_require_mfa_claim` | bool | `true` | **#99(g) control** — refuse a token with no configured `amr`/`acr`. The engine verifies what the IdP **asserts**, not what it enforced | | `oidc_mfa_amr_values` / `oidc_required_acr_values` | list[str] | `["mfa"]` / `[]` | either family satisfies the gate; both empty with the gate on is refused. Each value is stripped at load and a blank one dropped, in a TOML list as in an env string, so a list of blanks counts as empty ([BACKLOG #2325](BACKLOG.md)) | From 3e2a6a8d7bea5c5902f3deddfa225a0f1aff0d3e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:16:41 -0600 Subject: [PATCH 11/35] [auth] username-domains refusal reads strip_domain too, and reuses the claim-list helper (BACKLOG #5131) Review round 2. The claim check reads the list only with OIDC on and the suffix stripped, so the refusal now needs both; with strip off a blank template variable loads as empty. The strip and blank drop go through _normalise_claim_value_list, whose docstring names this field. The message no longer asserts an env variable the site may not have set. A test pins the field order the refusal depends on, and the field and property comments match. The tab case is written as an escape. Verified-by: tests --- messagefoundry/config/settings.py | 33 ++++++++++++++++--------- tests/test_auth_oidc.py | 41 +++++++++++++++++++++++++------ 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 62cc0c94a8..89be28b151 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -53,7 +53,7 @@ from datetime import date from enum import Enum from pathlib import Path -from typing import Any, Final, Literal, Self +from typing import Any, Final, Literal, Self, cast from urllib.parse import SplitResult, urlsplit from pydantic import ( @@ -3620,6 +3620,8 @@ def check_kerberos_realm(realm: str) -> str: def _normalise_claim_value_list(v: object) -> object: """An OIDC list setting, stripped with blanks dropped (BACKLOG #2325). Every OIDC list reads its env string through it; only the lists compared with a token claim read a TOML list through it. + ``oidc_allowed_username_domains`` splits its env string itself, keeping the blanks, and runs + its coerced list through this, so it can refuse a blanks-only value (BACKLOG #5131). An env string is comma-split first. A list or tuple keeps its order. A non-string item is left as it is, for the field's own type check to refuse, and anything else passes through.""" @@ -4066,7 +4068,8 @@ class AuthSettings(_Section): # refused. This no longer decides which on-prem account a login reaches: since ADR 0184 the bound # (issuer, sub) pair selects it, and the claim is only a hint in the not-bound refusal. It was that # control before, because `preferred_username` is neither unique nor stable (OIDC Core §5.7) and is - # self-editable on many IdPs. Empty = fall back to [auth].ad_domain; if neither is set while + # self-editable on many IdPs. Unset or [] = fall back to [auth].ad_domain (a blanks-only value is + # refused while the list is read, BACKLOG #5131); if neither is set while # strip_domain is on, oidc_enabled is refused at load rather than stripping unchecked. List the alternate UPN suffixes # of a multi-domain forest here. An ASCII suffix matches without regard to case; one holding a # non-ASCII character matches only as written (upn_suffix_key in domainshape.py). @@ -4403,16 +4406,21 @@ def _username_domains_name_a_suffix(cls, v: list[str], info: ValidationInfo) -> # accepts arrives here as a list. BACKLOG #5131: a value that names something but holds # only blanks used to disable the [auth].ad_domain fallback as a TOML list, and to fall # back to it as the env string, so a blank variable over a real TOML list moved the check - # to a suffix the value never named. With OIDC on it now refuses in every form. With OIDC - # off nothing reads the setting, so it loads as empty, as the sibling lists do. Only an - # unset setting or an explicit empty list falls back. The value is not quoted. - out = [item.strip() for item in v if item.strip()] - if v and not out and info.data.get("oidc_enabled", False): + # to a suffix the value never named. It now refuses in every form while the list is read: + # OIDC on and the suffix stripped (the claim check reads it only then). Otherwise it loads + # as empty, as the sibling lists do. Only an unset setting or an explicit empty list falls + # back. The value is not quoted. Both switches are declared above this field, so info.data + # holds them; tests/test_auth_oidc.py pins that order, since a reorder would fail open. + out = cast(list[str], _normalise_claim_value_list(v)) + read = info.data.get("oidc_enabled", False) and info.data.get( + "oidc_username_strip_domain", True + ) + if v and not out and read: raise ValueError( "[auth].oidc_allowed_username_domains holds only blank entries, so it names no UPN " - "suffix. A blank MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS replaces the TOML list. " - "List at least one suffix, or remove the blank value; to fall back to " - "[auth].ad_domain, leave the setting unset in both places" + "suffix. Where MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS is set, it replaces the " + "TOML list. List at least one suffix; to fall back to [auth].ad_domain, leave the " + "setting unset or empty in the file and unset in the environment" ) return out @@ -5059,8 +5067,9 @@ def effective_oidc_username_domains(self) -> tuple[str, ...]: # name the engine resolves, and a UPN suffix may be non-ASCII or hold an underscore, # both of which the shared rule refuses. upn_suffix_key is the form the claim is compared # in, so a change to one side of this compare cannot stop or start a match on its own. - # A list of only blanks, in either form, is refused at its field (BACKLOG #5131), so a - # non-empty list here names a suffix. The blank filter stays for a model built past that. + # A list of only blanks is refused at its field while the list is read, and loads as empty + # otherwise (BACKLOG #5131), so a non-empty list here names a suffix. The blank filter + # stays for a model built past that. if self.oidc_allowed_username_domains: return tuple( upn_suffix_key(d.strip()) for d in self.oidc_allowed_username_domains if d.strip() diff --git a/tests/test_auth_oidc.py b/tests/test_auth_oidc.py index 7ea14493a6..239cc6bca9 100644 --- a/tests/test_auth_oidc.py +++ b/tests/test_auth_oidc.py @@ -416,15 +416,40 @@ def test_a_blank_env_value_over_a_real_toml_list_refuses_at_load(tmp_path: Path) @pytest.mark.parametrize("value", [[" "], ""], ids=["toml-blank", "env-empty"]) -def test_with_oidc_off_a_blank_value_loads_as_empty(value: object) -> None: - """Nothing reads the setting with OIDC off, so a blank template variable does not stop the - engine, as an empty ``MEFOR_AUTH_OIDC_SCOPES`` does not. +@pytest.mark.parametrize( + "switches", + [{}, {"oidc_enabled": True, "oidc_username_strip_domain": False}], + ids=["oidc-off", "strip-off"], +) +def test_where_the_list_is_not_read_a_blank_value_loads_as_empty( + value: object, switches: dict[str, bool] +) -> None: + """The claim check reads the list only with OIDC on and the suffix stripped, so a blank + template variable elsewhere does not stop the engine, as an empty ``MEFOR_AUTH_OIDC_SCOPES`` + does not. - Mutation: refuse whatever ``oidc_enabled`` holds. Red: both ids.""" - settings = AuthSettings.model_validate( - {"ad_domain": "corp.example", "oidc_allowed_username_domains": value} - ) - assert settings.oidc_allowed_username_domains == [] + Mutation: refuse whatever ``oidc_enabled`` holds. Red: oidc-off. Mutation: drop the strip + test. Red: strip-off.""" + fields = {"ad_domain": "corp.example", "oidc_allowed_username_domains": value, **switches} + try: + settings = AuthSettings.model_validate(fields) + except ValidationError as exc: + # With OIDC on, this bare section fails the whole-model OIDC checks; the field must not. + assert "holds only blank" not in str(exc) + else: + assert settings.oidc_allowed_username_domains == [] + + +def test_the_switches_the_refusal_reads_are_declared_above_the_list() -> None: + """The refusal reads ``oidc_enabled`` and ``oidc_username_strip_domain`` from ``info.data``, + which holds only fields declared above the one being validated. A reorder would make it read + the defaults and never fire, so the order is pinned here. + + Mutation: move ``oidc_enabled`` below the list. Red: this test.""" + order = list(AuthSettings.model_fields) + target = order.index("oidc_allowed_username_domains") + assert order.index("oidc_enabled") < target + assert order.index("oidc_username_strip_domain") < target def test_an_unset_or_empty_list_still_falls_back_and_blanks_beside_a_suffix_drop() -> None: From 5c2c31e124d07670592ee307f65bf57923668d00 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:17:30 -0600 Subject: [PATCH 12/35] docs: username-domains refusal needs stripping on too; CHANGELOG trimmed (BACKLOG #5131) Review round 2. CONFIGURATION.md and the CHANGELOG scope the refusal to OIDC and stripping both on, and say an explicit empty list in the file falls back. The CHANGELOG drops a sentence that changed nothing an operator does. Proposed PR title: [auth] oidc_allowed_username_domains of only blanks refuses in both forms (BACKLOG #5131) Proposed vault banner: CLOSED by engine PR : with OIDC and stripping on, a blanks-only value refuses at load as a TOML list and as the env string, and the setting has its own claim-compared list validator; tests pin both forms, the row's env-over-TOML case, the not-read cases and the fallback. Verified-by: none --- CHANGELOG.md | 8 ++++---- docs/CONFIGURATION.md | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed1fc3b132..70e491a306 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,10 +16,10 @@ All notable changes to MessageFoundry are documented here. The format follows so an address such as `0.1.2.3`, which is not valid as a destination, loaded as the floating address. A config that 0.5.3 loads with such an address now fails to load. (`BACKLOG #5132`) - **`[auth].oidc_allowed_username_domains` holding only blanks refuses at load, in both forms, - while `oidc_enabled` is on.** A blank `MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS` over a real TOML - list loaded as empty and moved the UPN suffix check to `[auth].ad_domain`. To fall back to - `ad_domain`, leave the setting unset in the file and the environment. Entries are now stripped - at load, in the TOML form too. (`BACKLOG #5131`) + while `oidc_enabled` and `oidc_username_strip_domain` are on.** A blank + `MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS` over a real TOML list loaded as empty and moved the + UPN suffix check to `[auth].ad_domain`. To fall back to `ad_domain`, leave the setting unset or + empty in the file and unset in the environment. (`BACKLOG #5131`) ## [0.5.3] — 2026-11-27 — Early Access diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 4a499083af..daadf2a937 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -938,7 +938,7 @@ document ([SECURITY-DOCS-POLICY.md](SECURITY-DOCS-POLICY.md)). | `oidc_scopes` | list[str] | `["openid","profile"]` | no `email`, no `offline_access` | | `oidc_signing_algorithms` | list[str] | `["RS256"]` | coerced through the closed JWS algorithm enum | | `oidc_username_claim` / `oidc_username_strip_domain` | str / bool | `preferred_username` / `true` | strip the UPN suffix at the first `@`. The result is a hint only: since ADR 0184 the bound (issuer, sub) pair selects the account | -| `oidc_allowed_username_domains` | list[str] | `[]` | **defence in depth on the username claim.** Since ADR 0184 the bound (issuer, sub) pair selects the account, and the username claim selects none. The suffix is still checked because `preferred_username` is neither unique nor stable (OIDC Core §5.7) and is operator- or even self-editable on many IdPs. Before ADR 0184 this list was the control: without it a guest presenting `Administrator@attacker.example` stripped to `Administrator` and signed in as the on-prem Domain Admin. When `oidc_username_strip_domain` is on, the claim's UPN suffix **must** match one of these. An ASCII suffix matches without regard to case. A suffix with any non-ASCII character matches only as written, capitals included, so copy it from the claim your identity provider sends (BACKLOG #3765). Unset, or an explicit empty list, falls back to `ad_domain`; with neither set while stripping is on, `oidc_enabled` is **refused at load** rather than stripping unchecked, and a blank `ad_domain` counts as not set. Both forms are stripped with blanks dropped. With `oidc_enabled` on, a value holding only blanks, as a TOML list or as the env string (an empty variable included), is **refused at load** rather than read as empty, so a blank variable over a real TOML list never moves the check to `ad_domain`; with OIDC off it loads as empty (BACKLOG #5131). List the alternate UPN suffixes of a multi-domain forest here | +| `oidc_allowed_username_domains` | list[str] | `[]` | **defence in depth on the username claim.** Since ADR 0184 the bound (issuer, sub) pair selects the account, and the username claim selects none. The suffix is still checked because `preferred_username` is neither unique nor stable (OIDC Core §5.7) and is operator- or even self-editable on many IdPs. Before ADR 0184 this list was the control: without it a guest presenting `Administrator@attacker.example` stripped to `Administrator` and signed in as the on-prem Domain Admin. When `oidc_username_strip_domain` is on, the claim's UPN suffix **must** match one of these. An ASCII suffix matches without regard to case. A suffix with any non-ASCII character matches only as written, capitals included, so copy it from the claim your identity provider sends (BACKLOG #3765). Unset, or an explicit empty list, falls back to `ad_domain`; with neither set while stripping is on, `oidc_enabled` is **refused at load** rather than stripping unchecked, and a blank `ad_domain` counts as not set. Both forms are stripped with blanks dropped. With `oidc_enabled` and stripping on, a value holding only blanks, as a TOML list or as the env string (an empty variable included), is **refused at load** rather than read as empty, so a blank variable over a real TOML list never moves the check to `ad_domain`; otherwise nothing reads the list and it loads as empty (BACKLOG #5131). List the alternate UPN suffixes of a multi-domain forest here | | `oidc_clock_skew_seconds` | int | `60` | wall-clock skew tolerance (0–300) | | `oidc_require_mfa_claim` | bool | `true` | **#99(g) control** — refuse a token with no configured `amr`/`acr`. The engine verifies what the IdP **asserts**, not what it enforced | | `oidc_mfa_amr_values` / `oidc_required_acr_values` | list[str] | `["mfa"]` / `[]` | either family satisfies the gate; both empty with the gate on is refused. Each value is stripped at load and a blank one dropped, in a TOML list as in an env string, so a list of blanks counts as empty ([BACKLOG #2325](BACKLOG.md)) | From 87225b8557a691026c8c593dc1f9d5d9a4b70686 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:31:14 -0600 Subject: [PATCH 13/35] settings: public origin and OIDC host refusals quote no part of the value (BACKLOG #5109) _normalize_public_origin let urlsplit's ValueError through, and its message can quote the netloc, userinfo included; it is now replaced, with no chained cause. The IP-literal refusal quoted the whole origin, which may keep userinfo; the oidc_allowed_endpoints refusal quoted the host, which urlsplit reads from the value. Both now name the setting only. input_hiding.py's "names at least the ones known" read as a census; it now says the list is examples. Canary tests cover each. Proposed PR title: Public origin and OIDC host refusals quote no part of the value (BACKLOG #5109) Proposed vault banner: CLOSED by engine PR : _normalize_public_origin guards urlsplit, the IP-literal and oidc_allowed_endpoints refusals name the setting and quote nothing, with a canary test per field; the input_hiding.py sentence names what it covers. The OIDC loop's bare urlsplit stays #4783's. Verified-by: tests --- messagefoundry/config/input_hiding.py | 7 +- messagefoundry/config/settings.py | 24 +++-- ...st_settings_url_refusals_quote_no_value.py | 98 +++++++++++++++++++ 3 files changed, 118 insertions(+), 11 deletions(-) create mode 100644 tests/test_settings_url_refusals_quote_no_value.py diff --git a/messagefoundry/config/input_hiding.py b/messagefoundry/config/input_hiding.py index b9f57bdfb9..b4ac57768a 100644 --- a/messagefoundry/config/input_hiding.py +++ b/messagefoundry/config/input_hiding.py @@ -62,9 +62,10 @@ def _refuse_without_input(value: Any, handler: ValidatorFunctionWrapHandler) -> validator's own ``PydanticCustomError`` keeps its rendered message only). THIS HIDES THE INPUT ONLY. The message and ``ctx`` stay as raised, and they can quote the value: a validator that quotes what it refused still shows it there, and so does at least one error a library raised - inside a validator. :func:`settings_error_detail` names at least the ones known. None is meant - to hold a secret, but a URL can carry one, so a validator message must name the setting, never - quote a secret value. + inside a validator. :func:`settings_error_detail`'s docstring names some of each, as examples + and not a census: nothing lists every message that quotes a value. None is meant to hold a + secret, but a URL can carry one, so a validator message must name the setting, never quote a + secret value. """ try: return handler(value) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 89be28b151..fabbc053d9 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -2058,7 +2058,15 @@ def _normalize_public_origin(cls, v: str | None) -> str | None: the same-origin comparison is an exact match against the browser's ``Origin`` header.""" if not v: return None - parts = urlsplit(v) + try: + parts = urlsplit(v) + except ValueError: + # urlsplit's own message can quote the netloc, userinfo included (BACKLOG #5109), so + # it is replaced, and `from None` keeps it off the chain. + raise ValueError( + "[security].web_console_public_address is not a URL that parses; it must be a " + "bare origin like 'https://ops.example.com'" + ) from None if ( parts.scheme not in ("http", "https") or not parts.netloc @@ -2253,8 +2261,10 @@ def _check_tls_cert_dependency(self) -> ApiSettings: except ValueError: pass # a DNS name — HSTS is notable, nothing to refuse else: + # The value is not quoted: an origin may keep userinfo, and a password holding an + # unencoded '/' makes urlsplit read the user field as the host (BACKLOG #5109). raise ValueError( - f"[security].web_console_public_address {self.public_origin!r} is an IP literal " + "[security].web_console_public_address names a host that is an IP literal " "while a TLS posture is declared. RFC 6797 §8.1.1 forbids a browser from noting " "an IP-literal host as " "an HSTS host, so the Strict-Transport-Security header would be silently " @@ -4965,10 +4975,9 @@ def given(*values: str | None) -> bool: if parts.username is not None or parts.password is not None: raise ValueError(f"[auth].{name} must not carry a user name or password") if parts.hostname not in allowed: - raise ValueError( - f"[auth].{name} host {parts.hostname!r} is not in oidc_allowed_endpoints " - f"{sorted(allowed)}" - ) + # Neither the host nor the allow-list is quoted: the host is read from the value, + # and the reason above for not quoting the URL holds for it (BACKLOG #5109). + raise ValueError(f"[auth].{name} host is not in oidc_allowed_endpoints") # A gate that can never fire is worse than none: require at least one MFA family populated. if self.oidc_require_mfa_claim and not ( @@ -12282,8 +12291,7 @@ def settings_error_detail(exc: Exception) -> str: THE MESSAGE IS NOT HIDDEN, AND THIS FUNCTION RETURNS IT. A validator that quotes the value it refused still shows it, here and in ``str(exc)``: at least the ``[api].trusted_proxies`` entry - refusals do, several path and enum refusals, and the ``[auth]`` ``oidc_allowed_endpoints`` - refusal, which quotes the host and the allow-list. A URL can carry a credential, so a validator + refusals do, and several path and enum refusals. A URL can carry a credential, so a validator message must name the setting and never quote a secret value. Callers print the returned text to at least stderr, a service log and ``security show``'s JSON. At least the ``[backup]`` and ``[dr]`` URL refusals quote no part of the URL for that reason, the text in front of ``://`` diff --git a/tests/test_settings_url_refusals_quote_no_value.py b/tests/test_settings_url_refusals_quote_no_value.py new file mode 100644 index 0000000000..0776b3eba7 --- /dev/null +++ b/tests/test_settings_url_refusals_quote_no_value.py @@ -0,0 +1,98 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""Refusals of a URL-shaped setting name the setting and quote no part of the value (BACKLOG #5109). + +A URL can carry a credential in its userinfo, and the text urlsplit reads as the host is the +value's own, so a refusal that quotes either prints whatever the operator pasted. Each case below +puts a canary where the value would carry a secret and checks every rendering of the error. +""" + +from __future__ import annotations + +from typing import Any + +import pytest +from pydantic import ValidationError + +from messagefoundry.config.settings import ApiSettings, AuthSettings, settings_error_detail + +_CANARY = "CANARYSECRET5109" + + +def _renderings(exc: ValidationError) -> str: + return "\n".join((str(exc), repr(exc), exc.json(), settings_error_detail(exc))) + + +@pytest.mark.parametrize( + ("origin", "needle"), + [ + # urlsplit refuses these, and its message quotes the netloc or the bracketed host. + (f"https://u:{_CANARY}@h#x", "is not a URL that parses"), + (f"https://u:x@[{_CANARY}]", "is not a URL that parses"), + ], + ids=["nfkc-netloc", "bracketed-host"], +) +def test_an_unparsable_public_origin_refuses_without_quoting_it(origin: str, needle: str) -> None: + """Mutation: drop the try around urlsplit in ``_normalize_public_origin``. Red: both ids, the + canary in urlsplit's own message.""" + with pytest.raises(ValidationError) as caught: + ApiSettings(public_origin=origin) + text = _renderings(caught.value) + assert "web_console_public_address" in text and needle in text + assert _CANARY not in text + assert caught.value.__cause__ is None + + +def test_the_ip_literal_refusal_quotes_no_part_of_the_origin() -> None: + """The origin may keep userinfo, so quoting it whole printed the password. + + Mutation: put ``self.public_origin!r`` back in the refusal. Red: the canary.""" + with pytest.raises(ValidationError) as caught: + ApiSettings( + public_origin=f"https://admin:{_CANARY}@192.0.2.5", + tls_terminated_upstream=True, + trusted_proxies=["127.0.0.1"], + serve_ui=True, + ) + text = _renderings(caught.value) + assert "web_console_public_address names a host that is an IP literal" in text + assert _CANARY not in text + + +def _auth(**over: Any) -> dict[str, Any]: + base: dict[str, Any] = { + "ad_enabled": True, + "ad_server": "ldaps://dc.corp.example", + "ad_user_search_base": "DC=corp,DC=example", + "ad_bind_dn": "CN=svc,DC=corp,DC=example", + "ad_bind_password": "not-a-real-password", + "ad_domain": "corp.example", + "oidc_enabled": True, + "oidc_issuer": "https://idp.example", + "oidc_client_id": "mefor-console", + "oidc_client_secret": "not-a-real-secret", + "oidc_token_endpoint_auth_method": "client_secret_post", + "oidc_authorization_endpoint": "https://idp.example/authorize", + "oidc_token_endpoint": "https://idp.example/token", + "oidc_jwks_uri": "https://idp.example/jwks", + "oidc_allowed_endpoints": ["idp.example"], + } + base.update(over) + return base + + +@pytest.mark.parametrize( + "field", + ["oidc_issuer", "oidc_authorization_endpoint", "oidc_token_endpoint", "oidc_jwks_uri"], +) +def test_the_allowed_endpoints_refusal_quotes_neither_host_nor_list(field: str) -> None: + """With an unencoded '/' in a password, urlsplit reads the user field as the host, so quoting + the host printed the credential's head. + + Mutation: put ``parts.hostname!r`` back in the refusal. Red: every field.""" + with pytest.raises(ValidationError) as caught: + AuthSettings.model_validate(_auth(**{field: f"https://{_CANARY}.example/x"})) + text = _renderings(caught.value) + assert f"[auth].{field} host is not in oidc_allowed_endpoints" in text + assert _CANARY not in text + assert "idp.example']" not in text From 2765e7a2772ba93428f7e6f4502caffbe21ea3d0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:45:52 -0600 Subject: [PATCH 14/35] settings: public-origin parse refusal raised after its handler; canaries case-folded (BACKLOG #5109) Review round 1. `from None` left urlsplit's error, which quotes the netloc, on __context__ of the error pydantic keeps in ctx, and it failed test_from_none_is_not_redaction; the refusal is now raised after the handler ends. The canaries were upper case while the origin and host are lower-cased before a refusal could quote them, so they could not fire; they are lower case, compared case-folded, and the kept error's chain is read too. The OIDC refusal shows the allow-list again, the operator's own host names. The IP-literal comment's second reason could not occur there and is gone. Verified-by: tests --- messagefoundry/config/settings.py | 23 +++++---- ...st_settings_url_refusals_quote_no_value.py | 47 +++++++++++-------- 2 files changed, 43 insertions(+), 27 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index fabbc053d9..f8c445fa8a 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -2058,15 +2058,19 @@ def _normalize_public_origin(cls, v: str | None) -> str | None: the same-origin comparison is an exact match against the browser's ``Origin`` header.""" if not v: return None + # urlsplit's own message can quote the netloc, userinfo included (BACKLOG #5109), so the + # refusal is raised after the handler ends: `from None` would still leave that error on + # __context__ (#1796), as _split_origin and urlscreen._split_or_refuse also note. + parts: SplitResult | None try: parts = urlsplit(v) except ValueError: - # urlsplit's own message can quote the netloc, userinfo included (BACKLOG #5109), so - # it is replaced, and `from None` keeps it off the chain. + parts = None + if parts is None: raise ValueError( "[security].web_console_public_address is not a URL that parses; it must be a " "bare origin like 'https://ops.example.com'" - ) from None + ) if ( parts.scheme not in ("http", "https") or not parts.netloc @@ -2261,8 +2265,8 @@ def _check_tls_cert_dependency(self) -> ApiSettings: except ValueError: pass # a DNS name — HSTS is notable, nothing to refuse else: - # The value is not quoted: an origin may keep userinfo, and a password holding an - # unencoded '/' makes urlsplit read the user field as the host (BACKLOG #5109). + # The value is not quoted: the normalized origin keeps any userinfo, password + # included (BACKLOG #5109; keeping it is #4840's). raise ValueError( "[security].web_console_public_address names a host that is an IP literal " "while a TLS posture is declared. RFC 6797 §8.1.1 forbids a browser from noting " @@ -4975,9 +4979,12 @@ def given(*values: str | None) -> bool: if parts.username is not None or parts.password is not None: raise ValueError(f"[auth].{name} must not carry a user name or password") if parts.hostname not in allowed: - # Neither the host nor the allow-list is quoted: the host is read from the value, - # and the reason above for not quoting the URL holds for it (BACKLOG #5109). - raise ValueError(f"[auth].{name} host is not in oidc_allowed_endpoints") + # The host is not quoted: it is read from the value, so the reason above for not + # quoting the URL holds for it (BACKLOG #5109). The allow-list is the operator's + # own host names, so it is still shown. + raise ValueError( + f"[auth].{name} host is not in oidc_allowed_endpoints {sorted(allowed)}" + ) # A gate that can never fire is worse than none: require at least one MFA family populated. if self.oidc_require_mfa_claim and not ( diff --git a/tests/test_settings_url_refusals_quote_no_value.py b/tests/test_settings_url_refusals_quote_no_value.py index 0776b3eba7..9ca931e847 100644 --- a/tests/test_settings_url_refusals_quote_no_value.py +++ b/tests/test_settings_url_refusals_quote_no_value.py @@ -16,37 +16,47 @@ from messagefoundry.config.settings import ApiSettings, AuthSettings, settings_error_detail -_CANARY = "CANARYSECRET5109" +#: Lower case, and compared case-folded: the origin and a URL's host are lower-cased before a +#: refusal could quote them, so an upper-case canary would miss the leak it is there to catch. +_CANARY = "canarysecret5109" def _renderings(exc: ValidationError) -> str: - return "\n".join((str(exc), repr(exc), exc.json(), settings_error_detail(exc))) + """Every rendering of the error, case-folded, plus the ``__context__`` and ``__cause__`` of + any exception pydantic kept in an error's ``ctx``.""" + parts = [str(exc), repr(exc), exc.json(), settings_error_detail(exc)] + for err in exc.errors(include_url=False): + kept = (err.get("ctx") or {}).get("error") + if isinstance(kept, BaseException): + parts += [repr(kept), repr(kept.__context__), repr(kept.__cause__)] + return "\n".join(parts).casefold() @pytest.mark.parametrize( - ("origin", "needle"), + "origin", [ - # urlsplit refuses these, and its message quotes the netloc or the bracketed host. - (f"https://u:{_CANARY}@h#x", "is not a URL that parses"), - (f"https://u:x@[{_CANARY}]", "is not a URL that parses"), + # urlsplit refuses these, and its message quotes the netloc or the bracketed host. U+FF03 + # is a full-width number sign, which NFKC turns into a fragment marker. + f"https://u:{_CANARY}@h#x", + f"https://u:x@[{_CANARY}]", ], ids=["nfkc-netloc", "bracketed-host"], ) -def test_an_unparsable_public_origin_refuses_without_quoting_it(origin: str, needle: str) -> None: +def test_an_unparsable_public_origin_refuses_without_quoting_it(origin: str) -> None: """Mutation: drop the try around urlsplit in ``_normalize_public_origin``. Red: both ids, the - canary in urlsplit's own message.""" + canary in urlsplit's own message. Mutation: raise inside the handler with ``from None``. Red: + both ids, the canary on the kept error's ``__context__``.""" with pytest.raises(ValidationError) as caught: ApiSettings(public_origin=origin) text = _renderings(caught.value) - assert "web_console_public_address" in text and needle in text + assert "web_console_public_address is not a url that parses" in text assert _CANARY not in text - assert caught.value.__cause__ is None def test_the_ip_literal_refusal_quotes_no_part_of_the_origin() -> None: - """The origin may keep userinfo, so quoting it whole printed the password. + """The normalized origin keeps userinfo, so quoting it whole printed the password. - Mutation: put ``self.public_origin!r`` back in the refusal. Red: the canary.""" + Mutation: append ``self.public_origin!r`` to the refusal. Red: the canary.""" with pytest.raises(ValidationError) as caught: ApiSettings( public_origin=f"https://admin:{_CANARY}@192.0.2.5", @@ -55,7 +65,7 @@ def test_the_ip_literal_refusal_quotes_no_part_of_the_origin() -> None: serve_ui=True, ) text = _renderings(caught.value) - assert "web_console_public_address names a host that is an IP literal" in text + assert "web_console_public_address names a host that is an ip literal" in text assert _CANARY not in text @@ -85,14 +95,13 @@ def _auth(**over: Any) -> dict[str, Any]: "field", ["oidc_issuer", "oidc_authorization_endpoint", "oidc_token_endpoint", "oidc_jwks_uri"], ) -def test_the_allowed_endpoints_refusal_quotes_neither_host_nor_list(field: str) -> None: - """With an unencoded '/' in a password, urlsplit reads the user field as the host, so quoting - the host printed the credential's head. +def test_the_allowed_endpoints_refusal_quotes_no_host(field: str) -> None: + """The host is read from the value, so quoting it prints whatever the operator pasted there. + The allow-list is the operator's own host names and is still shown. - Mutation: put ``parts.hostname!r`` back in the refusal. Red: every field.""" + Mutation: append ``parts.hostname!r`` to the refusal. Red: every field.""" with pytest.raises(ValidationError) as caught: AuthSettings.model_validate(_auth(**{field: f"https://{_CANARY}.example/x"})) text = _renderings(caught.value) - assert f"[auth].{field} host is not in oidc_allowed_endpoints" in text + assert f"[auth].{field} host is not in oidc_allowed_endpoints ['idp.example']" in text assert _CANARY not in text - assert "idp.example']" not in text From 917f365c140f620cfc101fb46617c2f4e63956df Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:46:50 -0600 Subject: [PATCH 15/35] docs: CHANGELOG entry for the refusals that stop quoting the value (BACKLOG #5109) Review round 1: the sibling refusal changes in [Unreleased] each have an entry, and this one changes security-relevant output. Proposed PR title: Public origin and OIDC host refusals quote no part of the value (BACKLOG #5109) Proposed vault banner: CLOSED by engine PR : _normalize_public_origin refuses an unparsable origin after its handler ends, the IP-literal and oidc_allowed_endpoints refusals quote no part of the value, with a canary test per field; the input_hiding.py sentence names what it covers. The OIDC loop's bare urlsplit stays #4783's. Verified-by: none --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 70e491a306..cd3bb57c22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,11 @@ All notable changes to MessageFoundry are documented here. The format follows `MEFOR_AUTH_OIDC_ALLOWED_USERNAME_DOMAINS` over a real TOML list loaded as empty and moved the UPN suffix check to `[auth].ad_domain`. To fall back to `ad_domain`, leave the setting unset or empty in the file and unset in the environment. (`BACKLOG #5131`) +- **Three settings refusals no longer quote the value they refuse.** A + `[security].web_console_public_address` that does not parse as a URL, or names an IP-literal host + while a TLS posture is declared, is refused without the address, which can keep a password. An + `[auth]` OIDC endpoint whose host is not in `oidc_allowed_endpoints` is refused without the host; + the allow-list is still shown. (`BACKLOG #5109`) ## [0.5.3] — 2026-11-27 — Early Access From e40d764c29b206a273757a0f1356c2bf1a00a121 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 22:02:53 -0600 Subject: [PATCH 16/35] settings: OIDC host refusal quotes no allow-list either; origin split uncached (BACKLOG #5109) Review round 2. An oidc_allowed_endpoints entry is not checked to be a host, so a pasted URL there could hold a password; the refusal now quotes neither, and says the host is read in lower case and compared exactly, which the dropped host used to show. The public-origin split is uncached (#5287) and its refusal names likely causes. Tests add the load_settings path, a second canary in the allow-list, and a positive control proving the renderer reaches a kept error's __context__. Verified-by: tests --- messagefoundry/config/settings.py | 19 ++--- ...st_settings_url_refusals_quote_no_value.py | 71 ++++++++++++++++--- 2 files changed, 73 insertions(+), 17 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index f8c445fa8a..7d12ed6de6 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -144,7 +144,7 @@ from messagefoundry.service_status import is_safe_service_name from messagefoundry.serviceenv import ServiceEnvPosture, service_env_loosenings from messagefoundry.startupcode import StartupPosture, startup_loosenings -from messagefoundry.urlscreen import HTTP_DEFAULT_PORTS +from messagefoundry.urlscreen import HTTP_DEFAULT_PORTS, UNCACHED_URLSPLIT __all__ = [ "StoreBackend", @@ -2060,16 +2060,18 @@ def _normalize_public_origin(cls, v: str | None) -> str | None: return None # urlsplit's own message can quote the netloc, userinfo included (BACKLOG #5109), so the # refusal is raised after the handler ends: `from None` would still leave that error on - # __context__ (#1796), as _split_origin and urlscreen._split_or_refuse also note. + # __context__ (#1796), as _split_origin and urlscreen._split_or_refuse also note. Split + # uncached, so a value that may hold a password is not a key in urllib's cache (#5287). parts: SplitResult | None try: - parts = urlsplit(v) + parts = UNCACHED_URLSPLIT(v) except ValueError: parts = None if parts is None: raise ValueError( "[security].web_console_public_address is not a URL that parses; it must be a " - "bare origin like 'https://ops.example.com'" + "bare origin like 'https://ops.example.com'. A password written into it, an " + "unbalanced '[' or a full-width character can cause this" ) if ( parts.scheme not in ("http", "https") @@ -4979,11 +4981,12 @@ def given(*values: str | None) -> bool: if parts.username is not None or parts.password is not None: raise ValueError(f"[auth].{name} must not carry a user name or password") if parts.hostname not in allowed: - # The host is not quoted: it is read from the value, so the reason above for not - # quoting the URL holds for it (BACKLOG #5109). The allow-list is the operator's - # own host names, so it is still shown. + # Neither the host nor the allow-list is quoted (BACKLOG #5109): the host is read + # from the value, so the reason above for not quoting the URL holds for it, and an + # allow-list entry is not checked to be a host, so a pasted URL there can hold one. raise ValueError( - f"[auth].{name} host is not in oidc_allowed_endpoints {sorted(allowed)}" + f"[auth].{name} host is not in oidc_allowed_endpoints (the URL's host is " + "read in lower case and compared with each entry exactly)" ) # A gate that can never fire is worse than none: require at least one MFA family populated. diff --git a/tests/test_settings_url_refusals_quote_no_value.py b/tests/test_settings_url_refusals_quote_no_value.py index 9ca931e847..e11559c71e 100644 --- a/tests/test_settings_url_refusals_quote_no_value.py +++ b/tests/test_settings_url_refusals_quote_no_value.py @@ -4,17 +4,25 @@ A URL can carry a credential in its userinfo, and the text urlsplit reads as the host is the value's own, so a refusal that quotes either prints whatever the operator pasted. Each case below -puts a canary where the value would carry a secret and checks every rendering of the error. +puts a canary where the value would carry a secret and checks at least the renderings +``_renderings`` reads. """ from __future__ import annotations +from pathlib import Path from typing import Any +from urllib.parse import urlsplit import pytest -from pydantic import ValidationError +from pydantic import BaseModel, ValidationError, field_validator -from messagefoundry.config.settings import ApiSettings, AuthSettings, settings_error_detail +from messagefoundry.config.settings import ( + ApiSettings, + AuthSettings, + load_settings, + settings_error_detail, +) #: Lower case, and compared case-folded: the origin and a URL's host are lower-cased before a #: refusal could quote them, so an upper-case canary would miss the leak it is there to catch. @@ -22,8 +30,9 @@ def _renderings(exc: ValidationError) -> str: - """Every rendering of the error, case-folded, plus the ``__context__`` and ``__cause__`` of - any exception pydantic kept in an error's ``ctx``.""" + """At least these renderings of the error, case-folded: ``str``, ``repr``, the JSON, the + detail the CLI prints, and the ``__context__`` and ``__cause__`` of any exception pydantic + kept in an error's ``ctx``.""" parts = [str(exc), repr(exc), exc.json(), settings_error_detail(exc)] for err in exc.errors(include_url=False): kept = (err.get("ctx") or {}).get("error") @@ -53,6 +62,47 @@ def test_an_unparsable_public_origin_refuses_without_quoting_it(origin: str) -> assert _CANARY not in text +class _FromNoneInsideTheHandler(BaseModel): + """A test-only model whose refusal is raised inside the handler with ``from None``.""" + + url: str + + @field_validator("url") + @classmethod + def _refuse(cls, v: str) -> str: + try: + urlsplit(v) + except ValueError: + raise ValueError("does not parse") from None + return v + + +def test_the_renderings_reach_the_kept_errors_context() -> None: + """The positive control for the chain read in ``_renderings``: urlsplit's error, left on + ``__context__`` by a ``from None`` inside the handler, is found. Without this, a pydantic that + stopped keeping the error in ``ctx`` would leave every canary check above green.""" + with pytest.raises(ValidationError) as caught: + _FromNoneInsideTheHandler(url=f"https://u:x@[{_CANARY}]") + assert _CANARY in _renderings(caught.value) + + +def test_an_unparsable_public_origin_from_the_file_refuses_without_quoting_it( + tmp_path: Path, +) -> None: + """The operator-facing key, through ``load_settings``, as a deploying site sets it. + + Mutation: drop the try around urlsplit. Red: the canary.""" + cfg = tmp_path / "messagefoundry.toml" + cfg.write_text( + f'[security]\nweb_console_public_address = "https://u:x@[{_CANARY}]"\n', encoding="utf-8" + ) + with pytest.raises(ValidationError) as caught: + load_settings(config_path=cfg, environ={}) + text = _renderings(caught.value) + assert "web_console_public_address is not a url that parses" in text + assert _CANARY not in text + + def test_the_ip_literal_refusal_quotes_no_part_of_the_origin() -> None: """The normalized origin keeps userinfo, so quoting it whole printed the password. @@ -97,11 +147,14 @@ def _auth(**over: Any) -> dict[str, Any]: ) def test_the_allowed_endpoints_refusal_quotes_no_host(field: str) -> None: """The host is read from the value, so quoting it prints whatever the operator pasted there. - The allow-list is the operator's own host names and is still shown. + An allow-list entry is not checked to be a host, so a pasted URL there is not quoted either. - Mutation: append ``parts.hostname!r`` to the refusal. Red: every field.""" + Mutation: append ``parts.hostname!r`` to the refusal. Red: every field. Mutation: append + ``sorted(allowed)``. Red: every field, the second canary.""" + allowed = ["idp.example", f"https://u:{_CANARY}2@idp.example"] + over = {field: f"https://{_CANARY}.example/x", "oidc_allowed_endpoints": allowed} with pytest.raises(ValidationError) as caught: - AuthSettings.model_validate(_auth(**{field: f"https://{_CANARY}.example/x"})) + AuthSettings.model_validate(_auth(**over)) text = _renderings(caught.value) - assert f"[auth].{field} host is not in oidc_allowed_endpoints ['idp.example']" in text + assert f"[auth].{field} host is not in oidc_allowed_endpoints" in text assert _CANARY not in text From 175842b15bf83b53f77f7ef2861d5a86f9feeab7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 22:03:36 -0600 Subject: [PATCH 17/35] docs: CHANGELOG says the OIDC host refusal quotes no allow-list (BACKLOG #5109) Review round 2 follows the code change. Proposed PR title: Public origin and OIDC allow-list refusals quote no part of the value (BACKLOG #5109) Proposed vault banner: CLOSED by engine PR : _normalize_public_origin refuses an unparsable origin after its handler ends, and the IP-literal and oidc_allowed_endpoints refusals quote no part of the value, with a canary test per field and a load_settings case; the input_hiding.py sentence names what it covers. The OIDC loop's bare urlsplit stays #4783's. Verified-by: none --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd3bb57c22..0a4a43cbba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,8 +23,8 @@ All notable changes to MessageFoundry are documented here. The format follows - **Three settings refusals no longer quote the value they refuse.** A `[security].web_console_public_address` that does not parse as a URL, or names an IP-literal host while a TLS posture is declared, is refused without the address, which can keep a password. An - `[auth]` OIDC endpoint whose host is not in `oidc_allowed_endpoints` is refused without the host; - the allow-list is still shown. (`BACKLOG #5109`) + `[auth]` OIDC endpoint whose host is not in `oidc_allowed_endpoints` is refused without the host + or the allow-list. (`BACKLOG #5109`) ## [0.5.3] — 2026-11-27 — Early Access From b4c01c945961573288860ff42703bfa3c7d7d4bf Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 22:25:36 -0600 Subject: [PATCH 18/35] [backup]/[dr] paths checked positively; DR runner logs no non-path destination (BACKLOG #5110) _looks_like_url reads one spelling, so x://u:pw@h, KEY:pw://h, s3:bucket?sig= and 1s://... loaded as paths at [backup].destination, [dr].seed_archive and [dr].restore_token. _is_local_or_unc_path adds a positive check: no URL, and a ':' only after a leading drive letter (after any \\?\ prefix). The DR runner's INFO start line and its not-writable WARNING read BackupSettings.destination_for_log, which shows a path and withholds anything else, and the WARNING names the OSError by strerror, since its own text quotes the path. Tests carry the four values, path controls and both log lines. The seed_dir render test now reaches _seed_dir_absolute with a colon-free value. Verified-by: tests --- messagefoundry/config/settings.py | 61 +++++++++-- messagefoundry/pipeline/dr_backup.py | 6 +- tests/test_backup_dr_path_shape.py | 129 ++++++++++++++++++++++++ tests/test_cli_settings_error_render.py | 8 +- 4 files changed, 187 insertions(+), 17 deletions(-) create mode 100644 tests/test_backup_dr_path_shape.py diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 7d12ed6de6..f75722041d 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -7882,6 +7882,32 @@ def _looks_like_url(value: str) -> bool: return _URL_SCHEME.match(value.strip().lower()) is not None +#: The Win32 extended-length prefixes, ``\\?\`` and its forward-slash spelling, which a local path +#: may carry before its drive letter. +_EXTENDED_PATH_PREFIXES = ("\\\\?\\", "//?/") + + +def _is_local_or_unc_path(value: str) -> bool: + """Whether ``value``, stripped, has a local or UNC path's shape: not a ``://`` URL + (:func:`_looks_like_url`), and a ``:`` only as a drive letter's, right after one ASCII letter + at the start, after any ``\\\\?\\`` prefix (vault BACKLOG #5110). + + The positive half catches what the URL shape misses, at least a one-letter scheme with + userinfo (``x://u:pw@h``), a scheme holding a ``:`` (``KEY:pw://h``), a scheme-only value + (``s3:bucket?sig=...``) and a scheme starting with a digit (``1s://...``). It refuses a POSIX + path holding a ``:`` too, which these settings, read on Windows, do not need. An empty value + passes; the fields refuse a blank or padded one elsewhere.""" + if _looks_like_url(value): + return False + path = value.strip() + if path.startswith(_EXTENDED_PATH_PREFIXES): + path = path[len(_EXTENDED_PATH_PREFIXES[0]) :] + colon = path.find(":") + if colon == -1: + return True + return colon == 1 and path[0].isascii() and path[0].isalpha() and ":" not in path[2:] + + class BackupSettings(_Section): """``[backup]`` — engine-managed scheduled + on-demand DR backup of the config bundle + the SQLite store, written as one AES-256-GCM ``.mfbak`` archive to a local/UNC destination (ADR 0049, #60). @@ -7965,14 +7991,25 @@ def _known_snapshot_method(cls, value: str) -> str: @classmethod def _no_cloud_destination(cls, value: str) -> str: # No cloud target / no new egress surface (ADR 0049, owner-locked). Reject a URL destination - # at config load rather than silently treating it as a (bogus) local path at 02:00. - if _looks_like_url(value): + # at config load rather than silently treating it as a (bogus) local path at 02:00. The + # check is positive, so a URL shape the scheme test misses is refused too (BACKLOG #5110). + if not _is_local_or_unc_path(value): raise ValueError( - "[backup].destination must be a LOCAL or UNC path, not a URL; " - "MessageFoundry DR backups have no cloud target (ADR 0049 — no new egress)" + "[backup].destination must be a LOCAL or UNC path, not a URL, with a ':' only " + "after a drive letter; MessageFoundry DR backups have no cloud target (ADR 0049 — " + "no new egress)" ) return value + @property + def destination_for_log(self) -> str: + """``destination`` as a log line may show it: the path, or a placeholder where it is not a + local or UNC path, which a load refuses but a model built past validation could hold + (BACKLOG #5110). A URL there could carry a credential.""" + if _is_local_or_unc_path(self.destination): + return self.destination + return "" + @model_validator(mode="after") def _require_destination_when_enabled(self) -> BackupSettings: # A backup with nowhere to write is a misconfiguration; fail loud at config load, not at 02:00. @@ -8122,10 +8159,12 @@ def _positive_timeout(cls, value: float) -> float: @field_validator("seed_archive", "seed_dir") @classmethod def _no_cloud_seed(cls, value: str, info: ValidationInfo) -> str: - if _looks_like_url(value): + # Positive, so a URL shape the scheme test misses is refused too (BACKLOG #5110). + if not _is_local_or_unc_path(value): raise ValueError( - f"[dr].{info.field_name} must be a LOCAL or UNC path, not a URL; " - "the DR cold seed has no cloud source (ADR 0048 — no new egress)" + f"[dr].{info.field_name} must be a LOCAL or UNC path, not a URL, with a ':' only " + "after a drive letter; the DR cold seed has no cloud source (ADR 0048 — no new " + "egress)" ) return value @@ -8148,10 +8187,12 @@ def _seed_dir_absolute(cls, value: str) -> str: def _no_cloud_restore_token(cls, value: str) -> str: # The restore-token is a DBA-placed local artifact on the DR box (BACKLOG #223, ADR 0102); like # seed_archive it is LOCAL/UNC only — a URL would imply new egress, which DR forbids. - if _looks_like_url(value): + # Positive, so a URL shape the scheme test misses is refused too (BACKLOG #5110). + if not _is_local_or_unc_path(value): raise ValueError( - "[dr].restore_token must be a LOCAL or UNC path, not a URL; " - "the DR restore-token is a local artifact on the DR box (ADR 0102 — no new egress)" + "[dr].restore_token must be a LOCAL or UNC path, not a URL, with a ':' only after " + "a drive letter; the DR restore-token is a local artifact on the DR box (ADR 0102 " + "— no new egress)" ) return value diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 02052f548a..3a65b3b262 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -670,7 +670,7 @@ def start(self) -> None: self._task = asyncio.create_task(self._run()) log.info( "DR backup enabled: destination=%r schedule_at=%r retention_keep=%d snapshot_method=%r", - self._settings.destination, + self._settings.destination_for_log, self._settings.schedule_at, self._settings.retention_keep, self._settings.snapshot_method, @@ -1841,8 +1841,8 @@ def _preflight_destination(self) -> None: log.warning( "DR backup destination %s is not writable at startup: %s " "(the scheduled backup will fail until this is fixed)", - self._settings.destination, - safe_exc(exc), + self._settings.destination_for_log, + exc.strerror or shown_class_name(exc), ) return try: diff --git a/tests/test_backup_dr_path_shape.py b/tests/test_backup_dr_path_shape.py new file mode 100644 index 0000000000..07f0706056 --- /dev/null +++ b/tests/test_backup_dr_path_shape.py @@ -0,0 +1,129 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""The [backup] and [dr] path settings take a local or UNC path, checked positively (BACKLOG #5110). + +The scheme test ``_looks_like_url`` reads one spelling, ``://``. At least +the four canary values below miss it and loaded as paths, and a credential in one would reach +the general log through the DR runner, which logged the destination raw at INFO and at WARNING. +""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Any + +import pytest +from pydantic import ValidationError + +from messagefoundry.config.settings import BackupSettings, DrSettings, settings_error_detail +from messagefoundry.pipeline.dr_backup import BackupRunner + +_CANARY = "canary5110" + +#: The values the PR 2699 Builder reported, each with the canary where a secret would sit. +_MISSED_BY_THE_SCHEME_TEST = [ + f"x://u:{_CANARY}@h/x", + f"KEY:{_CANARY}://host/x", + f"s3:bucket?sig={_CANARY}", + f"1s://user:{_CANARY}@host/seed", +] +_IDS = ["one-letter-scheme", "colon-in-scheme", "scheme-only", "digit-first-scheme"] + +#: Paths that must keep loading: a drive path in both slash spellings, a drive letter with a +#: doubled slash, a UNC share in both spellings, a Win32 extended-length path, a POSIX path and a +#: relative one. +_PATHS = [ + "D:/mefor-backups", + "D:\\mefor-backups", + "C://mefor-backups", + "\\\\nas\\share\\backups", + "//nas/share/backups", + "\\\\?\\D:\\mefor-backups", + "/var/lib/mefor/backups", + "backups", +] + + +def _build(section: str, field: str, value: str) -> Any: + model = BackupSettings if section == "backup" else DrSettings + return model.model_validate({field: value}) + + +@pytest.mark.parametrize( + ("section", "field"), + [("backup", "destination"), ("dr", "seed_archive"), ("dr", "restore_token")], +) +@pytest.mark.parametrize("value", _MISSED_BY_THE_SCHEME_TEST, ids=_IDS) +def test_a_url_the_scheme_test_misses_is_refused_and_not_quoted( + section: str, field: str, value: str +) -> None: + """Mutation: test ``_looks_like_url`` alone again in the validator. Red: every value.""" + with pytest.raises(ValidationError) as caught: + _build(section, field, value) + text = "\n".join((str(caught.value), settings_error_detail(caught.value))).casefold() + assert f"[{section}].{field} must be a local or unc path" in text + assert _CANARY not in text + + +@pytest.mark.parametrize( + ("section", "field"), + [("backup", "destination"), ("dr", "seed_archive"), ("dr", "restore_token")], +) +@pytest.mark.parametrize("value", _PATHS) +def test_a_local_or_unc_path_still_loads(section: str, field: str, value: str) -> None: + """The control: a check too wide would refuse these. + + Mutation: refuse every ``:``. Red: the drive paths.""" + assert getattr(_build(section, field, value), field) == value + + +def _runner(settings: BackupSettings) -> BackupRunner: + return BackupRunner(store=object(), settings=settings, store_settings=None, config_dir=None) # type: ignore[arg-type] + + +def _refuse_mkdir(monkeypatch: pytest.MonkeyPatch) -> None: + """Make every mkdir fail as an unwritable share does, on any platform, with an OSError whose + own text quotes the path, so the WARNING branch runs and nothing is created.""" + + def refuse(self: Path, *args: object, **kwargs: object) -> None: + raise PermissionError(13, "Permission denied", str(self)) + + monkeypatch.setattr(Path, "mkdir", refuse) + + +@pytest.mark.parametrize("value", _MISSED_BY_THE_SCHEME_TEST, ids=_IDS) +async def test_the_runner_never_logs_a_destination_that_is_not_a_path( + value: str, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A model built past validation can still hold one, so both log lines, the INFO at start and + the WARNING when the destination is not writable, read ``destination_for_log``. The WARNING + names the OS error by its message alone: an OSError's own text quotes the path. + + Mutation: log ``destination`` again in either line. Red: every value. Mutation: log + ``safe_exc(exc)`` again. Red: every value.""" + _refuse_mkdir(monkeypatch) + settings = BackupSettings.model_construct( + **{**BackupSettings().model_dump(), "enabled": True, "destination": value} + ) + runner = _runner(settings) + with caplog.at_level(logging.DEBUG, logger="messagefoundry.pipeline.dr_backup"): + runner.start() + await runner.stop() + assert "DR backup enabled" in caplog.text and "not writable at startup" in caplog.text + assert _CANARY not in caplog.text.casefold() + + +def test_the_runner_still_logs_a_path_destination( + tmp_path: Path, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """The control: a real path is shown, so the log still says where the backups go. + + Mutation: always log the placeholder. Red: this test.""" + _refuse_mkdir(monkeypatch) + destination = str(tmp_path / "backups") + settings = BackupSettings(enabled=True, destination=destination) + with caplog.at_level(logging.WARNING, logger="messagefoundry.pipeline.dr_backup"): + _runner(settings)._preflight_destination() + assert destination in caplog.text + assert "not writable at startup: Permission denied" in caplog.text diff --git a/tests/test_cli_settings_error_render.py b/tests/test_cli_settings_error_render.py index 2b4177a6a7..4ce7df1f9b 100644 --- a/tests/test_cli_settings_error_render.py +++ b/tests/test_cli_settings_error_render.py @@ -400,10 +400,10 @@ def test_a_url_refusal_is_the_same_text_whatever_the_url( def test_a_seed_dir_refused_as_not_absolute_quotes_no_part_of_the_value() -> None: - """``seed_dir``'s second refusal. A value with no ``://`` passes the URL refusal and reaches - ``_seed_dir_absolute``. No one-letter scheme here: ``os.path.isabs`` reads that as a Windows - drive path, so the value would load.""" - exc = _refused(DrSettings, "seed_dir", f"user:{_CANARY}@host/seed") + """``seed_dir``'s second refusal. A relative value with no ``:`` passes the path-shape refusal + and reaches ``_seed_dir_absolute``; one holding a ``:`` past a drive letter is refused first + since BACKLOG #5110.""" + exc = _refused(DrSettings, "seed_dir", f"{_CANARY}@host/seed") _assert_quotes_no_canary(exc, "seed_dir", "[dr].seed_dir must be an absolute path, or omitted") From b612832457629d49b50ad3e9f8fc8ce7569ec7fe Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 22:26:07 -0600 Subject: [PATCH 19/35] docs: CHANGELOG entry for the [backup]/[dr] path-shape check (BACKLOG #5110) The CONFIGURATION.md rows that describe _looks_like_url are left to open PR 3528, which rewrites them; the wording they need is in the Builder's report. Proposed PR title: [backup]/[dr] path settings checked positively; DR runner logs no URL destination (BACKLOG #5110) Proposed vault banner: CLOSED by engine PR : destination, seed_archive and restore_token take a positive local-or-UNC shape check, with the four reported values as tests; the DR runner's INFO and WARNING lines log destination_for_log. CONFIGURATION.md rows owed after PR 3528 lands. Verified-by: none --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a4a43cbba..825049e304 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,11 @@ All notable changes to MessageFoundry are documented here. The format follows while a TLS posture is declared, is refused without the address, which can keep a password. An `[auth]` OIDC endpoint whose host is not in `oidc_allowed_endpoints` is refused without the host or the allow-list. (`BACKLOG #5109`) +- **`[backup].destination`, `[dr].seed_archive` and `[dr].restore_token` must have a local or UNC + path's shape.** Besides a `://` URL, a value with a `:` anywhere but right after a + leading drive letter is now refused at load, which catches URL shapes the scheme test missed + and also refuses a POSIX path holding a `:`. The DR backup runner no longer logs a destination + that is not such a path. (`BACKLOG #5110`) ## [0.5.3] — 2026-11-27 — Early Access From 25f000e9e139ca559f65b8caf7f1e60525cf9696 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 22:41:39 -0600 Subject: [PATCH 20/35] [backup]/[dr] path check also refuses a drive-letter scheme with userinfo and a query (BACKLOG #5110) Review round 1. x://token@h/x and C:/c?sig=... still loaded; the check now refuses an '@' in the segment after a drive letter's '//' and any character Win32 refuses in a path, read after the \\?\ or \\.\ prefix in either slash spelling, which it now strips by matched length. The WARNING keeps the OSError's class and code, without its filename. The new values join _CREDENTIAL_URLS, so all four path fields and every rendering are checked; the runner test patches mkdir for its own path only. Verified-by: tests --- messagefoundry/config/settings.py | 46 ++++++++----- messagefoundry/pipeline/dr_backup.py | 4 +- tests/test_backup_dr_path_shape.py | 85 +++++++++++-------------- tests/test_cli_settings_error_render.py | 7 ++ 4 files changed, 78 insertions(+), 64 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index f75722041d..cf454e6817 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -7882,26 +7882,41 @@ def _looks_like_url(value: str) -> bool: return _URL_SCHEME.match(value.strip().lower()) is not None -#: The Win32 extended-length prefixes, ``\\?\`` and its forward-slash spelling, which a local path -#: may carry before its drive letter. -_EXTENDED_PATH_PREFIXES = ("\\\\?\\", "//?/") +#: The Win32 prefixes a local path may carry before its drive letter: extended-length ``\\?\`` and +#: the device namespace ``\\.\``, in either slash spelling. +_WIN32_PATH_PREFIXES = ("\\\\?\\", "//?/", "\\\\?/", "\\\\.\\", "//./", "\\\\./") + +#: Characters Win32 refuses in a path component. A query (``?sig=``) is the one these settings met. +_WIN32_INVALID_PATH_CHARS = frozenset('<>"|?*') + +#: A drive letter, two slashes, then a segment holding ``@``: a one-letter scheme with userinfo. +_ONE_LETTER_SCHEME_USERINFO = re.compile(r"[a-z]:[\\/]{2}[^\\/]*@", re.IGNORECASE) def _is_local_or_unc_path(value: str) -> bool: - """Whether ``value``, stripped, has a local or UNC path's shape: not a ``://`` URL - (:func:`_looks_like_url`), and a ``:`` only as a drive letter's, right after one ASCII letter - at the start, after any ``\\\\?\\`` prefix (vault BACKLOG #5110). - - The positive half catches what the URL shape misses, at least a one-letter scheme with - userinfo (``x://u:pw@h``), a scheme holding a ``:`` (``KEY:pw://h``), a scheme-only value - (``s3:bucket?sig=...``) and a scheme starting with a digit (``1s://...``). It refuses a POSIX - path holding a ``:`` too, which these settings, read on Windows, do not need. An empty value - passes; the fields refuse a blank or padded one elsewhere.""" + """Whether ``value``, stripped, has a local or UNC path's shape (vault BACKLOG #5110): not a + ``://`` URL (:func:`_looks_like_url`, named first so the refusal reads the same for + one); a ``:`` only as a drive letter's, right after one ASCII letter at the start, after any + Win32 prefix in :data:`_WIN32_PATH_PREFIXES`; no character Win32 refuses in a path; and no + ``@`` in the segment after a drive letter's ``//``. + + The positive half catches at least what the scheme test misses: a one-letter scheme with + userinfo (``x://u:pw@h``, ``x://token@h``), a scheme holding a ``:`` (``KEY:pw://h``), a + scheme-only value (``s3:bucket?sig=...``), a scheme starting with a digit (``1s://...``) and a + query after a drive (``C:/x?sig=...``). It also refuses a POSIX path holding a ``:`` or one of + those characters, which these settings, read on Windows, do not need. An empty value passes; + whether a blank or padded one is refused is each field's own rule.""" if _looks_like_url(value): return False path = value.strip() - if path.startswith(_EXTENDED_PATH_PREFIXES): - path = path[len(_EXTENDED_PATH_PREFIXES[0]) :] + for prefix in _WIN32_PATH_PREFIXES: + if path.startswith(prefix): + path = path.removeprefix(prefix) + break + if any(char in _WIN32_INVALID_PATH_CHARS for char in path): + return False + if _ONE_LETTER_SCHEME_USERINFO.match(path): + return False colon = path.find(":") if colon == -1: return True @@ -7925,7 +7940,8 @@ class BackupSettings(_Section): # Opt-in master switch; a deployment with no [backup] is unaffected (no-op default). enabled: bool = False # Operator-set LOCAL or UNC destination path, e.g. "D:/mefor-backups" or r"\\nas\mefor\backups". - # REQUIRED (non-empty) when enabled. A :// URL (s3://, https://, sftp://, ...) is REJECTED. + # REQUIRED (non-empty) when enabled. A :// URL (s3://, https://, sftp://, ...) is REJECTED, + # and so is any value without a local or UNC path's shape (_is_local_or_unc_path). destination: str = "" # Daily local "HH:MM" at which the scheduled backup runs (reusing the RetentionSettings clock parser). # "" = on-demand only (the `messagefoundry backup` CLI), no scheduled pass. diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 3a65b3b262..6db9763751 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -1842,7 +1842,9 @@ def _preflight_destination(self) -> None: "DR backup destination %s is not writable at startup: %s " "(the scheduled backup will fail until this is fixed)", self._settings.destination_for_log, - exc.strerror or shown_class_name(exc), + safe_exc(OSError(exc.errno, exc.strerror)) + if exc.strerror + else shown_class_name(exc), ) return try: diff --git a/tests/test_backup_dr_path_shape.py b/tests/test_backup_dr_path_shape.py index 07f0706056..3e22ed8aa9 100644 --- a/tests/test_backup_dr_path_shape.py +++ b/tests/test_backup_dr_path_shape.py @@ -2,9 +2,10 @@ # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """The [backup] and [dr] path settings take a local or UNC path, checked positively (BACKLOG #5110). -The scheme test ``_looks_like_url`` reads one spelling, ``://``. At least -the four canary values below miss it and loaded as paths, and a credential in one would reach -the general log through the DR runner, which logged the destination raw at INFO and at WARNING. +The refusals of the URL shapes the scheme test missed are pinned with the other URL refusals, in +``_CREDENTIAL_URLS`` in ``tests/test_cli_settings_error_render.py``, which checks every path field +and every rendering. This file holds the paths that must keep loading, and the DR runner's two +log lines, which logged the destination raw at INFO and at WARNING. """ from __future__ import annotations @@ -14,32 +15,27 @@ from typing import Any import pytest -from pydantic import ValidationError -from messagefoundry.config.settings import BackupSettings, DrSettings, settings_error_detail +from messagefoundry.config.settings import BackupSettings, DrSettings from messagefoundry.pipeline.dr_backup import BackupRunner _CANARY = "canary5110" -#: The values the PR 2699 Builder reported, each with the canary where a secret would sit. -_MISSED_BY_THE_SCHEME_TEST = [ - f"x://u:{_CANARY}@h/x", - f"KEY:{_CANARY}://host/x", - f"s3:bucket?sig={_CANARY}", - f"1s://user:{_CANARY}@host/seed", -] -_IDS = ["one-letter-scheme", "colon-in-scheme", "scheme-only", "digit-first-scheme"] - #: Paths that must keep loading: a drive path in both slash spellings, a drive letter with a -#: doubled slash, a UNC share in both spellings, a Win32 extended-length path, a POSIX path and a -#: relative one. +#: doubled slash, a UNC share in both spellings, Win32 extended-length and device-namespace paths +#: in each slash spelling, an ``@`` in a later segment, a POSIX path and a relative one. _PATHS = [ "D:/mefor-backups", - "D:\\mefor-backups", + r"D:\mefor-backups", "C://mefor-backups", - "\\\\nas\\share\\backups", + r"\\nas\share\backups", "//nas/share/backups", - "\\\\?\\D:\\mefor-backups", + r"\\?\D:\mefor-backups", + "//?/D:/mefor-backups", + r"\\?/D:/mefor-backups", + r"\\.\D:\mefor-backups", + r"\\?\UNC\nas\share\backups", + "D:/backups/ops@site/x", "/var/lib/mefor/backups", "backups", ] @@ -50,59 +46,51 @@ def _build(section: str, field: str, value: str) -> Any: return model.model_validate({field: value}) -@pytest.mark.parametrize( - ("section", "field"), - [("backup", "destination"), ("dr", "seed_archive"), ("dr", "restore_token")], -) -@pytest.mark.parametrize("value", _MISSED_BY_THE_SCHEME_TEST, ids=_IDS) -def test_a_url_the_scheme_test_misses_is_refused_and_not_quoted( - section: str, field: str, value: str -) -> None: - """Mutation: test ``_looks_like_url`` alone again in the validator. Red: every value.""" - with pytest.raises(ValidationError) as caught: - _build(section, field, value) - text = "\n".join((str(caught.value), settings_error_detail(caught.value))).casefold() - assert f"[{section}].{field} must be a local or unc path" in text - assert _CANARY not in text - - @pytest.mark.parametrize( ("section", "field"), [("backup", "destination"), ("dr", "seed_archive"), ("dr", "restore_token")], ) @pytest.mark.parametrize("value", _PATHS) def test_a_local_or_unc_path_still_loads(section: str, field: str, value: str) -> None: - """The control: a check too wide would refuse these. + """The control for the positive check: one too wide would refuse these. - Mutation: refuse every ``:``. Red: the drive paths.""" + Mutation: refuse every ``:``. Red: the drive paths. Mutation: test the Win32 characters + before the prefix is removed. Red: the ``\\\\?\\`` paths.""" assert getattr(_build(section, field, value), field) == value +_NOT_PATHS = [f"x://u:{_CANARY}@h/x", f"KEY:{_CANARY}://host/x", f"s3:bucket?sig={_CANARY}"] + + def _runner(settings: BackupSettings) -> BackupRunner: return BackupRunner(store=object(), settings=settings, store_settings=None, config_dir=None) # type: ignore[arg-type] -def _refuse_mkdir(monkeypatch: pytest.MonkeyPatch) -> None: - """Make every mkdir fail as an unwritable share does, on any platform, with an OSError whose - own text quotes the path, so the WARNING branch runs and nothing is created.""" +def _refuse_mkdir_of(monkeypatch: pytest.MonkeyPatch, target: str) -> None: + """Make mkdir of ``target`` fail as an unwritable share does, on any platform, with an OSError + whose own text quotes the path, so the WARNING branch runs and nothing is created. Any other + mkdir runs as usual.""" + original = Path.mkdir - def refuse(self: Path, *args: object, **kwargs: object) -> None: - raise PermissionError(13, "Permission denied", str(self)) + def refuse(self: Path, *args: Any, **kwargs: Any) -> None: + if str(self) == str(Path(target)): + raise PermissionError(13, "Permission denied", str(self)) + original(self, *args, **kwargs) monkeypatch.setattr(Path, "mkdir", refuse) -@pytest.mark.parametrize("value", _MISSED_BY_THE_SCHEME_TEST, ids=_IDS) +@pytest.mark.parametrize("value", _NOT_PATHS, ids=["userinfo", "colon-in-scheme", "query"]) async def test_the_runner_never_logs_a_destination_that_is_not_a_path( value: str, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: """A model built past validation can still hold one, so both log lines, the INFO at start and the WARNING when the destination is not writable, read ``destination_for_log``. The WARNING - names the OS error by its message alone: an OSError's own text quotes the path. + renders the OS error without its filename: an OSError's own text quotes the path. Mutation: log ``destination`` again in either line. Red: every value. Mutation: log ``safe_exc(exc)`` again. Red: every value.""" - _refuse_mkdir(monkeypatch) + _refuse_mkdir_of(monkeypatch, value) settings = BackupSettings.model_construct( **{**BackupSettings().model_dump(), "enabled": True, "destination": value} ) @@ -117,13 +105,14 @@ async def test_the_runner_never_logs_a_destination_that_is_not_a_path( def test_the_runner_still_logs_a_path_destination( tmp_path: Path, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: - """The control: a real path is shown, so the log still says where the backups go. + """The control: a real path is shown, and the OS error keeps its class and code, so the log + still says where the backups go and why the write failed. Mutation: always log the placeholder. Red: this test.""" - _refuse_mkdir(monkeypatch) destination = str(tmp_path / "backups") + _refuse_mkdir_of(monkeypatch, destination) settings = BackupSettings(enabled=True, destination=destination) with caplog.at_level(logging.WARNING, logger="messagefoundry.pipeline.dr_backup"): _runner(settings)._preflight_destination() assert destination in caplog.text - assert "not writable at startup: Permission denied" in caplog.text + assert "PermissionError: [Errno 13] Permission denied" in caplog.text diff --git a/tests/test_cli_settings_error_render.py b/tests/test_cli_settings_error_render.py index 4ce7df1f9b..90659d0166 100644 --- a/tests/test_cli_settings_error_render.py +++ b/tests/test_cli_settings_error_render.py @@ -351,6 +351,13 @@ def test_a_json_caller_still_gets_a_json_error( "scheme-past-the-old-fixed-list": f"sftp://user:{_CANARY}@host/seed?sig={_CANARY}", "before-the-separator": f"{_CANARY}://u@h", "before-the-separator-upper-case": f"{_CANARY.upper()}://u@h", + # Shapes the scheme test misses, refused by the positive path check (BACKLOG #5110). + "one-letter-scheme": f"x://u:{_CANARY}@h/x", + "one-letter-scheme-token": f"x://{_CANARY}@h/x", + "colon-in-scheme": f"KEY:{_CANARY}://host/x", + "scheme-only": f"s3:bucket?sig={_CANARY}", + "digit-first-scheme": f"1s://user:{_CANARY}@host/seed", + "query-after-a-drive": f"C:/c?sig={_CANARY}", } From 377c08caae482bcd41fcce2dcd6d9a437e3dfcf9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 22:43:02 -0600 Subject: [PATCH 21/35] docs: CHANGELOG names seed_dir and the wider path-shape refusal (BACKLOG #5110) Review round 1. The entry omitted [dr].seed_dir, and said the runner no longer logs such a destination at all; only its startup lines changed. The CONFIGURATION.md rows that describe _looks_like_url are left to open PR 3528; the wording they need is in the Builder's report. Proposed PR title: [backup]/[dr] path settings checked positively; DR runner startup lines log no URL destination (BACKLOG #5110) Proposed vault banner: CLOSED by engine PR : destination, seed_archive, seed_dir and restore_token take a positive local-or-UNC shape check, with the four reported values among the tested shapes; the DR runner's startup INFO and WARNING lines log destination_for_log. CONFIGURATION.md rows owed after PR 3528 lands. Verified-by: none --- CHANGELOG.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 825049e304..b9e67bd4a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,11 +25,12 @@ All notable changes to MessageFoundry are documented here. The format follows while a TLS posture is declared, is refused without the address, which can keep a password. An `[auth]` OIDC endpoint whose host is not in `oidc_allowed_endpoints` is refused without the host or the allow-list. (`BACKLOG #5109`) -- **`[backup].destination`, `[dr].seed_archive` and `[dr].restore_token` must have a local or UNC - path's shape.** Besides a `://` URL, a value with a `:` anywhere but right after a - leading drive letter is now refused at load, which catches URL shapes the scheme test missed - and also refuses a POSIX path holding a `:`. The DR backup runner no longer logs a destination - that is not such a path. (`BACKLOG #5110`) +- **`[backup].destination`, `[dr].seed_archive`, `[dr].seed_dir` and `[dr].restore_token` must + have a local or UNC path's shape.** Besides a `://` URL, a value is now refused at load + when it has a `:` anywhere but right after a leading drive letter, a character Windows refuses + in a path (such as `?`), or an `@` in the segment after a drive letter's `//`. That catches URL + shapes the scheme test missed, and also refuses a POSIX path holding one of them. The DR backup + runner's startup lines no longer log a destination that is not such a path. (`BACKLOG #5110`) ## [0.5.3] — 2026-11-27 — Early Access From df087a8ec615c49ed83f5bff190c4c56ee723757 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 23:11:39 -0600 Subject: [PATCH 22/35] [backup]/[dr] path check refuses controls and any slash run; refusal states every rule (BACKLOG #5110) Review round 2. A NUL loaded and then failed the runner's mkdir with an uncaught ValueError; the C0 controls are now refused. The userinfo rule takes two or more slashes, and the \\?\ and \\.\ prefixes match in every slash spelling. Each refusal now states the whole rule, one fixed text. The WARNING keeps a WinError code. Tests add NUL, three slashes, the mixed prefixes, seed_dir controls and a WinError case. Verified-by: tests --- messagefoundry/config/settings.py | 57 ++++++++++++++----------- messagefoundry/pipeline/dr_backup.py | 6 ++- tests/test_backup_dr_path_shape.py | 32 ++++++++++++++ tests/test_cli_settings_error_render.py | 2 + 4 files changed, 72 insertions(+), 25 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index cf454e6817..baddc24fac 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -7882,23 +7882,34 @@ def _looks_like_url(value: str) -> bool: return _URL_SCHEME.match(value.strip().lower()) is not None -#: The Win32 prefixes a local path may carry before its drive letter: extended-length ``\\?\`` and -#: the device namespace ``\\.\``, in either slash spelling. -_WIN32_PATH_PREFIXES = ("\\\\?\\", "//?/", "\\\\?/", "\\\\.\\", "//./", "\\\\./") - -#: Characters Win32 refuses in a path component. A query (``?sig=``) is the one these settings met. -_WIN32_INVALID_PATH_CHARS = frozenset('<>"|?*') - -#: A drive letter, two slashes, then a segment holding ``@``: a one-letter scheme with userinfo. -_ONE_LETTER_SCHEME_USERINFO = re.compile(r"[a-z]:[\\/]{2}[^\\/]*@", re.IGNORECASE) +#: The Win32 prefixes a local path may carry before its drive letter, extended-length ``\\?\`` and +#: the device namespace ``\\.\``, each compared with its first four characters' slashes made +#: backslashes, so every slash spelling matches. +_WIN32_PATH_PREFIXES = ("\\\\?\\", "\\\\.\\") + +#: Characters Win32 refuses in a path: ``< > " | ? *`` and the C0 controls, NUL included. A query +#: (``?sig=``) is the one these settings met; a NUL would load and then fail the runner's mkdir +#: with a ValueError its handler does not catch. +_WIN32_INVALID_PATH_CHARS = frozenset('<>"|?*') | frozenset(map(chr, range(0x20))) + +#: A drive letter, two or more slashes, then a segment holding ``@``: a one-letter scheme with +#: userinfo. +_ONE_LETTER_SCHEME_USERINFO = re.compile(r"[a-z]:[\\/]{2,}[^\\/]*@", re.IGNORECASE) + +#: The refused shape, as each path refusal states it; one text, so a refusal reads the same +#: whatever the value. +_PATH_SHAPE_RULE = ( + "a ':' only right after a leading drive letter, none of < > \" | ? * or a control character, " + "and no '@' right after a drive letter's '//'" +) def _is_local_or_unc_path(value: str) -> bool: """Whether ``value``, stripped, has a local or UNC path's shape (vault BACKLOG #5110): not a - ``://`` URL (:func:`_looks_like_url`, named first so the refusal reads the same for - one); a ``:`` only as a drive letter's, right after one ASCII letter at the start, after any - Win32 prefix in :data:`_WIN32_PATH_PREFIXES`; no character Win32 refuses in a path; and no - ``@`` in the segment after a drive letter's ``//``. + ``://`` URL (:func:`_looks_like_url`); a ``:`` only as a drive letter's, right after + one ASCII letter at the start, after any Win32 prefix in :data:`_WIN32_PATH_PREFIXES`; none of + :data:`_WIN32_INVALID_PATH_CHARS`; and no ``@`` in the segment after a drive letter's ``//``. + The scheme test is redundant with the colon rule; it is kept as the detector the docs name. The positive half catches at least what the scheme test misses: a one-letter scheme with userinfo (``x://u:pw@h``, ``x://token@h``), a scheme holding a ``:`` (``KEY:pw://h``), a @@ -7909,10 +7920,8 @@ def _is_local_or_unc_path(value: str) -> bool: if _looks_like_url(value): return False path = value.strip() - for prefix in _WIN32_PATH_PREFIXES: - if path.startswith(prefix): - path = path.removeprefix(prefix) - break + if path[:4].replace("/", "\\") in _WIN32_PATH_PREFIXES: + path = path[4:] if any(char in _WIN32_INVALID_PATH_CHARS for char in path): return False if _ONE_LETTER_SCHEME_USERINFO.match(path): @@ -8011,8 +8020,8 @@ def _no_cloud_destination(cls, value: str) -> str: # check is positive, so a URL shape the scheme test misses is refused too (BACKLOG #5110). if not _is_local_or_unc_path(value): raise ValueError( - "[backup].destination must be a LOCAL or UNC path, not a URL, with a ':' only " - "after a drive letter; MessageFoundry DR backups have no cloud target (ADR 0049 — " + "[backup].destination must be a LOCAL or UNC path, not a URL, with " + f"{_PATH_SHAPE_RULE}; MessageFoundry DR backups have no cloud target (ADR 0049 — " "no new egress)" ) return value @@ -8178,8 +8187,8 @@ def _no_cloud_seed(cls, value: str, info: ValidationInfo) -> str: # Positive, so a URL shape the scheme test misses is refused too (BACKLOG #5110). if not _is_local_or_unc_path(value): raise ValueError( - f"[dr].{info.field_name} must be a LOCAL or UNC path, not a URL, with a ':' only " - "after a drive letter; the DR cold seed has no cloud source (ADR 0048 — no new " + f"[dr].{info.field_name} must be a LOCAL or UNC path, not a URL, with " + f"{_PATH_SHAPE_RULE}; the DR cold seed has no cloud source (ADR 0048 — no new " "egress)" ) return value @@ -8206,9 +8215,9 @@ def _no_cloud_restore_token(cls, value: str) -> str: # Positive, so a URL shape the scheme test misses is refused too (BACKLOG #5110). if not _is_local_or_unc_path(value): raise ValueError( - "[dr].restore_token must be a LOCAL or UNC path, not a URL, with a ':' only after " - "a drive letter; the DR restore-token is a local artifact on the DR box (ADR 0102 " - "— no new egress)" + "[dr].restore_token must be a LOCAL or UNC path, not a URL, with " + f"{_PATH_SHAPE_RULE}; the DR restore-token is a local artifact on the DR box (ADR " + "0102 — no new egress)" ) return value diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 6db9763751..72cf31f11a 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -1842,7 +1842,11 @@ def _preflight_destination(self) -> None: "DR backup destination %s is not writable at startup: %s " "(the scheduled backup will fail until this is fixed)", self._settings.destination_for_log, - safe_exc(OSError(exc.errno, exc.strerror)) + safe_exc( + OSError(exc.errno, exc.strerror) + if getattr(exc, "winerror", None) is None + else OSError(exc.errno, exc.strerror, None, getattr(exc, "winerror", None)) + ) if exc.strerror else shown_class_name(exc), ) diff --git a/tests/test_backup_dr_path_shape.py b/tests/test_backup_dr_path_shape.py index 3e22ed8aa9..ad65db4b80 100644 --- a/tests/test_backup_dr_path_shape.py +++ b/tests/test_backup_dr_path_shape.py @@ -11,6 +11,7 @@ from __future__ import annotations import logging +import os from pathlib import Path from typing import Any @@ -33,7 +34,9 @@ r"\\?\D:\mefor-backups", "//?/D:/mefor-backups", r"\\?/D:/mefor-backups", + "//?\\D:\\mefor-backups", r"\\.\D:\mefor-backups", + "//.\\D:\\mefor-backups", r"\\?\UNC\nas\share\backups", "D:/backups/ops@site/x", "/var/lib/mefor/backups", @@ -59,6 +62,14 @@ def test_a_local_or_unc_path_still_loads(section: str, field: str, value: str) - assert getattr(_build(section, field, value), field) == value +@pytest.mark.parametrize("value", [path for path in _PATHS if os.path.isabs(path)]) +def test_an_absolute_local_or_unc_seed_dir_still_loads(value: str) -> None: + """``seed_dir`` takes the shape check and ``_seed_dir_absolute``; an absolute path passes both. + + Mutation: refuse every ``:``. Red: the drive paths.""" + assert DrSettings(seed_dir=value).seed_dir == value + + _NOT_PATHS = [f"x://u:{_CANARY}@h/x", f"KEY:{_CANARY}://host/x", f"s3:bucket?sig={_CANARY}"] @@ -116,3 +127,24 @@ def test_the_runner_still_logs_a_path_destination( _runner(settings)._preflight_destination() assert destination in caplog.text assert "PermissionError: [Errno 13] Permission denied" in caplog.text + + +@pytest.mark.skipif(os.name != "nt", reason="only Windows builds an OSError with a winerror") +def test_the_warning_keeps_a_windows_error_code( + tmp_path: Path, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """An unreachable share fails with a WinError code an operator searches for; the rebuilt error + keeps it, without the filename. + + Mutation: rebuild the error from errno and strerror alone. Red: this test.""" + destination = str(tmp_path / "share") + + def refuse(self: Path, *args: Any, **kwargs: Any) -> None: + raise OSError(None, "The network path was not found", str(self), 53) + + monkeypatch.setattr(Path, "mkdir", refuse) + settings = BackupSettings(enabled=True, destination=destination) + with caplog.at_level(logging.WARNING, logger="messagefoundry.pipeline.dr_backup"): + _runner(settings)._preflight_destination() + assert "[WinError 53] The network path was not found" in caplog.text + assert caplog.text.count(destination) == 1 diff --git a/tests/test_cli_settings_error_render.py b/tests/test_cli_settings_error_render.py index 90659d0166..3a81cfa867 100644 --- a/tests/test_cli_settings_error_render.py +++ b/tests/test_cli_settings_error_render.py @@ -358,6 +358,8 @@ def test_a_json_caller_still_gets_a_json_error( "scheme-only": f"s3:bucket?sig={_CANARY}", "digit-first-scheme": f"1s://user:{_CANARY}@host/seed", "query-after-a-drive": f"C:/c?sig={_CANARY}", + "one-letter-scheme-three-slashes": f"x:///{_CANARY}@h/x", + "nul-in-a-drive-path": f"D:/b\x00{_CANARY}", } From a0042f9c4b59c84db6b7aeea3032edce327a7dd1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 23:13:19 -0600 Subject: [PATCH 23/35] docs: 5110 changelog entry moves to a changelog.d fragment (BACKLOG #5110) Review round 2. changelog.d/README.md says a pull request adds a fragment and does not edit CHANGELOG.md; this branch's entry moves to changelog.d/5110.security.md and names the control-character and prefix rules. The CONFIGURATION.md rows that describe _looks_like_url are left to open PR 3528; the wording they need is in the Builder's report. Proposed PR title: [backup]/[dr] path settings checked positively; DR runner startup lines log no URL destination (BACKLOG #5110) Proposed vault banner: CLOSED by engine PR : destination, seed_archive, seed_dir and restore_token take a positive local-or-UNC shape check, with the four reported values among the tested shapes; the DR runner's startup INFO and WARNING lines log destination_for_log. CONFIGURATION.md rows owed after PR 3528 lands. Verified-by: none --- CHANGELOG.md | 6 ------ changelog.d/5110.security.md | 7 +++++++ 2 files changed, 7 insertions(+), 6 deletions(-) create mode 100644 changelog.d/5110.security.md diff --git a/CHANGELOG.md b/CHANGELOG.md index b9e67bd4a5..0a4a43cbba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,12 +25,6 @@ All notable changes to MessageFoundry are documented here. The format follows while a TLS posture is declared, is refused without the address, which can keep a password. An `[auth]` OIDC endpoint whose host is not in `oidc_allowed_endpoints` is refused without the host or the allow-list. (`BACKLOG #5109`) -- **`[backup].destination`, `[dr].seed_archive`, `[dr].seed_dir` and `[dr].restore_token` must - have a local or UNC path's shape.** Besides a `://` URL, a value is now refused at load - when it has a `:` anywhere but right after a leading drive letter, a character Windows refuses - in a path (such as `?`), or an `@` in the segment after a drive letter's `//`. That catches URL - shapes the scheme test missed, and also refuses a POSIX path holding one of them. The DR backup - runner's startup lines no longer log a destination that is not such a path. (`BACKLOG #5110`) ## [0.5.3] — 2026-11-27 — Early Access diff --git a/changelog.d/5110.security.md b/changelog.d/5110.security.md new file mode 100644 index 0000000000..82de83d41d --- /dev/null +++ b/changelog.d/5110.security.md @@ -0,0 +1,7 @@ +- **`[backup].destination`, `[dr].seed_archive`, `[dr].seed_dir` and `[dr].restore_token` must + have a local or UNC path's shape.** Besides a `://` URL, a value is now refused at load + when it has a `:` anywhere but right after a leading drive letter, a character Windows refuses + in a path (such as `?`) or a control character, or an `@` in the segment after a drive + letter's `//`. A `\\?\` or `\\.\` prefix, in any slash spelling, is read past first. That catches URL + shapes the scheme test missed, and also refuses a POSIX path holding one of them. The DR backup + runner's startup lines no longer log a destination that is not such a path. (`BACKLOG #5110`) From 1b650f105d46d9afd6ed6797d539806ab6223c37 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 23:46:09 -0600 Subject: [PATCH 24/35] Sibling refusals name the setting and what it accepts, and quote no value (BACKLOG #5111) One shared helper, urlscreen.setting_must_be, writes the refusal for the eight "got scheme" sites (ai_broker, dicomweb, fhir twice, rest twice, smart, soap), [backup].schedule_at and snapshot_method, and the same shape found beside them: [retention].vacuum_at, and the load-time CRL and [store].ssl_root_cert path refusals, which quoted a value not yet shown to be a path. harden_crl_check's missing-file refusal names the setting alone; crl_label keeps quoting a path, with a line saying why that is safe (the file was there). ai_broker.py and rest.py import the helper at the refusal, to keep their hunks to those lines. Verified-by: tests --- messagefoundry/config/settings.py | 14 +-- messagefoundry/config/tls_policy.py | 11 +- messagefoundry/transports/ai_broker.py | 4 +- messagefoundry/transports/dicomweb.py | 5 +- messagefoundry/transports/fhir.py | 7 +- messagefoundry/transports/rest.py | 9 +- messagefoundry/transports/smart.py | 3 +- messagefoundry/transports/soap.py | 3 +- messagefoundry/urlscreen.py | 11 ++ tests/test_ai_broker.py | 2 +- tests/test_refusals_quote_no_scheme.py | 135 +++++++++++++++++++++++++ tests/test_settings.py | 8 +- tests/test_store_ssl.py | 2 +- 13 files changed, 188 insertions(+), 26 deletions(-) create mode 100644 tests/test_refusals_quote_no_scheme.py diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index baddc24fac..a4a3c640cd 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -144,7 +144,7 @@ from messagefoundry.service_status import is_safe_service_name from messagefoundry.serviceenv import ServiceEnvPosture, service_env_loosenings from messagefoundry.startupcode import StartupPosture, startup_loosenings -from messagefoundry.urlscreen import HTTP_DEFAULT_PORTS, UNCACHED_URLSPLIT +from messagefoundry.urlscreen import HTTP_DEFAULT_PORTS, UNCACHED_URLSPLIT, setting_must_be __all__ = [ "StoreBackend", @@ -382,7 +382,8 @@ def _refuse_a_missing_crl_file(value: str | None, setting: str) -> str | None: if value is not None and not value.strip(): raise ValueError(f"{setting} is set but empty. Remove it for no CRL, or name a CRL file") if value is not None and not Path(value).is_file(): - raise ValueError(f"{setting} path does not exist or is not a file: {value!r}") + # The value is not quoted: it has not been shown to be a path (BACKLOG #5111). + raise ValueError(setting_must_be(setting, "the path of an existing file")) return value @@ -1302,8 +1303,9 @@ def _ssl_root_cert_exists(cls, value: str | None) -> str | None: """Fail loud at load if the pinned cert path is missing, rather than surfacing a confusing error only at connect (#45). A path, not a secret — cheap to stat here. Empty/unset = no-op.""" if value and not Path(value).is_file(): + # The value is not quoted: it has not been shown to be a path (BACKLOG #5111). raise ValueError( - f"[store].ssl_root_cert path does not exist or is not a file: {value!r}" + setting_must_be("[store].ssl_root_cert", "the path of an existing file") ) return value @@ -3528,7 +3530,7 @@ def _non_negative_max_pass(cls, value: float) -> float: def _valid_clock_time(cls, value: str) -> str: value = value.strip() if value and cls._parse_clock(value) is None: - raise ValueError(f"vacuum_at must be empty or 'HH:MM' (24h), got {value!r}") + raise ValueError(setting_must_be("[retention].vacuum_at", "empty or 'HH:MM' (24h)")) return value @staticmethod @@ -7993,7 +7995,7 @@ def _valid_schedule(cls, value: str) -> str: # accept exactly the same "HH:MM" grammar (empty = on-demand only). value = value.strip() if value and RetentionSettings._parse_clock(value) is None: - raise ValueError(f"[backup].schedule_at must be empty or 'HH:MM' (24h), got {value!r}") + raise ValueError(setting_must_be("[backup].schedule_at", "empty or 'HH:MM' (24h)")) return value @field_validator("retention_keep") @@ -8008,7 +8010,7 @@ def _non_negative_keep(cls, value: int) -> int: def _known_snapshot_method(cls, value: str) -> str: if value not in _SNAPSHOT_METHODS: raise ValueError( - f"[backup].snapshot_method must be one of {sorted(_SNAPSHOT_METHODS)}, got {value!r}" + setting_must_be("[backup].snapshot_method", f"one of {sorted(_SNAPSHOT_METHODS)}") ) return value diff --git a/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index 216f0d6a5a..40aae94748 100644 --- a/messagefoundry/config/tls_policy.py +++ b/messagefoundry/config/tls_policy.py @@ -436,8 +436,11 @@ def harden_crl_check( label = crl_label(crl_file, setting) path = Path(crl_file) if not path.is_file(): + # Named by its setting alone where there is one: a value that is not a file has not been + # shown to be a path, so it is not quoted (BACKLOG #5111). + missing = f"the file {setting} names" if setting else label raise ValueError( - f"{label} does not exist; refusing to build a context that would advertise " + f"{missing} does not exist; refusing to build a context that would advertise " "revocation checking and perform none" ) @@ -881,7 +884,11 @@ def staged_crl(pem: bytes) -> Iterator[Path]: def crl_label(crl_file: str, setting: str | None) -> str: """How a CRL refusal names its file (BACKLOG #299): the setting the operator wrote, and no direction, since one CRL may guard a listener or an outbound hop. Without a setting, the path - alone, never a guessed setting name.""" + alone, never a guessed setting name. + + The path is safe to quote here because it names a file that was there (BACKLOG #5111): the + settings load check and :func:`harden_crl_check` refuse a CRL setting that names no file + without quoting it, so the value never reaches a label unless it opened as a file.""" return f"{setting} ({crl_file!r})" if setting else f"CRL file {crl_file!r}" diff --git a/messagefoundry/transports/ai_broker.py b/messagefoundry/transports/ai_broker.py index 5adb761b81..15ef23ef88 100644 --- a/messagefoundry/transports/ai_broker.py +++ b/messagefoundry/transports/ai_broker.py @@ -509,7 +509,9 @@ def __init__( "no escape. Use an https endpoint." ) if scheme != "https": - raise AiBrokerError(f"[ai].endpoint must be https, got scheme {scheme!r}") + from messagefoundry.urlscreen import setting_must_be # BACKLOG #5111 + + raise AiBrokerError(setting_must_be("[ai].endpoint", "https")) refuse_url_credentials(endpoint, "[ai].endpoint", use="[ai].api_key", error=AiBrokerError) if not api_key: raise AiBrokerError( diff --git a/messagefoundry/transports/dicomweb.py b/messagefoundry/transports/dicomweb.py index 194c9f27f5..e4cf808518 100644 --- a/messagefoundry/transports/dicomweb.py +++ b/messagefoundry/transports/dicomweb.py @@ -116,6 +116,7 @@ refuse_verify_off, url_scheme, ) +from messagefoundry.urlscreen import setting_must_be __all__ = ["DicomWebDestination", "dicomweb_credential_problem"] @@ -742,9 +743,7 @@ def __init__(self, config: Destination) -> None: _reject_url_control_chars(url, "url") scheme = url_scheme(url, "DICOMweb destination 'url'") if scheme not in ("http", "https"): - raise ValueError( - f"DICOMweb destination 'url' must be http or https, got scheme {scheme!r}" - ) + raise ValueError(setting_must_be("DICOMweb destination 'url'", "http or https")) refuse_url_credentials(url, "DICOMweb destination 'url'") _refuse_base_url_query_or_fragment(url, config.name) _refuse_ambiguous_credentials(s, config.name) diff --git a/messagefoundry/transports/fhir.py b/messagefoundry/transports/fhir.py index 6e89427eca..49bb0732d1 100644 --- a/messagefoundry/transports/fhir.py +++ b/messagefoundry/transports/fhir.py @@ -154,6 +154,7 @@ url_scheme, ) from messagefoundry.transports.signing import MessageSigner, signer_from_destination +from messagefoundry.urlscreen import setting_must_be __all__ = ["FhirDestination", "FhirLookupExecutor"] @@ -1117,7 +1118,7 @@ def __init__(self, config: Destination) -> None: _reject_config_control_chars(url, "url") scheme = url_scheme(url, "FHIR destination 'url'") if scheme not in ("http", "https"): - raise ValueError(f"FHIR destination 'url' must be http or https, got scheme {scheme!r}") + raise ValueError(setting_must_be("FHIR destination 'url'", "http or https")) refuse_url_credentials(url, "FHIR destination 'url'") self.base_url = url # BACKLOG #2060: names this hop in a bounded-read refusal, which never carries the URL. @@ -2259,9 +2260,7 @@ def _planned( _reject_config_control_chars(url, "url", f"lookup {cname!r}") scheme = url_scheme(url, f"FhirLookup {cname!r} 'url'") if scheme not in ("http", "https"): - raise ValueError( - f"FhirLookup {cname!r} 'url' must be http or https, got scheme {scheme!r}" - ) + raise ValueError(setting_must_be(f"FhirLookup {cname!r} 'url'", "http or https")) refuse_url_credentials(url, f"FhirLookup {cname!r} 'url'") # Named by hop_name_prefix, whose `;` keeps a credential-word lookup name from making # the log scrubber redact the rest of the refusal. diff --git a/messagefoundry/transports/rest.py b/messagefoundry/transports/rest.py index 4fa021cc3f..f9134d1995 100644 --- a/messagefoundry/transports/rest.py +++ b/messagefoundry/transports/rest.py @@ -2701,9 +2701,10 @@ def proxy_config_from_settings( ) proxy_scheme = url_scheme(proxy_url, "proxy_url", use="proxy_user/proxy_password") if proxy_scheme not in ("http", "https"): + from messagefoundry.urlscreen import setting_must_be # BACKLOG #5111 + raise ValueError( - f"proxy_url must be 'default' or an http(s):// address, got scheme {proxy_scheme!r} " - "(ADR 0126)" + setting_must_be("proxy_url", "'default' or an http(s):// address (ADR 0126)") ) # The credential first, so a URL that holds one is refused for it, with the advice that fits, # even where the parse below would refuse its shape too. @@ -2980,7 +2981,9 @@ def __init__(self, config: Destination) -> None: raise ValueError("REST destination requires a 'url' setting") scheme = url_scheme(url, "REST destination 'url'") if scheme not in ("http", "https"): - raise ValueError(f"REST destination 'url' must be http or https, got scheme {scheme!r}") + from messagefoundry.urlscreen import setting_must_be # BACKLOG #5111 + + raise ValueError(setting_must_be("REST destination 'url'", "http or https")) refuse_url_credentials(url, "REST destination 'url'") self.url = url # BACKLOG #2060: names this hop in a bounded-read refusal, which never carries the URL. diff --git a/messagefoundry/transports/smart.py b/messagefoundry/transports/smart.py index 9c73ccd855..1a67a47366 100644 --- a/messagefoundry/transports/smart.py +++ b/messagefoundry/transports/smart.py @@ -103,6 +103,7 @@ CompactJwtSigner, client_assertion_claims, ) +from messagefoundry.urlscreen import setting_must_be if TYPE_CHECKING: # only for the with_smart_backend() annotation — avoid importing heavy wiring from messagefoundry.config.wiring import ConnectionSpec, FhirLookupSpec @@ -349,7 +350,7 @@ def _check_token_url( token_url, cls._URL_SETTING, use=cls._CREDENTIAL_SETTINGS, error=cls._ERROR ) if scheme not in ("http", "https"): - raise cls._ERROR(f"{cls._URL_SETTING} must be http or https, got scheme {scheme!r}") + raise cls._ERROR(setting_must_be(cls._URL_SETTING, "http or https")) refuse_url_credentials( token_url, cls._URL_SETTING, use=cls._CREDENTIAL_SETTINGS, error=cls._ERROR ) diff --git a/messagefoundry/transports/soap.py b/messagefoundry/transports/soap.py index 8f7148eca7..68e388dd40 100644 --- a/messagefoundry/transports/soap.py +++ b/messagefoundry/transports/soap.py @@ -142,6 +142,7 @@ url_scheme, ) from messagefoundry.transports.signing import MessageSigner, signer_from_destination +from messagefoundry.urlscreen import setting_must_be __all__ = ["SoapDestination"] @@ -786,7 +787,7 @@ def __init__(self, config: Destination) -> None: raise ValueError("SOAP destination requires a 'url' setting") scheme = url_scheme(url, "SOAP destination 'url'") if scheme not in ("http", "https"): - raise ValueError(f"SOAP destination 'url' must be http or https, got scheme {scheme!r}") + raise ValueError(setting_must_be("SOAP destination 'url'", "http or https")) refuse_url_credentials(url, "SOAP destination 'url'") self.url = url # BACKLOG #2060: names this hop in a bounded-read refusal, which never carries the URL. diff --git a/messagefoundry/urlscreen.py b/messagefoundry/urlscreen.py index 8d5efdda43..ccce99c7fa 100644 --- a/messagefoundry/urlscreen.py +++ b/messagefoundry/urlscreen.py @@ -37,6 +37,17 @@ _URL_CREDENTIAL_USE = "basic_user/basic_password or bearer_token" +def setting_must_be(setting: str, accepted: str) -> str: + """The refusal text for a value ``setting`` does not accept: the setting and what it accepts, + and nothing of the value (vault BACKLOG #5111). + + The value is not quoted, its scheme included: the text in front of ``://`` is the value's own + and not a known word, so a password written there, or a user name read as the scheme where + ``://`` is missing, would print (vault BACKLOG #2850). The same holds for any setting value a + refusal could echo, so the shared form is used for them too.""" + return f"{setting} must be {accepted}" + + def _port_fields(netloc: str) -> tuple[str, ...]: """Every port field a reader takes from ``netloc``; empty when no reader sees a port. diff --git a/tests/test_ai_broker.py b/tests/test_ai_broker.py index 385dde01cd..02fbc0ff99 100644 --- a/tests/test_ai_broker.py +++ b/tests/test_ai_broker.py @@ -148,7 +148,7 @@ def test_broker_refuses_http_before_the_allowlist_and_other_schemes_as_not_https # whose http endpoint is refused anyway. Any other non-https scheme says https is required. with pytest.raises(AiBrokerError, match="cleartext http"): AiBroker(endpoint="http://ai.internal/v1/messages", api_key="k", allowed_endpoints=[]) - with pytest.raises(AiBrokerError, match="must be https, got scheme 'ftp'"): + with pytest.raises(AiBrokerError, match=r"^\[ai\]\.endpoint must be https$"): AiBroker(endpoint="ftp://ai.internal/x", api_key="k", allowed_endpoints=["ai.internal"]) diff --git a/tests/test_refusals_quote_no_scheme.py b/tests/test_refusals_quote_no_scheme.py new file mode 100644 index 0000000000..ab34864c90 --- /dev/null +++ b/tests/test_refusals_quote_no_scheme.py @@ -0,0 +1,135 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""Sibling refusals name the setting and what it accepts, and quote no part of the value +(BACKLOG #5111). + +The text in front of ``://`` is the value's own, so a scheme refusal that printed it printed +whatever the operator put there, a password included (vault BACKLOG #2850). Each case puts a +canary in the scheme position of a value the refusal rejects, and checks the message. +""" + +from __future__ import annotations + +import ssl +from collections.abc import Callable + +import pytest + +from messagefoundry.config.models import ConnectorType, Destination +from messagefoundry.config.settings import ( + BackupSettings, + EgressSettings, + RetentionSettings, + StoreSettings, +) +from messagefoundry.config.tls_policy import ( + HopPosture, + active_hop_posture, + crl_label, + harden_crl_check, +) +from messagefoundry.transports import build_destination +from messagefoundry.transports.ai_broker import AiBroker +from messagefoundry.transports.fhir import FhirLookupExecutor +from messagefoundry.transports.rest import proxy_config_from_settings +from messagefoundry.transports.smart import token_provider_from_settings +from messagefoundry.urlscreen import setting_must_be + +_CANARY = "canary5111" +#: A value whose scheme is the canary: refused by every scheme check, and quoted by the old text. +_URL = f"{_CANARY}://host.example/x" + + +def test_the_shared_text_names_the_setting_and_what_it_accepts() -> None: + assert setting_must_be("[x].url", "http or https") == "[x].url must be http or https" + + +def _refusal(build: Callable[[], object]) -> str: + with pytest.raises(ValueError) as caught: + build() + return str(caught.value) + + +def _destination(ctype: ConnectorType) -> Callable[[], object]: + def build() -> object: + return build_destination( + Destination(name="OB", type=ctype, settings={"url": _URL}), + egress=EgressSettings(deny_by_default=False), + ) + + return build + + +#: ``case id -> (builder, the text the refusal must hold)``. The text is what keeps a case honest: +#: one that failed for another reason cannot pass. +_CASES: dict[str, tuple[Callable[[], object], str]] = { + "ai-endpoint": ( + lambda: AiBroker(endpoint=_URL, api_key="k", allowed_endpoints=["host.example"]), + "[ai].endpoint must be https", + ), + "rest-url": (_destination(ConnectorType.REST), "REST destination 'url' must be http or https"), + "soap-url": (_destination(ConnectorType.SOAP), "SOAP destination 'url' must be http or https"), + "fhir-url": (_destination(ConnectorType.FHIR), "FHIR destination 'url' must be http or https"), + "dicomweb-url": ( + _destination(ConnectorType.DICOMWEB), + "DICOMweb destination 'url' must be http or https", + ), + "fhir-lookup-url": ( + lambda: FhirLookupExecutor( + {"lk": {"url": _URL}}, egress=EgressSettings(deny_by_default=False) + ), + "FhirLookup 'lk' 'url' must be http or https", + ), + "smart-token-url": ( + lambda: token_provider_from_settings({"smart_token_url": _URL, "smart_client_id": "c"}), + "must be http or https", + ), + "proxy-url": ( + lambda: proxy_config_from_settings( + {"url": "https://host.example/x", "proxy_url": _URL}, + dest_scheme="https", + connection=None, + ), + "proxy_url must be 'default' or an http(s):// address", + ), + "backup-schedule-at": ( + lambda: BackupSettings(schedule_at=_CANARY), + "[backup].schedule_at must be empty or 'HH:MM'", + ), + "backup-snapshot-method": ( + lambda: BackupSettings(snapshot_method=_CANARY), + "[backup].snapshot_method must be one of", + ), + "retention-vacuum-at": ( + lambda: RetentionSettings(vacuum_at=_CANARY), + "[retention].vacuum_at must be empty or 'HH:MM'", + ), + "store-ssl-root-cert": ( + lambda: StoreSettings(ssl_root_cert=_URL), + "[store].ssl_root_cert must be the path of an existing file", + ), +} + + +@pytest.mark.parametrize("case", list(_CASES)) +def test_a_refusal_quotes_no_part_of_the_value(case: str) -> None: + """Mutation: put ``got scheme {scheme!r}`` or ``got {value!r}`` back on any one refusal. Red: + that case.""" + build, needle = _CASES[case] + with active_hop_posture(HopPosture(enforcing=True)): + text = _refusal(build) + assert needle in text + assert _CANARY not in text.casefold() + + +def test_a_crl_that_is_no_file_is_refused_at_build_without_quoting_it() -> None: + """A value that is not a file has not been shown to be a path, so the build refusal names the + setting alone. A label for a file that exists still quotes its path. + + Mutation: refuse with ``crl_label`` again. Red: the first assertion.""" + ctx = ssl.create_default_context() + with pytest.raises(ValueError) as caught: + harden_crl_check(ctx, _URL, setting="[tls].crl_file") + assert "the file [tls].crl_file names does not exist" in str(caught.value) + assert _CANARY not in str(caught.value).casefold() + assert _CANARY in crl_label(f"/etc/{_CANARY}.pem", "[tls].crl_file") diff --git a/tests/test_settings.py b/tests/test_settings.py index 5e4a594a4f..fd92ae5ee5 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -2512,12 +2512,14 @@ def test_a_missing_crl_path_is_refused_at_load_naming_its_own_setting( """harden_crl_check refuses a missing file too, but only when the hop's context is built, and until BACKLOG #299 its refusal began "[tls] crl file" for every caller. That sent an operator who mistyped [api].tls_client_crl_file to go and fix [tls].crl_file. The load-time refusal - names the setting the operator wrote, and nothing else but the path.""" - absent = tmp_path / "absent-crl.pem" + names the setting the operator wrote, and since BACKLOG #5111 not the value, which has not + been shown to be a path.""" + absent = tmp_path / "absent-crl-canary5111.pem" cfg = _write(tmp_path / "messagefoundry.toml", _toml(section, key, str(absent))) with pytest.raises(ValidationError) as excinfo: load_settings(config_path=cfg, environ={}) - assert f"{name} path does not exist or is not a file: {str(absent)!r}" in str(excinfo.value) + assert f"{name} must be the path of an existing file" in str(excinfo.value) + assert "canary5111" not in str(excinfo.value) @pytest.mark.parametrize(("section", "key", "name"), _CRL_KNOBS) diff --git a/tests/test_store_ssl.py b/tests/test_store_ssl.py index 9defbe9305..7e060c32e7 100644 --- a/tests/test_store_ssl.py +++ b/tests/test_store_ssl.py @@ -496,7 +496,7 @@ def test_ssl_root_cert_rejected_for_sqlite(tmp_path: object) -> None: def test_ssl_root_cert_missing_file_rejected() -> None: # A path that does not exist fails loud at load (#45), not confusingly at connect. - with pytest.raises(ValidationError, match="does not exist"): + with pytest.raises(ValidationError, match="must be the path of an existing file"): StoreSettings( backend=StoreBackend.POSTGRES, server="db.example", From da3d53fbf245e65f71ae042fc0db82056222cd04 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 23:47:27 -0600 Subject: [PATCH 25/35] docs: changelog fragment for the refusals that stop quoting the value (BACKLOG #5111) Proposed PR title: Sibling refusals name the setting and what it accepts, and quote no value (BACKLOG #5111) Proposed vault banner: CLOSED by engine PR : urlscreen.setting_must_be writes the eight got-scheme refusals, schedule_at, snapshot_method, vacuum_at and the load-time CRL and ssl_root_cert path refusals, with a canary test per refusal; crl_label carries the line saying why a path it quotes is safe. Verified-by: none --- changelog.d/5111.security.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 changelog.d/5111.security.md diff --git a/changelog.d/5111.security.md b/changelog.d/5111.security.md new file mode 100644 index 0000000000..17e13e4a9d --- /dev/null +++ b/changelog.d/5111.security.md @@ -0,0 +1,6 @@ +- **Scheme, clock-time and missing-file refusals no longer quote the value.** A refused URL scheme + on the `[ai]` endpoint, a REST, SOAP, FHIR or DICOMweb destination, a FHIR lookup, a SMART token + endpoint or a `proxy_url`; a refused `[backup].schedule_at`, `[backup].snapshot_method` or + `[retention].vacuum_at`; and a CRL setting or `[store].ssl_root_cert` naming no file now name + the setting and what it accepts, and nothing of the value, since the text in front of `://` + can be a password. (`BACKLOG #5111`) From 9f5f2bbdd925eb2b695d3086bf62e7bca46df728 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 00:26:05 -0600 Subject: [PATCH 26/35] Scheme refusals name the connection; api client base-URL refusal quotes no scheme (BACKLOG #5111) Review round 1. The REST, SOAP, FHIR and DICOMweb scheme refusals now name the destination, since without the scheme nothing else told the operator which one failed. The api client's base-URL refusal quoted the scheme, which is a user name when '//' is missing; it no longer does. harden_crl_check's missing-file refusal leads with the setting, as its docstring says. setting_must_be's and crl_label's docstrings no longer claim more than holds. test_hop_refusal_revocation's pin moves to the new text; tests add oauth2_token_url and the api client. Verified-by: tests --- messagefoundry/apiclient/client.py | 4 ++- messagefoundry/config/tls_policy.py | 9 +++--- messagefoundry/transports/dicomweb.py | 4 ++- messagefoundry/transports/fhir.py | 4 ++- messagefoundry/transports/rest.py | 4 ++- messagefoundry/transports/soap.py | 4 ++- messagefoundry/urlscreen.py | 4 ++- tests/test_hop_refusal_revocation.py | 4 ++- tests/test_refusals_quote_no_scheme.py | 42 +++++++++++++++++++++++--- 9 files changed, 63 insertions(+), 16 deletions(-) diff --git a/messagefoundry/apiclient/client.py b/messagefoundry/apiclient/client.py index 36c412ccca..e300e17014 100644 --- a/messagefoundry/apiclient/client.py +++ b/messagefoundry/apiclient/client.py @@ -533,7 +533,9 @@ def _assert_safe_transport(base_url: str, *, allow_insecure: bool) -> bool: raise ApiError("refusing a base URL that does not parse as a URL.") scheme = url.scheme.lower() if scheme not in _ALLOWED_URL_SCHEMES: - found = f"scheme {scheme!r}" if scheme else "no scheme" + # The scheme is not quoted: the text in front of ':' is the URL's own, so a user name or + # password there would print (BACKLOG #5111). + found = "another scheme" if scheme else "no scheme" raise ApiError( f"refusing a base URL with {found}: this client permits only the " f"{' and '.join(sorted(_ALLOWED_URL_SCHEMES))} schemes." diff --git a/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index 40aae94748..96e517129f 100644 --- a/messagefoundry/config/tls_policy.py +++ b/messagefoundry/config/tls_policy.py @@ -438,7 +438,7 @@ def harden_crl_check( if not path.is_file(): # Named by its setting alone where there is one: a value that is not a file has not been # shown to be a path, so it is not quoted (BACKLOG #5111). - missing = f"the file {setting} names" if setting else label + missing = f"{setting} names a file that" if setting else label raise ValueError( f"{missing} does not exist; refusing to build a context that would advertise " "revocation checking and perform none" @@ -886,9 +886,10 @@ def crl_label(crl_file: str, setting: str | None) -> str: direction, since one CRL may guard a listener or an outbound hop. Without a setting, the path alone, never a guessed setting name. - The path is safe to quote here because it names a file that was there (BACKLOG #5111): the - settings load check and :func:`harden_crl_check` refuse a CRL setting that names no file - without quoting it, so the value never reaches a label unless it opened as a file.""" + With a setting, the path is quoted only for a file that was there (BACKLOG #5111): the + settings load check and :func:`harden_crl_check` refuse a setting that names no file without + quoting it. Without a setting, :func:`harden_crl_check`'s missing-file refusal still quotes + the value through this label, since it is the only name there is.""" return f"{setting} ({crl_file!r})" if setting else f"CRL file {crl_file!r}" diff --git a/messagefoundry/transports/dicomweb.py b/messagefoundry/transports/dicomweb.py index e4cf808518..08efbb709d 100644 --- a/messagefoundry/transports/dicomweb.py +++ b/messagefoundry/transports/dicomweb.py @@ -743,7 +743,9 @@ def __init__(self, config: Destination) -> None: _reject_url_control_chars(url, "url") scheme = url_scheme(url, "DICOMweb destination 'url'") if scheme not in ("http", "https"): - raise ValueError(setting_must_be("DICOMweb destination 'url'", "http or https")) + raise ValueError( + setting_must_be(f"DICOMweb destination {config.name!r} 'url'", "http or https") + ) refuse_url_credentials(url, "DICOMweb destination 'url'") _refuse_base_url_query_or_fragment(url, config.name) _refuse_ambiguous_credentials(s, config.name) diff --git a/messagefoundry/transports/fhir.py b/messagefoundry/transports/fhir.py index 49bb0732d1..71089540cb 100644 --- a/messagefoundry/transports/fhir.py +++ b/messagefoundry/transports/fhir.py @@ -1118,7 +1118,9 @@ def __init__(self, config: Destination) -> None: _reject_config_control_chars(url, "url") scheme = url_scheme(url, "FHIR destination 'url'") if scheme not in ("http", "https"): - raise ValueError(setting_must_be("FHIR destination 'url'", "http or https")) + raise ValueError( + setting_must_be(f"FHIR destination {config.name!r} 'url'", "http or https") + ) refuse_url_credentials(url, "FHIR destination 'url'") self.base_url = url # BACKLOG #2060: names this hop in a bounded-read refusal, which never carries the URL. diff --git a/messagefoundry/transports/rest.py b/messagefoundry/transports/rest.py index f9134d1995..8ac5dfc0fb 100644 --- a/messagefoundry/transports/rest.py +++ b/messagefoundry/transports/rest.py @@ -2983,7 +2983,9 @@ def __init__(self, config: Destination) -> None: if scheme not in ("http", "https"): from messagefoundry.urlscreen import setting_must_be # BACKLOG #5111 - raise ValueError(setting_must_be("REST destination 'url'", "http or https")) + raise ValueError( + setting_must_be(f"REST destination {config.name!r} 'url'", "http or https") + ) refuse_url_credentials(url, "REST destination 'url'") self.url = url # BACKLOG #2060: names this hop in a bounded-read refusal, which never carries the URL. diff --git a/messagefoundry/transports/soap.py b/messagefoundry/transports/soap.py index 68e388dd40..3e6160e028 100644 --- a/messagefoundry/transports/soap.py +++ b/messagefoundry/transports/soap.py @@ -787,7 +787,9 @@ def __init__(self, config: Destination) -> None: raise ValueError("SOAP destination requires a 'url' setting") scheme = url_scheme(url, "SOAP destination 'url'") if scheme not in ("http", "https"): - raise ValueError(setting_must_be("SOAP destination 'url'", "http or https")) + raise ValueError( + setting_must_be(f"SOAP destination {config.name!r} 'url'", "http or https") + ) refuse_url_credentials(url, "SOAP destination 'url'") self.url = url # BACKLOG #2060: names this hop in a bounded-read refusal, which never carries the URL. diff --git a/messagefoundry/urlscreen.py b/messagefoundry/urlscreen.py index ccce99c7fa..fbb2a08dd4 100644 --- a/messagefoundry/urlscreen.py +++ b/messagefoundry/urlscreen.py @@ -44,7 +44,9 @@ def setting_must_be(setting: str, accepted: str) -> str: The value is not quoted, its scheme included: the text in front of ``://`` is the value's own and not a known word, so a password written there, or a user name read as the scheme where ``://`` is missing, would print (vault BACKLOG #2850). The same holds for any setting value a - refusal could echo, so the shared form is used for them too.""" + refusal could echo. At least the scheme refusals of the HTTP-family connectors, the ``[ai]`` + endpoint and ``proxy_url``, and the ``[backup]``, ``[retention]`` clock-time and the CRL and + ``[store].ssl_root_cert`` missing-file refusals use it; other refusals still quote a value.""" return f"{setting} must be {accepted}" diff --git a/tests/test_hop_refusal_revocation.py b/tests/test_hop_refusal_revocation.py index 042afa2210..f0510d106c 100644 --- a/tests/test_hop_refusal_revocation.py +++ b/tests/test_hop_refusal_revocation.py @@ -752,7 +752,9 @@ def test_the_store_crl_is_refused_where_it_could_not_be_loaded(crl_bundle: str) # A missing path is caught at LOAD too, naming [store].ssl_crl_file -- harden_crl_check would # catch it at store open but hard-codes the prefix "[tls] crl file" for every call site, so it # would report a store setting against the wrong config section. - with pytest.raises(ValueError, match=r"\[store\].ssl_crl_file path does not exist"): + with pytest.raises( + ValueError, match=r"\[store\].ssl_crl_file must be the path of an existing file" + ): _pg(ssl_root_cert=crl_bundle, ssl_crl_file=str(crl_bundle) + ".absent") diff --git a/tests/test_refusals_quote_no_scheme.py b/tests/test_refusals_quote_no_scheme.py index ab34864c90..46da13df64 100644 --- a/tests/test_refusals_quote_no_scheme.py +++ b/tests/test_refusals_quote_no_scheme.py @@ -15,6 +15,7 @@ import pytest +from messagefoundry.apiclient.client import ApiError, EngineClient from messagefoundry.config.models import ConnectorType, Destination from messagefoundry.config.settings import ( BackupSettings, @@ -31,6 +32,7 @@ from messagefoundry.transports import build_destination from messagefoundry.transports.ai_broker import AiBroker from messagefoundry.transports.fhir import FhirLookupExecutor +from messagefoundry.transports.http_auth import oauth2_cc_provider_from_settings from messagefoundry.transports.rest import proxy_config_from_settings from messagefoundry.transports.smart import token_provider_from_settings from messagefoundry.urlscreen import setting_must_be @@ -67,12 +69,21 @@ def build() -> object: lambda: AiBroker(endpoint=_URL, api_key="k", allowed_endpoints=["host.example"]), "[ai].endpoint must be https", ), - "rest-url": (_destination(ConnectorType.REST), "REST destination 'url' must be http or https"), - "soap-url": (_destination(ConnectorType.SOAP), "SOAP destination 'url' must be http or https"), - "fhir-url": (_destination(ConnectorType.FHIR), "FHIR destination 'url' must be http or https"), + "rest-url": ( + _destination(ConnectorType.REST), + "REST destination 'OB' 'url' must be http or https", + ), + "soap-url": ( + _destination(ConnectorType.SOAP), + "SOAP destination 'OB' 'url' must be http or https", + ), + "fhir-url": ( + _destination(ConnectorType.FHIR), + "FHIR destination 'OB' 'url' must be http or https", + ), "dicomweb-url": ( _destination(ConnectorType.DICOMWEB), - "DICOMweb destination 'url' must be http or https", + "DICOMweb destination 'OB' 'url' must be http or https", ), "fhir-lookup-url": ( lambda: FhirLookupExecutor( @@ -84,6 +95,16 @@ def build() -> object: lambda: token_provider_from_settings({"smart_token_url": _URL, "smart_client_id": "c"}), "must be http or https", ), + "oauth2-token-url": ( + lambda: oauth2_cc_provider_from_settings( + { + "oauth2_token_url": _URL, + "oauth2_client_id": "c", + "oauth2_client_secret": "synthetic", # nosec B105 - a made-up test value + } + ), + "oauth2_token_url must be http or https", + ), "proxy-url": ( lambda: proxy_config_from_settings( {"url": "https://host.example/x", "proxy_url": _URL}, @@ -130,6 +151,17 @@ def test_a_crl_that_is_no_file_is_refused_at_build_without_quoting_it() -> None: ctx = ssl.create_default_context() with pytest.raises(ValueError) as caught: harden_crl_check(ctx, _URL, setting="[tls].crl_file") - assert "the file [tls].crl_file names does not exist" in str(caught.value) + assert "[tls].crl_file names a file that does not exist" in str(caught.value) assert _CANARY not in str(caught.value).casefold() assert _CANARY in crl_label(f"/etc/{_CANARY}.pem", "[tls].crl_file") + + +def test_the_api_client_refuses_a_base_url_scheme_without_quoting_it() -> None: + """A base URL with no ``//`` reads its user name as the scheme, so quoting the scheme printed + it. + + Mutation: quote the scheme again. Red: the canary.""" + with pytest.raises(ApiError) as caught: + EngineClient(f"{_CANARY}:secret@engine.example:8765") + assert "refusing a base URL with another scheme" in str(caught.value) + assert _CANARY not in str(caught.value).casefold() From 14eefe82ec51674cf71c75ffdcd2fbc707a6afbc Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 00:27:51 -0600 Subject: [PATCH 27/35] docs: 5111 fragment names the OAuth2 token endpoint and the API client (BACKLOG #5111) Review round 1 follows the code change. Proposed PR title: Sibling refusals name the setting and what it accepts, and quote no value (BACKLOG #5111) Proposed vault banner: CLOSED by engine PR : urlscreen.setting_must_be writes the eight got-scheme refusals, schedule_at, snapshot_method, vacuum_at and the load-time CRL and ssl_root_cert path refusals, the API client's base-URL refusal no longer quotes its scheme, with a canary test per refusal; crl_label says when a path it quotes is safe. Verified-by: none --- changelog.d/5111.security.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/changelog.d/5111.security.md b/changelog.d/5111.security.md index 17e13e4a9d..52dc6c73a1 100644 --- a/changelog.d/5111.security.md +++ b/changelog.d/5111.security.md @@ -1,6 +1,7 @@ - **Scheme, clock-time and missing-file refusals no longer quote the value.** A refused URL scheme - on the `[ai]` endpoint, a REST, SOAP, FHIR or DICOMweb destination, a FHIR lookup, a SMART token - endpoint or a `proxy_url`; a refused `[backup].schedule_at`, `[backup].snapshot_method` or - `[retention].vacuum_at`; and a CRL setting or `[store].ssl_root_cert` naming no file now name - the setting and what it accepts, and nothing of the value, since the text in front of `://` - can be a password. (`BACKLOG #5111`) + on the `[ai]` endpoint, a REST, SOAP, FHIR or DICOMweb destination, a FHIR lookup, a SMART or + OAuth2 token endpoint, a `proxy_url` or the API client's base URL; a refused + `[backup].schedule_at`, `[backup].snapshot_method` or `[retention].vacuum_at`; and a CRL setting + or `[store].ssl_root_cert` naming no file now name the setting and what it accepts, and nothing + of the value, since the text in front of `://` can be a password. A destination's refusal now + names the destination. (`BACKLOG #5111`) From 3505444f3a35571abda19820519e5fb3262a0be6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 01:22:03 -0600 Subject: [PATCH 28/35] Scheme refusals name the connection through hop_name_prefix (BACKLOG #5111) Review round 2. The REST, SOAP, FHIR and DICOMweb scheme refusals lead with hop_name_prefix(config.name), as their neighbours do, in place of an ad-hoc label; the SMART/OAuth2 token-URL and proxy_url scheme refusals now name their connection too. harden_crl_check's setting-named refusal says the path does not exist or is not a file, which is true of a directory. The settings docstrings no longer say "A path, not a secret". test_api_tls_client_trust pins the new load-time CRL text, and test_cli_offline_resolution swaps its public-address NFKC case, whose refusal stopped quoting the value under #5109, for an [update_check].mode case that still quotes. Verified-by: tests --- messagefoundry/config/settings.py | 6 ++++-- messagefoundry/config/tls_policy.py | 8 ++++++-- messagefoundry/transports/dicomweb.py | 3 ++- messagefoundry/transports/fhir.py | 3 ++- messagefoundry/transports/rest.py | 6 ++++-- messagefoundry/transports/smart.py | 4 +++- messagefoundry/transports/soap.py | 3 ++- messagefoundry/urlscreen.py | 5 +++-- tests/test_api_tls_client_trust.py | 2 +- tests/test_cli_offline_resolution.py | 8 ++++---- tests/test_refusals_quote_no_scheme.py | 22 +++++++++++++--------- 11 files changed, 44 insertions(+), 26 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index a4a3c640cd..3850bc8d33 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -374,7 +374,8 @@ def _refuse_a_missing_crl_file(value: str | None, setting: str) -> str | None: ``harden_crl_check`` would catch it when the hop's context is built, but its refusals hard-code the prefix ``[tls] crl file`` for every call site, so a bad path on any other CRL knob would be - reported against the wrong config section. A path, not a secret. + reported against the wrong config section. The refusal does not quote the value: one that is + not a file has not been shown to be a path, and could be a pasted secret (BACKLOG #5111). A blank value is refused too, as ``refuse_a_blank_anchor_pin`` refuses a blank pin. ``None`` is the only spelling of "no CRL": some consumers test ``is not None`` and would hand ``""`` to @@ -1301,7 +1302,8 @@ def _require_server_db_fields(self) -> StoreSettings: @classmethod def _ssl_root_cert_exists(cls, value: str | None) -> str | None: """Fail loud at load if the pinned cert path is missing, rather than surfacing a confusing - error only at connect (#45). A path, not a secret — cheap to stat here. Empty/unset = no-op.""" + error only at connect (#45). Cheap to stat here. Empty/unset = no-op. The refusal does not + quote the value: one that is not a file has not been shown to be a path (BACKLOG #5111).""" if value and not Path(value).is_file(): # The value is not quoted: it has not been shown to be a path (BACKLOG #5111). raise ValueError( diff --git a/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index 96e517129f..9819dda2f8 100644 --- a/messagefoundry/config/tls_policy.py +++ b/messagefoundry/config/tls_policy.py @@ -438,9 +438,13 @@ def harden_crl_check( if not path.is_file(): # Named by its setting alone where there is one: a value that is not a file has not been # shown to be a path, so it is not quoted (BACKLOG #5111). - missing = f"{setting} names a file that" if setting else label + missing = ( + f"{setting} names a path that does not exist or is not a file" + if setting + else f"{label} does not exist" + ) raise ValueError( - f"{missing} does not exist; refusing to build a context that would advertise " + f"{missing}; refusing to build a context that would advertise " "revocation checking and perform none" ) diff --git a/messagefoundry/transports/dicomweb.py b/messagefoundry/transports/dicomweb.py index 08efbb709d..fee79058fe 100644 --- a/messagefoundry/transports/dicomweb.py +++ b/messagefoundry/transports/dicomweb.py @@ -744,7 +744,8 @@ def __init__(self, config: Destination) -> None: scheme = url_scheme(url, "DICOMweb destination 'url'") if scheme not in ("http", "https"): raise ValueError( - setting_must_be(f"DICOMweb destination {config.name!r} 'url'", "http or https") + f"{hop_name_prefix(config.name)}" + + setting_must_be("DICOMweb destination 'url'", "http or https") ) refuse_url_credentials(url, "DICOMweb destination 'url'") _refuse_base_url_query_or_fragment(url, config.name) diff --git a/messagefoundry/transports/fhir.py b/messagefoundry/transports/fhir.py index 71089540cb..d2437838eb 100644 --- a/messagefoundry/transports/fhir.py +++ b/messagefoundry/transports/fhir.py @@ -1119,7 +1119,8 @@ def __init__(self, config: Destination) -> None: scheme = url_scheme(url, "FHIR destination 'url'") if scheme not in ("http", "https"): raise ValueError( - setting_must_be(f"FHIR destination {config.name!r} 'url'", "http or https") + f"{hop_name_prefix(config.name)}" + + setting_must_be("FHIR destination 'url'", "http or https") ) refuse_url_credentials(url, "FHIR destination 'url'") self.base_url = url diff --git a/messagefoundry/transports/rest.py b/messagefoundry/transports/rest.py index 8ac5dfc0fb..1b4b044a44 100644 --- a/messagefoundry/transports/rest.py +++ b/messagefoundry/transports/rest.py @@ -2704,7 +2704,8 @@ def proxy_config_from_settings( from messagefoundry.urlscreen import setting_must_be # BACKLOG #5111 raise ValueError( - setting_must_be("proxy_url", "'default' or an http(s):// address (ADR 0126)") + f"{hop_name_prefix(connection)}" + + setting_must_be("proxy_url", "'default' or an http(s):// address (ADR 0126)") ) # The credential first, so a URL that holds one is refused for it, with the advice that fits, # even where the parse below would refuse its shape too. @@ -2984,7 +2985,8 @@ def __init__(self, config: Destination) -> None: from messagefoundry.urlscreen import setting_must_be # BACKLOG #5111 raise ValueError( - setting_must_be(f"REST destination {config.name!r} 'url'", "http or https") + f"{hop_name_prefix(config.name)}" + + setting_must_be("REST destination 'url'", "http or https") ) refuse_url_credentials(url, "REST destination 'url'") self.url = url diff --git a/messagefoundry/transports/smart.py b/messagefoundry/transports/smart.py index 1a67a47366..63c068f4e1 100644 --- a/messagefoundry/transports/smart.py +++ b/messagefoundry/transports/smart.py @@ -350,7 +350,9 @@ def _check_token_url( token_url, cls._URL_SETTING, use=cls._CREDENTIAL_SETTINGS, error=cls._ERROR ) if scheme not in ("http", "https"): - raise cls._ERROR(setting_must_be(cls._URL_SETTING, "http or https")) + raise cls._ERROR( + f"{hop_name_prefix(connection)}{setting_must_be(cls._URL_SETTING, 'http or https')}" + ) refuse_url_credentials( token_url, cls._URL_SETTING, use=cls._CREDENTIAL_SETTINGS, error=cls._ERROR ) diff --git a/messagefoundry/transports/soap.py b/messagefoundry/transports/soap.py index 3e6160e028..501769320c 100644 --- a/messagefoundry/transports/soap.py +++ b/messagefoundry/transports/soap.py @@ -788,7 +788,8 @@ def __init__(self, config: Destination) -> None: scheme = url_scheme(url, "SOAP destination 'url'") if scheme not in ("http", "https"): raise ValueError( - setting_must_be(f"SOAP destination {config.name!r} 'url'", "http or https") + f"{hop_name_prefix(config.name)}" + + setting_must_be("SOAP destination 'url'", "http or https") ) refuse_url_credentials(url, "SOAP destination 'url'") self.url = url diff --git a/messagefoundry/urlscreen.py b/messagefoundry/urlscreen.py index fbb2a08dd4..2b5413b8b7 100644 --- a/messagefoundry/urlscreen.py +++ b/messagefoundry/urlscreen.py @@ -45,8 +45,9 @@ def setting_must_be(setting: str, accepted: str) -> str: and not a known word, so a password written there, or a user name read as the scheme where ``://`` is missing, would print (vault BACKLOG #2850). The same holds for any setting value a refusal could echo. At least the scheme refusals of the HTTP-family connectors, the ``[ai]`` - endpoint and ``proxy_url``, and the ``[backup]``, ``[retention]`` clock-time and the CRL and - ``[store].ssl_root_cert`` missing-file refusals use it; other refusals still quote a value.""" + endpoint and ``proxy_url``, the ``[backup]`` and ``[retention]`` clock-time refusals, and the + load-time CRL and ``[store].ssl_root_cert`` missing-file refusals use it. ``harden_crl_check`` + builds its own text; other refusals still quote a value.""" return f"{setting} must be {accepted}" diff --git a/tests/test_api_tls_client_trust.py b/tests/test_api_tls_client_trust.py index 2b3eda6c33..0aca844ef5 100644 --- a/tests/test_api_tls_client_trust.py +++ b/tests/test_api_tls_client_trust.py @@ -614,7 +614,7 @@ def _denied(path: str) -> bytes: def test_a_missing_crl_still_refuses_with_its_own_message( two_tier: _TwoTier, tmp_path: Path ) -> None: - with pytest.raises(ValueError, match="does not exist"): + with pytest.raises(ValueError, match="must be the path of an existing file"): build_api_ssl_context(_settings(two_tier, tmp_path / "absent.pem")) diff --git a/tests/test_cli_offline_resolution.py b/tests/test_cli_offline_resolution.py index 055b9d8990..9c2a480412 100644 --- a/tests/test_cli_offline_resolution.py +++ b/tests/test_cli_offline_resolution.py @@ -840,12 +840,12 @@ def _settings_failure_output( #: Settings that fail on a validator whose message quotes the value it refused, with a password in -#: the value: a trusted_proxies URL, and a public address urlsplit refuses under NFKC. +#: the value: a trusted_proxies URL, and an [update_check].mode. The public-address NFKC case left +#: this table when that refusal stopped quoting the value (BACKLOG #5109), so its control could +#: no longer fire; a case here must be a refusal that still quotes. _QUOTING_FAILURES = { "trusted-proxies": f'[api]\ntrusted_proxies = ["https://u:{_URL_PASSWORD}@host/"]\n', - "public-address-nfkc": ( - f'[security]\nweb_console_public_address = "https://u:{_URL_PASSWORD}@host\\uff0fx"\n' - ), + "update-check-mode": f'[update_check]\nmode = "https://u:{_URL_PASSWORD}@host/"\n', } diff --git a/tests/test_refusals_quote_no_scheme.py b/tests/test_refusals_quote_no_scheme.py index 46da13df64..9833203f6f 100644 --- a/tests/test_refusals_quote_no_scheme.py +++ b/tests/test_refusals_quote_no_scheme.py @@ -34,7 +34,7 @@ from messagefoundry.transports.fhir import FhirLookupExecutor from messagefoundry.transports.http_auth import oauth2_cc_provider_from_settings from messagefoundry.transports.rest import proxy_config_from_settings -from messagefoundry.transports.smart import token_provider_from_settings +from messagefoundry.transports.smart import SmartBackendTokenProvider, token_provider_from_settings from messagefoundry.urlscreen import setting_must_be _CANARY = "canary5111" @@ -71,19 +71,19 @@ def build() -> object: ), "rest-url": ( _destination(ConnectorType.REST), - "REST destination 'OB' 'url' must be http or https", + "connection 'OB'; REST destination 'url' must be http or https", ), "soap-url": ( _destination(ConnectorType.SOAP), - "SOAP destination 'OB' 'url' must be http or https", + "connection 'OB'; SOAP destination 'url' must be http or https", ), "fhir-url": ( _destination(ConnectorType.FHIR), - "FHIR destination 'OB' 'url' must be http or https", + "connection 'OB'; FHIR destination 'url' must be http or https", ), "dicomweb-url": ( _destination(ConnectorType.DICOMWEB), - "DICOMweb destination 'OB' 'url' must be http or https", + "connection 'OB'; DICOMweb destination 'url' must be http or https", ), "fhir-lookup-url": ( lambda: FhirLookupExecutor( @@ -93,7 +93,11 @@ def build() -> object: ), "smart-token-url": ( lambda: token_provider_from_settings({"smart_token_url": _URL, "smart_client_id": "c"}), - "must be http or https", + "smart_token_url must be http or https", + ), + "smart-token-url-names-its-connection": ( + lambda: SmartBackendTokenProvider._check_token_url(_URL, connection="OB"), + "connection 'OB'; smart_token_url must be http or https", ), "oauth2-token-url": ( lambda: oauth2_cc_provider_from_settings( @@ -109,9 +113,9 @@ def build() -> object: lambda: proxy_config_from_settings( {"url": "https://host.example/x", "proxy_url": _URL}, dest_scheme="https", - connection=None, + connection="OB", ), - "proxy_url must be 'default' or an http(s):// address", + "connection 'OB'; proxy_url must be 'default' or an http(s):// address", ), "backup-schedule-at": ( lambda: BackupSettings(schedule_at=_CANARY), @@ -151,7 +155,7 @@ def test_a_crl_that_is_no_file_is_refused_at_build_without_quoting_it() -> None: ctx = ssl.create_default_context() with pytest.raises(ValueError) as caught: harden_crl_check(ctx, _URL, setting="[tls].crl_file") - assert "[tls].crl_file names a file that does not exist" in str(caught.value) + assert "[tls].crl_file names a path that does not exist or is not a file" in str(caught.value) assert _CANARY not in str(caught.value).casefold() assert _CANARY in crl_label(f"/etc/{_CANARY}.pem", "[tls].crl_file") From 73cac06d26b427c6802f03ed54e9bdf8ed733ebc Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 01:25:53 -0600 Subject: [PATCH 29/35] docs: 5111 fragment says which refusals name the connection (BACKLOG #5111) Review round 2: the fragment no longer says every refusal names what the setting accepts or that every destination refusal names the destination. Proposed PR title: Sibling refusals name the setting and what it accepts, and quote no value (BACKLOG #5111) Proposed vault banner: CLOSED by engine PR : urlscreen.setting_must_be writes the eight got-scheme refusals, schedule_at, snapshot_method, vacuum_at and the load-time CRL and ssl_root_cert path refusals; the scheme refusals of destinations, token URLs and proxy_url name their connection; the API client's base-URL refusal quotes no scheme; a canary test per refusal. Verified-by: none --- changelog.d/5111.security.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/changelog.d/5111.security.md b/changelog.d/5111.security.md index 52dc6c73a1..77b7292510 100644 --- a/changelog.d/5111.security.md +++ b/changelog.d/5111.security.md @@ -2,6 +2,8 @@ on the `[ai]` endpoint, a REST, SOAP, FHIR or DICOMweb destination, a FHIR lookup, a SMART or OAuth2 token endpoint, a `proxy_url` or the API client's base URL; a refused `[backup].schedule_at`, `[backup].snapshot_method` or `[retention].vacuum_at`; and a CRL setting - or `[store].ssl_root_cert` naming no file now name the setting and what it accepts, and nothing - of the value, since the text in front of `://` can be a password. A destination's refusal now - names the destination. (`BACKLOG #5111`) + or `[store].ssl_root_cert` naming no file at load now name the setting and nothing of the value, + since the text in front of `://` can be a password. Most also say what the setting accepts. The + scheme refusal of a destination, a SMART token endpoint or a `proxy_url` now leads with the + connection's name where the engine knows it; other refusals on the same connection may not. + (`BACKLOG #5111`) From 1039ab1893ea284309f8058839717fa005728ed5 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 03:38:34 -0600 Subject: [PATCH 30/35] Snapshot hazard test keeps "?" out of the backup destination (BACKLOG #5110) The [backup].destination path-shape check refuses a "?" on every platform, as the 5110 changelog fragment states, so the POSIX-only "?" case of test_backup_verify_and_restore_count_the_real_snapshot_under_hazard_paths failed to build its BackupSettings on CI test shard 3 (ubuntu). On origin/main the same destination loads. No snapshot is staged in the destination, so the "?" case now writes its archive to a hazard-free directory; the data, OS temp and restore directories keep the hazard, and "#" and "%41" keep it in the destination too. The refusal stays. Verified-by: tests --- tests/test_b2186_snapshot_uri.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_b2186_snapshot_uri.py b/tests/test_b2186_snapshot_uri.py index 7d38f2d945..a9c1e5984a 100644 --- a/tests/test_b2186_snapshot_uri.py +++ b/tests/test_b2186_snapshot_uri.py @@ -139,7 +139,9 @@ async def test_backup_verify_and_restore_count_the_real_snapshot_under_hazard_pa monkeypatch.setattr(tempfile, "tempdir", str(os_temp)) data_dir = tmp_path / f"data{hazard}store" data_dir.mkdir() - out_dir = tmp_path / f"b{hazard}out" + # No snapshot is staged in the backup destination, and [backup].destination must have a local + # path's shape, which refuses a "?" on every platform (BACKLOG #5110); it keeps the others. + out_dir = tmp_path / ("bout" if hazard == "?" else f"b{hazard}out") restore_dir = tmp_path / f"r{hazard}dest" key_b64 = generate_key() From 290bc727f74af05ebdfab364178e9de28a121bb4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 06:22:28 -0600 Subject: [PATCH 31/35] Comments name _is_local_or_unc_path and the CRL refusals as they now read (BACKLOG #5110, #5111) Comment and docstring text only; no behaviour changes. - _looks_like_url: says it detects one shape and that the settings refuse through _is_local_or_unc_path (#5110). - seed_dir comment and settings_error_detail: name _is_local_or_unc_path, not _looks_like_url. - _refuse_a_missing_crl_file: harden_crl_check no longer hard-codes a "[tls] crl file" prefix (#5111); the load check's point is refusing at load, led by the setting. - tls_policy _naming_the_ca_setting: a missing CRL is refused by setting without its path (#5111); only refusals on a file that is there quote it. - test_security_cli docstring names _is_local_or_unc_path. Verified-by: tests Verified-by: code-review xhigh --- messagefoundry/config/settings.py | 19 ++++++++++--------- messagefoundry/config/tls_policy.py | 7 ++++--- tests/test_security_cli.py | 5 +++-- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 3618f8268b..e0f9593a4c 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -372,10 +372,10 @@ def refuse_a_non_canonical_issuer(issuer: str, setting: str) -> None: def _refuse_a_missing_crl_file(value: str | None, setting: str) -> str | None: """Refuse a CRL path that names no file, at load, naming ``setting`` (BACKLOG #1997). - ``harden_crl_check`` would catch it when the hop's context is built, but its refusals hard-code - the prefix ``[tls] crl file`` for every call site, so a bad path on any other CRL knob would be - reported against the wrong config section. The refusal does not quote the value: one that is - not a file has not been shown to be a path, and could be a pasted secret (BACKLOG #5111). + ``harden_crl_check`` would catch it only when the hop's context is built; this refuses it at + load, led by the setting the operator wrote, so a bad path on any CRL knob is reported against + its own config section. The refusal does not quote the value: one that is not a file has not + been shown to be a path, and could be a pasted secret (BACKLOG #5111). A blank value is refused too, as ``refuse_a_blank_anchor_pin`` refuses a blank pin. ``None`` is the only spelling of "no CRL": some consumers test ``is not None`` and would hand ``""`` to @@ -7878,8 +7878,9 @@ def _looks_like_url(value: str) -> bool: """Whether ``value``, stripped and lower-cased, starts with ``://``, where the scheme is an ASCII letter and then at least one more ASCII letter, digit, ``+``, ``.`` or ``-``. These settings take a LOCAL or UNC path. A fixed list of seven cloud schemes let ``sftp://`` or - ``s3a://`` load as a bogus local path (vault BACKLOG #2600). A value with any other shape once - stripped and lower-cased is not detected, and can load as a path. + ``s3a://`` load as a bogus local path (vault BACKLOG #2600). This detects that one shape only; + the settings refuse through :func:`_is_local_or_unc_path`, which calls it and also refuses the + URL shapes it misses (BACKLOG #5110). It hands back no text, because a refusal quotes no part of the value: see :func:`settings_error_detail`.""" @@ -8206,8 +8207,8 @@ def _seed_dir_absolute(cls, value: str) -> str: # for THIS platform, the one that will resolve it: a rooted path with no drive is relative # on Windows. if value and not os.path.isabs(value): - # The value is not quoted: a URL that _looks_like_url missed could carry a - # credential (vault BACKLOG #2600). + # The value is not quoted: it could still carry a credential, since a value that + # passes _is_local_or_unc_path is only path-shaped (vault BACKLOG #2600, #5110). raise ValueError("[dr].seed_dir must be an absolute path, or omitted") return value @@ -12376,7 +12377,7 @@ def settings_error_detail(exc: Exception) -> str: to at least stderr, a service log and ``security show``'s JSON. At least the ``[backup]`` and ``[dr]`` URL refusals quote no part of the URL for that reason, the text in front of ``://`` included, because that text is the value's own and not a known word (vault BACKLOG #2850, - :func:`_looks_like_url`). + :func:`_is_local_or_unc_path`). NOT COVERED: A MESSAGE NO VALIDATOR WROTE. At least the ``AuthSettings`` OIDC endpoint loop lets the ``ValueError`` from ``urlsplit`` pass, and that message quotes the URL's netloc, its diff --git a/messagefoundry/config/tls_policy.py b/messagefoundry/config/tls_policy.py index b4f2b787be..4b5bbdcca6 100644 --- a/messagefoundry/config/tls_policy.py +++ b/messagefoundry/config/tls_policy.py @@ -3500,9 +3500,10 @@ def _naming_the_ca_setting(anchor: TrustAnchor) -> Iterator[None]: # # A [tls].crl_file refusal on the same hop still names its file, and the two shapes are # kept by Manager decision (BACKLOG #3096 item 11). This CA setting is per connection. The - # CRL file is the instance's one [tls] setting: settings load refuses a missing one, path - # and all, and harden_crl_check's refusals at hop build name it too. So the CRL path can - # still reach a connection test's text. One rule for both is not decided here. + # CRL file is the instance's one [tls] setting. Settings load and harden_crl_check refuse a + # missing one by its setting, without its path (BACKLOG #5111), but harden_crl_check's other + # refusals at hop build, on a file that is there, quote the path through crl_label. So the + # CRL path can still reach a connection test's text. One rule for both is not decided here. setting = anchor.cafile_setting or "the CA file setting" if isinstance(exc, ssl.SSLError): # OpenSSL's text names no path. reason is None for some errors, such as a bad PEM body, diff --git a/tests/test_security_cli.py b/tests/test_security_cli.py index d35980c0ce..0f4b72deca 100644 --- a/tests/test_security_cli.py +++ b/tests/test_security_cli.py @@ -989,8 +989,9 @@ def test_a_cloud_url_refusal_in_the_partial_reason_quotes_no_part_of_the_url( table: str, key: str, scheme: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: """A URL can carry a credential, and the reason prints each validator's message. The cloud-URL - refusals refuse the ``://`` shape ``_looks_like_url`` reads (vault BACKLOG #2600) and - quote no part of the URL, the scheme included (vault BACKLOG #2850).""" + refusals refuse a value ``_is_local_or_unc_path`` does not read as a local or UNC path, the + ``://`` shape included (vault BACKLOG #2600, #5110), and quote no part of the URL, the + scheme included (vault BACKLOG #2850).""" planted = "canary-canary-canary" toml = tmp_path / "mf.toml" toml.write_text( From 991b29c073dfbb1bc5cd3859f9cf7a7c24622e9e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 06:22:50 -0600 Subject: [PATCH 32/35] docs: [backup]/[dr] path rows name _is_local_or_unc_path and its refusals (BACKLOG #5110) The rows merged from main (#5116) said the check was _looks_like_url and that my_s3:// and 1s:// load as a path. #5110 replaced that gate with _is_local_or_unc_path, which refuses both. The backup destination row now names that check and its refusals with their remedy, and the three [dr] path rows point to it. Proposed PR title: [backup]/[dr] paths checked positively; refusals name the setting and quote no value (BACKLOG #5110, #5111) Proposed vault banner: #5110 built on PR 3560, docs follow-up included. Verified-by: tests Verified-by: code-review xhigh --- docs/CONFIGURATION.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 916aa46ec3..b968e5f16c 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3466,7 +3466,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | Key | Type | Default | Notes | |---|---|---|---| | `enabled` | bool | `false` | opt-in master switch; a deployment with no `[backup]` is unaffected | -| `destination` | path | `""` | local or UNC destination dir (e.g. `D:/mefor-backups`). **Required (non-empty) when enabled.** A `://` URL (`s3://`, `https://`, `sftp://`, …) is **rejected** — there is no cloud or URL target. The URL check is `_looks_like_url` in [config/settings.py](../messagefoundry/config/settings.py), whose docstring states the one shape it detects; the `[dr]` path keys share it. It misses at least a one-letter scheme, a scheme holding `_` (`my_s3://`) and a scheme that starts with a digit (`1s://`). A one-letter scheme reads as a drive letter, so `C://x` stays a path. Here a value the check misses loads as a path, relative to the working directory of the process that runs the backup (`serve`, or the `messagefoundry backup` command) where it is not absolute, as `C://x` is not on POSIX. The value can reach at least the service log and a failed run's `dr_backup` audit row and alert, so keep a credential out of it | +| `destination` | path | `""` | local or UNC destination dir (e.g. `D:/mefor-backups`). **Required (non-empty) when enabled.** A `://` URL (`s3://`, `https://`, `sftp://`, …) is **rejected** — there is no cloud or URL target — and so is any value without a local or UNC path's shape. The check is `_is_local_or_unc_path` in [config/settings.py](../messagefoundry/config/settings.py), whose docstring is the source of record for what it refuses; the `[dr]` path keys share it (BACKLOG #5110). It refuses at least: a `:` anywhere but right after one leading drive letter (after any `\\?\` or `\\.\` prefix), so `my_s3://x`, `1s://x` and `s3:bucket` are refused, and so is a POSIX path holding a `:`; any of `< > " | ? *` or a control character, so a query such as `?sig=` is refused; and an `@` in the segment right after a drive letter's `//`, as in `x://token@host`. The remedy for each is the same: name a local directory (`D:/mefor-backups`) or a UNC share (`\\nas\mefor\backups`) whose path holds none of those characters, with a `:` only after its drive letter. The refusal quotes no part of the value. A drive letter followed by `//` and no `@` stays a path, so `C://x` loads. A value the check passes loads as a path, relative to the working directory of the process that runs the backup (`serve`, or the `messagefoundry backup` command) where it is not absolute, as `C://x` is not on POSIX. The value can reach at least the service log and a failed run's `dr_backup` audit row and alert, so keep a credential out of it | | `schedule_at` | str | `"02:00"` | daily local `"HH:MM"` the scheduled backup runs at (the same clock grammar as `[retention].vacuum_at`). `""` = **on-demand only** (the `messagefoundry backup` CLI), no scheduled pass | | `retention_keep` | int | `7` | keep-N: after a successful, **verified** new archive, prune the oldest archives beyond the newest N at the destination. `0` = keep all, which on an enforcing instance needs `[security].allow_keeping_backup_archives_indefinitely = true` or `serve` refuses (BACKLOG #1967). Only archives that passed every configured check are counted: a backup is written as `.part` and renamed onto its canonical name after the verify, so a verify-**failed** archive keeps a `.failed` name and can evict a good one in neither this prune nor any later one. The flip side: `.failed` and `.part` files at the destination sit **outside** keep-N and nothing expires them — clear them yourself (ADR 0049) | | `snapshot_method` | str | `vacuum_into` | `vacuum_into` (default; a defragmented copy) or `online_backup` (a page-for-page copy). Neither holds the store write lock for the copy (BACKLOG #1937). The copy still has costs, so an off-peak `schedule_at` remains sensible; ADR 0049 points to where they are stated | @@ -3503,9 +3503,9 @@ cluster leader it would serve nothing. | `release_hook` | str | `""` | the symmetric command run on `POST /dr/release` to hand the VIP back to the recovered primary. `""` = no hook; whitespace-only rejected at load | | `pass_environment` | list of names | `[]` | Environment variable **names** both hooks are given, beyond what a shell needs to start (vault BACKLOG #2587). A hook gets an **allowlist**: the platform's start-up names, such as `PATH`, `SYSTEMROOT`, `TEMP` and `USERPROFILE` on Windows or `PATH`, `HOME` and the locale names on POSIX; on Windows the names that say where programs and shared data are installed, such as `ProgramFiles` and `ALLUSERSPROFILE`; and the names listed here. **No other variable crosses**, so list what the hook's own tools read, such as a cloud CLI's profile or a proxy. `PSModulePath` is not passed: PowerShell builds its own when it is unset. Nor is `PSExecutionPolicyPreference`, the process-scope execution policy a parent shell can set, so a PowerShell **script** hook runs under the execution policy the machine, Group Policy and the engine's account set; where that refuses scripts, give `-ExecutionPolicy` on the hook's command line or list that name here. Names only; the value comes from the engine's own environment when the hook runs, and a listed name that is not set there is logged as a WARNING, by name, when the engine starts with `enabled` and a hook configured, and again each time a hook runs. A hook that exits non-zero names this setting in its reason. A variable a hook needs that you did not list is not reported: the hook's own output is discarded, so test a hook under the service's environment before you need it. **Refused at load**: at least an entry that is not a variable name, such as `NAME=value`; any of the engine's own names, which are any `MEFOR_*` name and `VAULT_TOKEN` and `PGPASSWORD`; and `PYTHONINSPECT`, which leaves a child waiting at a prompt. `messagefoundry/childenv.py` (`pass_environment_refusal`) holds the rule. Under `[secrets].provider = "env"`, a name a secret-reference setting such as `[auth].ad_bind_password_secret` reads is refused too (in `[sandbox].pass_environment` as well). A connection secret a config module reads under another name is not known to the loader, so do not list one. A name you list reaches the hook with its value, so list a credential only when the hook needs it. `messagefoundry/childenv.py` (`hook_environment`) is the source of record for the full lists. Env: `MEFOR_DR_PASS_ENVIRONMENT`, comma-separated. | | `takeover_timeout_seconds` | float (>0) | `30.0` | bound on the takeover/release hook **and** on the cold-seed restore-verify at the DR site, its KeyProvider-reachability check included: a hook or restore-verify that doesn't succeed within this **aborts activation closed**, with no silent retry-forever. The bound reaches the key probe only where the key resolves off the event loop, which it tries to do under `[store].key_provider` `vault` or `env`, whatever `encryption_key_file` holds, and `auto` or `dpapi` with no `encryption_key_file` set (vault BACKLOG #5888). The key resolves on the event loop at least under `host`, under `auto` or `dpapi` with a key file set, and under any provider when the engine cannot start a thread for the probe, which it logs as a WARNING. A key probe that hangs on the loop stalls the whole engine, activation included, and the bound cannot fire until the probe returns. A probe the bound abandons keeps its thread until the provider answers. It also bounds the activation's digest of the running config dir, taken only for the `dr.activate` audit row: a dir that does not answer in time is recorded as `unreadable` and does **not** abort the activation. It also bounds the activation's preflights (the trust anchors and, in `serve`, the connection key files), which **abort** it after the takeover hook when they do not finish in time. What that bound leaves out is in [ADR 0048](adr/0048-third-tier-disaster-recovery-standby.md), the amendment for vault BACKLOG #3094. A **takeover** hook that runs past it is killed, with the processes it started. If the engine cannot put the hook in a Windows job object, or cannot signal its POSIX process group, it logs one WARNING and the kill reaches only the hook's shell. The abort is recorded once the hook has exited, or after at most 5 more seconds (vault BACKLOG #2622). At least these escape that kill: on POSIX a process that leaves the hook's process group (`setsid`, and `sudo` in its default `use_pty` mode) or that the engine's account may not signal; on Windows, work the hook hands to another service, such as WMI or Task Scheduler. A **release** hook that runs past it is left to finish, as before. Under `supervise` on Windows it still ends if the supervisor process dies while its engine shard runs, because each engine shard runs in the supervisor's kill-on-close job (BACKLOG #5978) | -| `seed_archive` | path | `""` | the `.mfbak` archive activation **verifies** the cold seed against. With `enabled = true`, this or `seed_dir` must be set, or the load refuses the box: no activation could name a seed (BACKLOG #5965). A whitespace-only or space-padded value is refused too. Activation does not load it — on a **SQLite** store, restore it first with `messagefoundry restore --to ` and name the same archive here, so activation can check the store actually carries it. `""` = the operator supplies the archive path in the `POST /dr/activate` request body instead (the runbook path), which needs `seed_dir` below. Local/UNC only, like the backup destination: a `://` URL is rejected by the URL check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify), and a value it misses loads here as a path, relative to the engine's working directory where it is not absolute. On a **SQLite** store a **config-only** archive cannot be a seed here and is refused: it carries no `store.db`, so nothing could have been restored from it — `messagefoundry restore --to` rejects one for the same reason, and with `--config-to` alone restores only its config bundle. On a server-DB (Postgres/SQL Server) store that refusal does not apply, and **`messagefoundry restore --to` is not part of the drill** — it rejects a config-only archive on *every* backend, so running it here is a hard error. There the DBA restores the live database natively and the archive named here is the **config bundle**, which by default is all a server-DB backup writes (`[backup].config_only_on_server_db`). That bundle restores with `messagefoundry restore --config-to ` and no `--to` (vault BACKLOG #5233). Activation instead gates the restored **live database**, not the archive: `POST /dr/activate` must carry `dba_attests_restored=true` **and** the restored database must already carry prior `dr_backup` history, or activation **refuses closed**; `restore_token` below adds an optional vintage floor on top of those two | -| `seed_dir` | path | `""` | the **one directory** a `POST /dr/activate` request body may name an archive under (vault BACKLOG #2581). `""` (default) = a request may name **no** archive, and activation uses `seed_archive`. Must be an **absolute** path on the DR box; a relative one is rejected at load, and so is a whitespace-only or space-padded one (BACKLOG #5965). A request path is confined to this directory the way `[api].config_reload_roots` confines a reload path, and activation verifies the resolved path. A refusal aborts activation (422) with one generic message that names no part of the path; the `dr_activation_aborted` audit row records the path that was asked for. If this directory itself cannot be resolved within `takeover_timeout_seconds`, activation aborts and says so. `seed_archive` is operator configuration and is not confined by this key. A `://` URL is rejected by the URL check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify). A value it misses is still refused here unless it is absolute on the platform that loads the settings, as `C://x` is on Windows and is not on POSIX | -| `restore_token` | path | `""` | **opt-in server-DB DR restore token** (BACKLOG #223, [ADR 0102](adr/0102-server-db-dr-restore-vintage-completeness-attestation-residual.md)). A local/UNC path to a small JSON token the DBA places on the DR box recording the **expected** source-backup anchor of a native (Postgres/SQL Server) restore. When set, the server-DB seed gate cross-checks it against the restored database's own latest successful `dr_backup` archive — a **vintage floor** a bare boolean attestation cannot give: a stale or wrong native restore's latest anchor differs, so activation **refuses closed**. `""` (default) = off (the gate is byte-unchanged). On a SQLite store any value is refused at load, since no check reads it there, and so is a whitespace-only or space-padded value (BACKLOG #5965). A `://` URL is rejected by the URL check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify); on a server-DB store a value it misses loads as a path, relative to the engine's working directory where it is not absolute | +| `seed_archive` | path | `""` | the `.mfbak` archive activation **verifies** the cold seed against. With `enabled = true`, this or `seed_dir` must be set, or the load refuses the box: no activation could name a seed (BACKLOG #5965). A whitespace-only or space-padded value is refused too. Activation does not load it — on a **SQLite** store, restore it first with `messagefoundry restore --to ` and name the same archive here, so activation can check the store actually carries it. `""` = the operator supplies the archive path in the `POST /dr/activate` request body instead (the runbook path), which needs `seed_dir` below. Local/UNC only, like the backup destination: a value without a local or UNC path's shape, a `://` URL included, is refused by the path check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify), which states what it refuses and the remedy, and a value it passes loads here as a path, relative to the engine's working directory where it is not absolute. On a **SQLite** store a **config-only** archive cannot be a seed here and is refused: it carries no `store.db`, so nothing could have been restored from it — `messagefoundry restore --to` rejects one for the same reason, and with `--config-to` alone restores only its config bundle. On a server-DB (Postgres/SQL Server) store that refusal does not apply, and **`messagefoundry restore --to` is not part of the drill** — it rejects a config-only archive on *every* backend, so running it here is a hard error. There the DBA restores the live database natively and the archive named here is the **config bundle**, which by default is all a server-DB backup writes (`[backup].config_only_on_server_db`). That bundle restores with `messagefoundry restore --config-to ` and no `--to` (vault BACKLOG #5233). Activation instead gates the restored **live database**, not the archive: `POST /dr/activate` must carry `dba_attests_restored=true` **and** the restored database must already carry prior `dr_backup` history, or activation **refuses closed**; `restore_token` below adds an optional vintage floor on top of those two | +| `seed_dir` | path | `""` | the **one directory** a `POST /dr/activate` request body may name an archive under (vault BACKLOG #2581). `""` (default) = a request may name **no** archive, and activation uses `seed_archive`. Must be an **absolute** path on the DR box; a relative one is rejected at load, and so is a whitespace-only or space-padded one (BACKLOG #5965). A request path is confined to this directory the way `[api].config_reload_roots` confines a reload path, and activation verifies the resolved path. A refusal aborts activation (422) with one generic message that names no part of the path; the `dr_activation_aborted` audit row records the path that was asked for. If this directory itself cannot be resolved within `takeover_timeout_seconds`, activation aborts and says so. `seed_archive` is operator configuration and is not confined by this key. A value without a local or UNC path's shape, a `://` URL included, is refused by the path check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify), which states what it refuses and the remedy. A value it passes is still refused here unless it is absolute on the platform that loads the settings, as `C://x` is on Windows and is not on POSIX | +| `restore_token` | path | `""` | **opt-in server-DB DR restore token** (BACKLOG #223, [ADR 0102](adr/0102-server-db-dr-restore-vintage-completeness-attestation-residual.md)). A local/UNC path to a small JSON token the DBA places on the DR box recording the **expected** source-backup anchor of a native (Postgres/SQL Server) restore. When set, the server-DB seed gate cross-checks it against the restored database's own latest successful `dr_backup` archive — a **vintage floor** a bare boolean attestation cannot give: a stale or wrong native restore's latest anchor differs, so activation **refuses closed**. `""` (default) = off (the gate is byte-unchanged). On a SQLite store any value is refused at load, since no check reads it there, and so is a whitespace-only or space-padded value (BACKLOG #5965). A value without a local or UNC path's shape, a `://` URL included, is refused by the path check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify), which states what it refuses and the remedy; on a server-DB store a value it passes loads as a path, relative to the engine's working directory where it is not absolute | ### `[approvals]` Optional **dual-control (maker-checker)** approval for high-value actions (ASVS 2.3.5) — see From 6b0e120c9cb0e1b9401a06201aed9426188e7b47 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 06:54:36 -0600 Subject: [PATCH 33/35] docs: [backup]/[dr] path rows say which URLs load and render as one cell (BACKLOG #5110) Prose only; no behaviour changes. - Escape the pipe in the destination row's code span, which split the table cell and dropped the rest of the row on render. - Say a two-or-more-character scheme is refused, and that a one-letter scheme (s://, x://) with none of the refused shapes still loads as a path, in the destination row, the three [dr] rows and the _looks_like_url docstring. - Name C0 control characters, not every control character. - Replace the C:// sentence, which was false both ways. - The remedy names the file itself for a [dr] key that takes a file. Verified-by: tests Verified-by: code-review xhigh --- docs/CONFIGURATION.md | 8 ++++---- messagefoundry/config/settings.py | 5 +++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index b968e5f16c..37755595fa 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3466,7 +3466,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | Key | Type | Default | Notes | |---|---|---|---| | `enabled` | bool | `false` | opt-in master switch; a deployment with no `[backup]` is unaffected | -| `destination` | path | `""` | local or UNC destination dir (e.g. `D:/mefor-backups`). **Required (non-empty) when enabled.** A `://` URL (`s3://`, `https://`, `sftp://`, …) is **rejected** — there is no cloud or URL target — and so is any value without a local or UNC path's shape. The check is `_is_local_or_unc_path` in [config/settings.py](../messagefoundry/config/settings.py), whose docstring is the source of record for what it refuses; the `[dr]` path keys share it (BACKLOG #5110). It refuses at least: a `:` anywhere but right after one leading drive letter (after any `\\?\` or `\\.\` prefix), so `my_s3://x`, `1s://x` and `s3:bucket` are refused, and so is a POSIX path holding a `:`; any of `< > " | ? *` or a control character, so a query such as `?sig=` is refused; and an `@` in the segment right after a drive letter's `//`, as in `x://token@host`. The remedy for each is the same: name a local directory (`D:/mefor-backups`) or a UNC share (`\\nas\mefor\backups`) whose path holds none of those characters, with a `:` only after its drive letter. The refusal quotes no part of the value. A drive letter followed by `//` and no `@` stays a path, so `C://x` loads. A value the check passes loads as a path, relative to the working directory of the process that runs the backup (`serve`, or the `messagefoundry backup` command) where it is not absolute, as `C://x` is not on POSIX. The value can reach at least the service log and a failed run's `dr_backup` audit row and alert, so keep a credential out of it | +| `destination` | path | `""` | local or UNC destination dir (e.g. `D:/mefor-backups`). **Required (non-empty) when enabled.** A `://` URL whose scheme is two or more characters (`s3://`, `https://`, `sftp://`, …) is **rejected** — there is no cloud or URL target — and so are the other shapes listed below. The check is `_is_local_or_unc_path` in [config/settings.py](../messagefoundry/config/settings.py), whose docstring is the source of record for what it refuses; the `[dr]` path keys share it (BACKLOG #5110). It refuses at least: a `:` anywhere but right after one leading drive letter (after any `\\?\` or `\\.\` prefix), so `my_s3://x`, `1s://x` and `s3:bucket` are refused, and so is a POSIX path holding a `:`; any of `< > " \| ? *` or a C0 control character (U+0000 to U+001F), so a query such as `?sig=` is refused; and an `@` in the first segment after a drive letter's `//`, as in `x://token@host`. The remedy for each is the same: name a local or UNC path, a directory for `destination` (`D:/mefor-backups`, `\\nas\mefor\backups`) and the file itself for a `[dr]` key that takes a file, holding none of those characters, with a `:` only after its drive letter. The refusal quotes no part of the value. A one-letter scheme reads as a drive letter, so a value such as `C://x`, `s://bucket/key` or `x://host/path`, with none of the refused shapes, passes the check and loads as a path. A value the check passes loads as a path, relative to the working directory of the process that runs the backup (`serve`, or the `messagefoundry backup` command) where it is not absolute, as `C://x` is not on POSIX. The value can reach at least the service log and a failed run's `dr_backup` audit row and alert, so keep a credential out of it | | `schedule_at` | str | `"02:00"` | daily local `"HH:MM"` the scheduled backup runs at (the same clock grammar as `[retention].vacuum_at`). `""` = **on-demand only** (the `messagefoundry backup` CLI), no scheduled pass | | `retention_keep` | int | `7` | keep-N: after a successful, **verified** new archive, prune the oldest archives beyond the newest N at the destination. `0` = keep all, which on an enforcing instance needs `[security].allow_keeping_backup_archives_indefinitely = true` or `serve` refuses (BACKLOG #1967). Only archives that passed every configured check are counted: a backup is written as `.part` and renamed onto its canonical name after the verify, so a verify-**failed** archive keeps a `.failed` name and can evict a good one in neither this prune nor any later one. The flip side: `.failed` and `.part` files at the destination sit **outside** keep-N and nothing expires them — clear them yourself (ADR 0049) | | `snapshot_method` | str | `vacuum_into` | `vacuum_into` (default; a defragmented copy) or `online_backup` (a page-for-page copy). Neither holds the store write lock for the copy (BACKLOG #1937). The copy still has costs, so an off-peak `schedule_at` remains sensible; ADR 0049 points to where they are stated | @@ -3503,9 +3503,9 @@ cluster leader it would serve nothing. | `release_hook` | str | `""` | the symmetric command run on `POST /dr/release` to hand the VIP back to the recovered primary. `""` = no hook; whitespace-only rejected at load | | `pass_environment` | list of names | `[]` | Environment variable **names** both hooks are given, beyond what a shell needs to start (vault BACKLOG #2587). A hook gets an **allowlist**: the platform's start-up names, such as `PATH`, `SYSTEMROOT`, `TEMP` and `USERPROFILE` on Windows or `PATH`, `HOME` and the locale names on POSIX; on Windows the names that say where programs and shared data are installed, such as `ProgramFiles` and `ALLUSERSPROFILE`; and the names listed here. **No other variable crosses**, so list what the hook's own tools read, such as a cloud CLI's profile or a proxy. `PSModulePath` is not passed: PowerShell builds its own when it is unset. Nor is `PSExecutionPolicyPreference`, the process-scope execution policy a parent shell can set, so a PowerShell **script** hook runs under the execution policy the machine, Group Policy and the engine's account set; where that refuses scripts, give `-ExecutionPolicy` on the hook's command line or list that name here. Names only; the value comes from the engine's own environment when the hook runs, and a listed name that is not set there is logged as a WARNING, by name, when the engine starts with `enabled` and a hook configured, and again each time a hook runs. A hook that exits non-zero names this setting in its reason. A variable a hook needs that you did not list is not reported: the hook's own output is discarded, so test a hook under the service's environment before you need it. **Refused at load**: at least an entry that is not a variable name, such as `NAME=value`; any of the engine's own names, which are any `MEFOR_*` name and `VAULT_TOKEN` and `PGPASSWORD`; and `PYTHONINSPECT`, which leaves a child waiting at a prompt. `messagefoundry/childenv.py` (`pass_environment_refusal`) holds the rule. Under `[secrets].provider = "env"`, a name a secret-reference setting such as `[auth].ad_bind_password_secret` reads is refused too (in `[sandbox].pass_environment` as well). A connection secret a config module reads under another name is not known to the loader, so do not list one. A name you list reaches the hook with its value, so list a credential only when the hook needs it. `messagefoundry/childenv.py` (`hook_environment`) is the source of record for the full lists. Env: `MEFOR_DR_PASS_ENVIRONMENT`, comma-separated. | | `takeover_timeout_seconds` | float (>0) | `30.0` | bound on the takeover/release hook **and** on the cold-seed restore-verify at the DR site, its KeyProvider-reachability check included: a hook or restore-verify that doesn't succeed within this **aborts activation closed**, with no silent retry-forever. The bound reaches the key probe only where the key resolves off the event loop, which it tries to do under `[store].key_provider` `vault` or `env`, whatever `encryption_key_file` holds, and `auto` or `dpapi` with no `encryption_key_file` set (vault BACKLOG #5888). The key resolves on the event loop at least under `host`, under `auto` or `dpapi` with a key file set, and under any provider when the engine cannot start a thread for the probe, which it logs as a WARNING. A key probe that hangs on the loop stalls the whole engine, activation included, and the bound cannot fire until the probe returns. A probe the bound abandons keeps its thread until the provider answers. It also bounds the activation's digest of the running config dir, taken only for the `dr.activate` audit row: a dir that does not answer in time is recorded as `unreadable` and does **not** abort the activation. It also bounds the activation's preflights (the trust anchors and, in `serve`, the connection key files), which **abort** it after the takeover hook when they do not finish in time. What that bound leaves out is in [ADR 0048](adr/0048-third-tier-disaster-recovery-standby.md), the amendment for vault BACKLOG #3094. A **takeover** hook that runs past it is killed, with the processes it started. If the engine cannot put the hook in a Windows job object, or cannot signal its POSIX process group, it logs one WARNING and the kill reaches only the hook's shell. The abort is recorded once the hook has exited, or after at most 5 more seconds (vault BACKLOG #2622). At least these escape that kill: on POSIX a process that leaves the hook's process group (`setsid`, and `sudo` in its default `use_pty` mode) or that the engine's account may not signal; on Windows, work the hook hands to another service, such as WMI or Task Scheduler. A **release** hook that runs past it is left to finish, as before. Under `supervise` on Windows it still ends if the supervisor process dies while its engine shard runs, because each engine shard runs in the supervisor's kill-on-close job (BACKLOG #5978) | -| `seed_archive` | path | `""` | the `.mfbak` archive activation **verifies** the cold seed against. With `enabled = true`, this or `seed_dir` must be set, or the load refuses the box: no activation could name a seed (BACKLOG #5965). A whitespace-only or space-padded value is refused too. Activation does not load it — on a **SQLite** store, restore it first with `messagefoundry restore --to ` and name the same archive here, so activation can check the store actually carries it. `""` = the operator supplies the archive path in the `POST /dr/activate` request body instead (the runbook path), which needs `seed_dir` below. Local/UNC only, like the backup destination: a value without a local or UNC path's shape, a `://` URL included, is refused by the path check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify), which states what it refuses and the remedy, and a value it passes loads here as a path, relative to the engine's working directory where it is not absolute. On a **SQLite** store a **config-only** archive cannot be a seed here and is refused: it carries no `store.db`, so nothing could have been restored from it — `messagefoundry restore --to` rejects one for the same reason, and with `--config-to` alone restores only its config bundle. On a server-DB (Postgres/SQL Server) store that refusal does not apply, and **`messagefoundry restore --to` is not part of the drill** — it rejects a config-only archive on *every* backend, so running it here is a hard error. There the DBA restores the live database natively and the archive named here is the **config bundle**, which by default is all a server-DB backup writes (`[backup].config_only_on_server_db`). That bundle restores with `messagefoundry restore --config-to ` and no `--to` (vault BACKLOG #5233). Activation instead gates the restored **live database**, not the archive: `POST /dr/activate` must carry `dba_attests_restored=true` **and** the restored database must already carry prior `dr_backup` history, or activation **refuses closed**; `restore_token` below adds an optional vintage floor on top of those two | -| `seed_dir` | path | `""` | the **one directory** a `POST /dr/activate` request body may name an archive under (vault BACKLOG #2581). `""` (default) = a request may name **no** archive, and activation uses `seed_archive`. Must be an **absolute** path on the DR box; a relative one is rejected at load, and so is a whitespace-only or space-padded one (BACKLOG #5965). A request path is confined to this directory the way `[api].config_reload_roots` confines a reload path, and activation verifies the resolved path. A refusal aborts activation (422) with one generic message that names no part of the path; the `dr_activation_aborted` audit row records the path that was asked for. If this directory itself cannot be resolved within `takeover_timeout_seconds`, activation aborts and says so. `seed_archive` is operator configuration and is not confined by this key. A value without a local or UNC path's shape, a `://` URL included, is refused by the path check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify), which states what it refuses and the remedy. A value it passes is still refused here unless it is absolute on the platform that loads the settings, as `C://x` is on Windows and is not on POSIX | -| `restore_token` | path | `""` | **opt-in server-DB DR restore token** (BACKLOG #223, [ADR 0102](adr/0102-server-db-dr-restore-vintage-completeness-attestation-residual.md)). A local/UNC path to a small JSON token the DBA places on the DR box recording the **expected** source-backup anchor of a native (Postgres/SQL Server) restore. When set, the server-DB seed gate cross-checks it against the restored database's own latest successful `dr_backup` archive — a **vintage floor** a bare boolean attestation cannot give: a stale or wrong native restore's latest anchor differs, so activation **refuses closed**. `""` (default) = off (the gate is byte-unchanged). On a SQLite store any value is refused at load, since no check reads it there, and so is a whitespace-only or space-padded value (BACKLOG #5965). A value without a local or UNC path's shape, a `://` URL included, is refused by the path check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify), which states what it refuses and the remedy; on a server-DB store a value it passes loads as a path, relative to the engine's working directory where it is not absolute | +| `seed_archive` | path | `""` | the `.mfbak` archive activation **verifies** the cold seed against. With `enabled = true`, this or `seed_dir` must be set, or the load refuses the box: no activation could name a seed (BACKLOG #5965). A whitespace-only or space-padded value is refused too. Activation does not load it — on a **SQLite** store, restore it first with `messagefoundry restore --to ` and name the same archive here, so activation can check the store actually carries it. `""` = the operator supplies the archive path in the `POST /dr/activate` request body instead (the runbook path), which needs `seed_dir` below. Local/UNC only, like the backup destination: the path check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify) refuses at least a `://` URL whose scheme is two or more characters, and that row states what else it refuses and the remedy; a one-letter scheme such as `s://` passes it, and a value it passes loads here as a path, relative to the engine's working directory where it is not absolute. On a **SQLite** store a **config-only** archive cannot be a seed here and is refused: it carries no `store.db`, so nothing could have been restored from it — `messagefoundry restore --to` rejects one for the same reason, and with `--config-to` alone restores only its config bundle. On a server-DB (Postgres/SQL Server) store that refusal does not apply, and **`messagefoundry restore --to` is not part of the drill** — it rejects a config-only archive on *every* backend, so running it here is a hard error. There the DBA restores the live database natively and the archive named here is the **config bundle**, which by default is all a server-DB backup writes (`[backup].config_only_on_server_db`). That bundle restores with `messagefoundry restore --config-to ` and no `--to` (vault BACKLOG #5233). Activation instead gates the restored **live database**, not the archive: `POST /dr/activate` must carry `dba_attests_restored=true` **and** the restored database must already carry prior `dr_backup` history, or activation **refuses closed**; `restore_token` below adds an optional vintage floor on top of those two | +| `seed_dir` | path | `""` | the **one directory** a `POST /dr/activate` request body may name an archive under (vault BACKLOG #2581). `""` (default) = a request may name **no** archive, and activation uses `seed_archive`. Must be an **absolute** path on the DR box; a relative one is rejected at load, and so is a whitespace-only or space-padded one (BACKLOG #5965). A request path is confined to this directory the way `[api].config_reload_roots` confines a reload path, and activation verifies the resolved path. A refusal aborts activation (422) with one generic message that names no part of the path; the `dr_activation_aborted` audit row records the path that was asked for. If this directory itself cannot be resolved within `takeover_timeout_seconds`, activation aborts and says so. `seed_archive` is operator configuration and is not confined by this key. The path check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify) refuses at least a `://` URL whose scheme is two or more characters, and that row states what else it refuses and the remedy; a one-letter scheme such as `s://` passes it. A value it passes is still refused here unless it is absolute on the platform that loads the settings, as `C://x` is on Windows and is not on POSIX | +| `restore_token` | path | `""` | **opt-in server-DB DR restore token** (BACKLOG #223, [ADR 0102](adr/0102-server-db-dr-restore-vintage-completeness-attestation-residual.md)). A local/UNC path to a small JSON token the DBA places on the DR box recording the **expected** source-backup anchor of a native (Postgres/SQL Server) restore. When set, the server-DB seed gate cross-checks it against the restored database's own latest successful `dr_backup` archive — a **vintage floor** a bare boolean attestation cannot give: a stale or wrong native restore's latest anchor differs, so activation **refuses closed**. `""` (default) = off (the gate is byte-unchanged). On a SQLite store any value is refused at load, since no check reads it there, and so is a whitespace-only or space-padded value (BACKLOG #5965). The path check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify) refuses at least a `://` URL whose scheme is two or more characters, and that row states what else it refuses and the remedy; a one-letter scheme such as `s://` passes it; on a server-DB store a value it passes loads as a path, relative to the engine's working directory where it is not absolute | ### `[approvals]` Optional **dual-control (maker-checker)** approval for high-value actions (ASVS 2.3.5) — see diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index e0f9593a4c..2bbcd41d6a 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -7879,8 +7879,9 @@ def _looks_like_url(value: str) -> bool: an ASCII letter and then at least one more ASCII letter, digit, ``+``, ``.`` or ``-``. These settings take a LOCAL or UNC path. A fixed list of seven cloud schemes let ``sftp://`` or ``s3a://`` load as a bogus local path (vault BACKLOG #2600). This detects that one shape only; - the settings refuse through :func:`_is_local_or_unc_path`, which calls it and also refuses the - URL shapes it misses (BACKLOG #5110). + the settings refuse through :func:`_is_local_or_unc_path`, which calls it and also refuses at + least some URL shapes it misses (BACKLOG #5110). A one-letter scheme (``s://bucket/key``) passes + both and loads as a path, since it reads as a drive letter. It hands back no text, because a refusal quotes no part of the value: see :func:`settings_error_detail`.""" From 8cd99fb1de603944374dbbacafd3683eb766356c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 07:54:13 -0600 Subject: [PATCH 34/35] Backup destination docs say what the path screen refuses, not every URL or control character The changelog fragment, CONFIGURATION.md and the settings comment now say a one-letter scheme loads and a leading or trailing control character stripped before the screen is not refused by it. Verified-by: tests --- changelog.d/5110.security.md | 15 +++++++++------ docs/CONFIGURATION.md | 2 +- messagefoundry/config/settings.py | 4 ++-- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/changelog.d/5110.security.md b/changelog.d/5110.security.md index 82de83d41d..9a2067db12 100644 --- a/changelog.d/5110.security.md +++ b/changelog.d/5110.security.md @@ -1,7 +1,10 @@ - **`[backup].destination`, `[dr].seed_archive`, `[dr].seed_dir` and `[dr].restore_token` must - have a local or UNC path's shape.** Besides a `://` URL, a value is now refused at load - when it has a `:` anywhere but right after a leading drive letter, a character Windows refuses - in a path (such as `?`) or a control character, or an `@` in the segment after a drive - letter's `//`. A `\\?\` or `\\.\` prefix, in any slash spelling, is read past first. That catches URL - shapes the scheme test missed, and also refuses a POSIX path holding one of them. The DR backup - runner's startup lines no longer log a destination that is not such a path. (`BACKLOG #5110`) + have a local or UNC path's shape.** Besides a `://` URL whose scheme has two or more + characters (a one-letter scheme reads as a drive letter and can load), a value is now refused at + load when it has a `:` anywhere but right after a leading drive letter, a character Windows + refuses in a path (such as `?`) or a control character inside the value (a leading or trailing + TAB, LF, VT, FF, CR or U+001C to U+001F is not refused by this rule), or an `@` in the segment + after a drive letter's `//`. A `\\?\` or `\\.\` prefix, in any slash spelling, is read past + first. That catches URL shapes the scheme test missed, and also refuses a POSIX path holding one + of them. The DR backup runner's startup lines no longer log a destination that is not such a + path. (`BACKLOG #5110`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 37755595fa..f67f670078 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3466,7 +3466,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | Key | Type | Default | Notes | |---|---|---|---| | `enabled` | bool | `false` | opt-in master switch; a deployment with no `[backup]` is unaffected | -| `destination` | path | `""` | local or UNC destination dir (e.g. `D:/mefor-backups`). **Required (non-empty) when enabled.** A `://` URL whose scheme is two or more characters (`s3://`, `https://`, `sftp://`, …) is **rejected** — there is no cloud or URL target — and so are the other shapes listed below. The check is `_is_local_or_unc_path` in [config/settings.py](../messagefoundry/config/settings.py), whose docstring is the source of record for what it refuses; the `[dr]` path keys share it (BACKLOG #5110). It refuses at least: a `:` anywhere but right after one leading drive letter (after any `\\?\` or `\\.\` prefix), so `my_s3://x`, `1s://x` and `s3:bucket` are refused, and so is a POSIX path holding a `:`; any of `< > " \| ? *` or a C0 control character (U+0000 to U+001F), so a query such as `?sig=` is refused; and an `@` in the first segment after a drive letter's `//`, as in `x://token@host`. The remedy for each is the same: name a local or UNC path, a directory for `destination` (`D:/mefor-backups`, `\\nas\mefor\backups`) and the file itself for a `[dr]` key that takes a file, holding none of those characters, with a `:` only after its drive letter. The refusal quotes no part of the value. A one-letter scheme reads as a drive letter, so a value such as `C://x`, `s://bucket/key` or `x://host/path`, with none of the refused shapes, passes the check and loads as a path. A value the check passes loads as a path, relative to the working directory of the process that runs the backup (`serve`, or the `messagefoundry backup` command) where it is not absolute, as `C://x` is not on POSIX. The value can reach at least the service log and a failed run's `dr_backup` audit row and alert, so keep a credential out of it | +| `destination` | path | `""` | local or UNC destination dir (e.g. `D:/mefor-backups`). **Required (non-empty) when enabled.** A `://` URL whose scheme is two or more characters (`s3://`, `https://`, `sftp://`, …) is **rejected** — there is no cloud or URL target — and so are the other shapes listed below. The check is `_is_local_or_unc_path` in [config/settings.py](../messagefoundry/config/settings.py), whose docstring is the source of record for what it refuses; the `[dr]` path keys share it (BACKLOG #5110). It refuses at least: a `:` anywhere but right after one leading drive letter (after any `\\?\` or `\\.\` prefix), so `my_s3://x`, `1s://x` and `s3:bucket` are refused, and so is a POSIX path holding a `:`; any of `< > " \| ? *` or a C0 control character (U+0000 to U+001F) inside the value; a leading or trailing TAB, LF, VT, FF, CR or U+001C to U+001F is not refused by this rule, so a query such as `?sig=` is refused; and an `@` in the first segment after a drive letter's `//`, as in `x://token@host`. The remedy for each is the same: name a local or UNC path, a directory for `destination` (`D:/mefor-backups`, `\\nas\mefor\backups`) and the file itself for a `[dr]` key that takes a file, holding none of those characters, with a `:` only after its drive letter. The refusal quotes no part of the value. A one-letter scheme reads as a drive letter, so a value such as `C://x`, `s://bucket/key` or `x://host/path`, with none of the refused shapes, passes the check and loads as a path. A value the check passes loads as a path, relative to the working directory of the process that runs the backup (`serve`, or the `messagefoundry backup` command) where it is not absolute, as `C://x` is not on POSIX. The value can reach at least the service log and a failed run's `dr_backup` audit row and alert, so keep a credential out of it | | `schedule_at` | str | `"02:00"` | daily local `"HH:MM"` the scheduled backup runs at (the same clock grammar as `[retention].vacuum_at`). `""` = **on-demand only** (the `messagefoundry backup` CLI), no scheduled pass | | `retention_keep` | int | `7` | keep-N: after a successful, **verified** new archive, prune the oldest archives beyond the newest N at the destination. `0` = keep all, which on an enforcing instance needs `[security].allow_keeping_backup_archives_indefinitely = true` or `serve` refuses (BACKLOG #1967). Only archives that passed every configured check are counted: a backup is written as `.part` and renamed onto its canonical name after the verify, so a verify-**failed** archive keeps a `.failed` name and can evict a good one in neither this prune nor any later one. The flip side: `.failed` and `.part` files at the destination sit **outside** keep-N and nothing expires them — clear them yourself (ADR 0049) | | `snapshot_method` | str | `vacuum_into` | `vacuum_into` (default; a defragmented copy) or `online_backup` (a page-for-page copy). Neither holds the store write lock for the copy (BACKLOG #1937). The copy still has costs, so an off-peak `schedule_at` remains sensible; ADR 0049 points to where they are stated | diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 2bbcd41d6a..011d9c2479 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -7955,8 +7955,8 @@ class BackupSettings(_Section): # Opt-in master switch; a deployment with no [backup] is unaffected (no-op default). enabled: bool = False # Operator-set LOCAL or UNC destination path, e.g. "D:/mefor-backups" or r"\\nas\mefor\backups". - # REQUIRED (non-empty) when enabled. A :// URL (s3://, https://, sftp://, ...) is REJECTED, - # and so is any value without a local or UNC path's shape (_is_local_or_unc_path). + # REQUIRED (non-empty) when enabled. _is_local_or_unc_path decides which values are refused; a + # one-letter scheme such as s://x passes it and loads as a path. destination: str = "" # Daily local "HH:MM" at which the scheduled backup runs (reusing the RetentionSettings clock parser). # "" = on-demand only (the `messagefoundry backup` CLI), no scheduled pass. From 9f54f62c28b6f7cd38c4b705874e1564fed5a2b6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 08:05:10 -0600 Subject: [PATCH 35/35] Backup destination docs name C0 control characters and keep the query example beside its rule The changelog fragment and CONFIGURATION.md row now say C0 control character and attach the ?sig= example to the rule that refuses it. Verified-by: tests --- changelog.d/5110.security.md | 12 ++++++------ docs/CONFIGURATION.md | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/changelog.d/5110.security.md b/changelog.d/5110.security.md index 9a2067db12..826899ff77 100644 --- a/changelog.d/5110.security.md +++ b/changelog.d/5110.security.md @@ -2,9 +2,9 @@ have a local or UNC path's shape.** Besides a `://` URL whose scheme has two or more characters (a one-letter scheme reads as a drive letter and can load), a value is now refused at load when it has a `:` anywhere but right after a leading drive letter, a character Windows - refuses in a path (such as `?`) or a control character inside the value (a leading or trailing - TAB, LF, VT, FF, CR or U+001C to U+001F is not refused by this rule), or an `@` in the segment - after a drive letter's `//`. A `\\?\` or `\\.\` prefix, in any slash spelling, is read past - first. That catches URL shapes the scheme test missed, and also refuses a POSIX path holding one - of them. The DR backup runner's startup lines no longer log a destination that is not such a - path. (`BACKLOG #5110`) + refuses in a path (such as `?`) or a C0 control character (U+0000 to U+001F) inside the value + (a leading or trailing TAB, LF, VT, FF, CR or U+001C to U+001F is not refused by this rule), or + an `@` in the segment after a drive letter's `//`. A `\\?\` or `\\.\` prefix, in any slash + spelling, is read past first. That catches URL shapes the scheme test missed, and also refuses a + POSIX path holding one of them. The DR backup runner's startup lines no longer log a destination + that is not such a path. (`BACKLOG #5110`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index f67f670078..703a1bffbd 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3466,7 +3466,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | Key | Type | Default | Notes | |---|---|---|---| | `enabled` | bool | `false` | opt-in master switch; a deployment with no `[backup]` is unaffected | -| `destination` | path | `""` | local or UNC destination dir (e.g. `D:/mefor-backups`). **Required (non-empty) when enabled.** A `://` URL whose scheme is two or more characters (`s3://`, `https://`, `sftp://`, …) is **rejected** — there is no cloud or URL target — and so are the other shapes listed below. The check is `_is_local_or_unc_path` in [config/settings.py](../messagefoundry/config/settings.py), whose docstring is the source of record for what it refuses; the `[dr]` path keys share it (BACKLOG #5110). It refuses at least: a `:` anywhere but right after one leading drive letter (after any `\\?\` or `\\.\` prefix), so `my_s3://x`, `1s://x` and `s3:bucket` are refused, and so is a POSIX path holding a `:`; any of `< > " \| ? *` or a C0 control character (U+0000 to U+001F) inside the value; a leading or trailing TAB, LF, VT, FF, CR or U+001C to U+001F is not refused by this rule, so a query such as `?sig=` is refused; and an `@` in the first segment after a drive letter's `//`, as in `x://token@host`. The remedy for each is the same: name a local or UNC path, a directory for `destination` (`D:/mefor-backups`, `\\nas\mefor\backups`) and the file itself for a `[dr]` key that takes a file, holding none of those characters, with a `:` only after its drive letter. The refusal quotes no part of the value. A one-letter scheme reads as a drive letter, so a value such as `C://x`, `s://bucket/key` or `x://host/path`, with none of the refused shapes, passes the check and loads as a path. A value the check passes loads as a path, relative to the working directory of the process that runs the backup (`serve`, or the `messagefoundry backup` command) where it is not absolute, as `C://x` is not on POSIX. The value can reach at least the service log and a failed run's `dr_backup` audit row and alert, so keep a credential out of it | +| `destination` | path | `""` | local or UNC destination dir (e.g. `D:/mefor-backups`). **Required (non-empty) when enabled.** A `://` URL whose scheme is two or more characters (`s3://`, `https://`, `sftp://`, …) is **rejected** — there is no cloud or URL target — and so are the other shapes listed below. The check is `_is_local_or_unc_path` in [config/settings.py](../messagefoundry/config/settings.py), whose docstring is the source of record for what it refuses; the `[dr]` path keys share it (BACKLOG #5110). It refuses at least: a `:` anywhere but right after one leading drive letter (after any `\\?\` or `\\.\` prefix), so `my_s3://x`, `1s://x` and `s3:bucket` are refused, and so is a POSIX path holding a `:`; any of `< > " \| ? *` or a C0 control character (U+0000 to U+001F) inside the value, so a query such as `?sig=` is refused (a leading or trailing TAB, LF, VT, FF, CR or U+001C to U+001F is not refused by this rule); and an `@` in the first segment after a drive letter's `//`, as in `x://token@host`. The remedy for each is the same: name a local or UNC path, a directory for `destination` (`D:/mefor-backups`, `\\nas\mefor\backups`) and the file itself for a `[dr]` key that takes a file, holding none of those characters, with a `:` only after its drive letter. The refusal quotes no part of the value. A one-letter scheme reads as a drive letter, so a value such as `C://x`, `s://bucket/key` or `x://host/path`, with none of the refused shapes, passes the check and loads as a path. A value the check passes loads as a path, relative to the working directory of the process that runs the backup (`serve`, or the `messagefoundry backup` command) where it is not absolute, as `C://x` is not on POSIX. The value can reach at least the service log and a failed run's `dr_backup` audit row and alert, so keep a credential out of it | | `schedule_at` | str | `"02:00"` | daily local `"HH:MM"` the scheduled backup runs at (the same clock grammar as `[retention].vacuum_at`). `""` = **on-demand only** (the `messagefoundry backup` CLI), no scheduled pass | | `retention_keep` | int | `7` | keep-N: after a successful, **verified** new archive, prune the oldest archives beyond the newest N at the destination. `0` = keep all, which on an enforcing instance needs `[security].allow_keeping_backup_archives_indefinitely = true` or `serve` refuses (BACKLOG #1967). Only archives that passed every configured check are counted: a backup is written as `.part` and renamed onto its canonical name after the verify, so a verify-**failed** archive keeps a `.failed` name and can evict a good one in neither this prune nor any later one. The flip side: `.failed` and `.part` files at the destination sit **outside** keep-N and nothing expires them — clear them yourself (ADR 0049) | | `snapshot_method` | str | `vacuum_into` | `vacuum_into` (default; a defragmented copy) or `online_backup` (a page-for-page copy). Neither holds the store write lock for the copy (BACKLOG #1937). The copy still has costs, so an off-peak `schedule_at` remains sensible; ADR 0049 points to where they are stated |