From 84a291cf9f003fdf33a9ca435c1fc91429a31509 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:29:36 -0600 Subject: [PATCH 01/49] settings: the URL check's docstring names an ASCII scheme, judged after lower-casing (BACKLOG #5116) _looks_like_url's docstring is the one statement docs/CONFIGURATION.md now links for the backup and DR path keys. It said "a letter", but _URL_SCHEME is ASCII only, and the shape is judged after str.lower(), so say both. Docstring only; no behaviour change. Verified-by: tests --- messagefoundry/config/settings.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 944b98e146..8333cdd8bf 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -7811,10 +7811,10 @@ def _dwell_inside_expiry(self) -> ApprovalsSettings: def _looks_like_url(value: str) -> bool: """Whether ``value``, stripped and lower-cased, starts with ``://``, where the scheme is - a letter and then at least one more 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 is not - detected, and can load as a path. + 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. It hands back no text, because a refusal quotes no part of the value: see :func:`settings_error_detail`.""" From 4c62e43561f609ade40512ee812e03c31f27a3c1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:30:31 -0600 Subject: [PATCH 02/49] docs: CONFIGURATION.md's backup and DR path rows state the URL check's real shape (BACKLOG #5116) The four rows ([backup] destination; [dr] seed_archive, seed_dir, restore_token) each said a URL "whose scheme has two or more characters" is rejected. The check, _looks_like_url, needs a leading ASCII letter, so a digit-led scheme such as 1s:// is missed and loads as a path. The destination row now names _looks_like_url as the one statement of the shape, and says it misses at least a one-letter scheme, a scheme holding _, and a digit-led one. Each [dr] row links it and says what its own key does with a missed value: seed_archive and restore_token load it as a path; seed_dir still refuses it unless it is absolute on the platform that loads the settings, since _seed_dir_absolute runs too. Proposed PR title: CONFIGURATION.md states the backup/DR URL check's real shape (BACKLOG #5116) Proposed vault banner: BUILT on branch b20053-5116 (batch 20053): the four CONFIGURATION.md rows link _looks_like_url, whose docstring now says ASCII and lower-cased; each row says what its key does with a missed value. Verified-by: tests --- docs/CONFIGURATION.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3f248b43e6..06d86fa2ad 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://`, …) whose scheme has two or more characters is **rejected** — there is no remote target. A one-letter scheme reads as a drive letter, so `C://x` stays a path | +| `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 | | `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. A `://` URL whose scheme has two or more characters is rejected (a one-letter scheme reads as a drive letter, so `C://x` stays a path) — local/UNC only, like the backup destination. 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 whose scheme has two or more characters is rejected (a one-letter scheme reads as a drive letter, so `C://x` stays a path), like `seed_archive` | -| `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 whose scheme has two or more characters is rejected (a one-letter scheme reads as a drive letter, so `C://x` stays a path) | +| `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 | ### `[approvals]` Optional **dual-control (maker-checker)** approval for high-value actions (ASVS 2.3.5) — see From 7578fe53ab5f337a25f0992a9b89f86cbd4c0f44 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 14:04:08 -0600 Subject: [PATCH 03/49] tests: pin the anchor check's refusal of a PEM block with no data, in each position (BACKLOG #5230) The fix itself landed with BACKLOG #5229 (PR 3301, 15b74a93247): the read-to-end check, _reads_to_the_end, refuses a file whose cadata= load stops early without an error. This adds a test for the block with no data under a CERTIFICATE label (LF and CRLF) and an X509 CRL label, between two certificates, after both and before both, and asserts cafile= refuses each file too. The between and after rows fail against anchor_cadata as it stood before 15b74a93247 (DID NOT RAISE); the before rows were already refused there, by the trial load. The controls: nothing, or a well-formed CRL, between the two certificates loads both by path and through the check. Test only; no product code changes. Proposed PR title: Pin the anchor check's refusal of a PEM block with no data (BACKLOG #5230) Proposed vault banner: ALREADY MET by BACKLOG #5229 (PR 3301, 15b74a93247), which refuses the shape and corrected the CONFIGURATION.md sentence; branch b20053-5230 adds the row's regression test with its controls. Verified-by: tests --- tests/test_trust_anchor_byte_binding.py | 75 +++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/tests/test_trust_anchor_byte_binding.py b/tests/test_trust_anchor_byte_binding.py index ec55dae97c..74d69936aa 100644 --- a/tests/test_trust_anchor_byte_binding.py +++ b/tests/test_trust_anchor_byte_binding.py @@ -838,6 +838,81 @@ def test_a_block_the_load_stops_at_refuses_as_cafile_does( assert anchor_cadata(good.pem, _SPEC) +#: A PEM block with no data, under a label ``cadata=`` reads as a certificate and one it skips, +#: and with CRLF line ends. +_EMPTY_BLOCKS = [ + pytest.param(b"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n", id="certificate"), + pytest.param( + b"-----BEGIN CERTIFICATE-----\r\n-----END CERTIFICATE-----\r\n", id="certificate-crlf" + ), + pytest.param(b"-----BEGIN X509 CRL-----\n-----END X509 CRL-----\n", id="crl"), +] + + +def _well_formed_crl() -> bytes: + """A parseable CRL from a throwaway issuer, for the control: ``cadata=`` skips it.""" + key = ec.generate_private_key(ec.SECP256R1()) + crl = ( + x509.CertificateRevocationListBuilder() + .issuer_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "crl-issuer")])) + .last_update(_NB) + .next_update(_NA) + .sign(key, hashes.SHA256()) + ) + return crl.public_bytes(serialization.Encoding.PEM) + + +@pytest.mark.parametrize("empty", _EMPTY_BLOCKS) +@pytest.mark.parametrize("where", ["between", "after", "before"]) +def test_an_empty_pem_block_refuses_wherever_it_sits( + tmp_path: Path, cas: tuple[_Ca, _Ca], empty: bytes, where: str +) -> None: + """A PEM block with no data, behind at least one certificate, stops the ``cadata=`` load + without an error: between two certificates the second never loads, and the load reports + success. ``cafile=`` refuses the file in every position, and so does the check, naming it. + Behind a certificate the read-to-end check finds the stop + (:func:`~messagefoundry.auth.trust_anchors._reads_to_the_end`, BACKLOG #5229). In front of + every certificate ``cadata=`` itself raises, and the check refuses with OpenSSL's reason. Both + fixture CAs stand for legitimate anchors here. The controls are in the next test.""" + first, second = cas + data = {"between": first.pem + empty + second.pem, "after": first.pem + second.pem + empty} + data["before"] = empty + first.pem + second.pem + anchor = tmp_path / "ca.pem" + anchor.write_bytes(data[where]) + with pytest.raises(ssl.SSLError): + ssl.create_default_context(cafile=str(anchor)) + text = data[where].decode() + if where == "before": + with pytest.raises(ssl.SSLError, match="no start line"): + ssl.create_default_context(cadata=text) + refusal, reason = "cannot load", "no start line" + else: # the gap: no error, and what loaded is all the caller learns + loaded = sorted(_subjects(ssl.create_default_context(cadata=text))) + assert loaded == ([first.name] if where == "between" else sorted([first.name, second.name])) + refusal, reason = "stops reading", "Remove or repair the block" + with pytest.raises(TrustAnchorError, match=refusal) as refused: + anchor_cadata(data[where], _SPEC) + assert refused.value.scope == "unloadable" + assert repr(_SPEC.path) in str(refused.value) + assert reason in str(refused.value) + + +@pytest.mark.parametrize("middle", ["nothing", "a well-formed CRL"]) +def test_two_certificates_load_both_with_no_empty_block_between( + tmp_path: Path, cas: tuple[_Ca, _Ca], middle: str +) -> None: + """The controls for the empty-block refusal above, under the same checks: the two + certificates with nothing between them, or a well-formed CRL, which ``cadata=`` skips, load + both by path, and the check passes them and returns text that loads both.""" + first, second = cas + data = first.pem + (_well_formed_crl() if middle != "nothing" else b"") + second.pem + anchor = tmp_path / "ca.pem" + anchor.write_bytes(data) + both = sorted([first.name, second.name]) + assert sorted(_subjects(ssl.create_default_context(cafile=str(anchor)))) == both + assert sorted(_subjects(ssl.create_default_context(cadata=anchor_cadata(data, _SPEC)))) == both + + def test_a_read_to_end_load_that_raises_refuses_naming_the_error( monkeypatch: pytest.MonkeyPatch, cas: tuple[_Ca, _Ca] ) -> None: From a7a537964d10ae0d96e44cca79b9700956831748 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:05:09 -0600 Subject: [PATCH 04/49] dr_backup: the config walk adds each file from a handle opened through no link (BACKLOG #6573) The walk screened each file by lstat, then tar.add opened it by name. A folder or a file swapped for a symlink or a junction in between was followed, so the target's bytes reached the archive: a swapped file up to its own size, a swapped folder its whole listing. Each screened file is now opened with the file connector's confined read, _open_confined (POSIX: O_NOFOLLOW per component from a parent descriptor; Windows: held folders, the file opened as itself, its final path checked), and its member is described and filled from that handle with gettarinfo(fileobj=) and addfile. A link refusal is a pass-over. Any other open failure re-screens the name: gone is gone, a folder or link now is a pass-over (Windows answers ERROR_ACCESS_DENIED there), and a name that still reads as a regular file fails the backup, naming the file, as an unreadable config file did before; Windows codes 1, 50 and 87 pass it over. The archive file being written is still skipped, as tar.add did. _tree_size is unchanged and still reads by name. Tests: a file and a folder swapped for a link after the walk checked them, with the controls carried; a file swapped for a folder, junction or directory symlink between its screen and its open; and a file that still screens as regular but will not open fails the backup. The swap tests for a file symlink and a folder junction fail on origin/main. The candidate test now hooks the open the walk makes, since the walk no longer calls tar.add. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 117 ++++++++++---- tests/test_backup_runner.py | 230 ++++++++++++++++++++++++++- 2 files changed, 311 insertions(+), 36 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 02052f548a..d6f8ca3090 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -117,6 +117,7 @@ _fd_for, _file_id, _handle_final_path, + _open_confined, _os_handle, _Replaced, _Unconfined, @@ -1425,14 +1426,12 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ directory link the walk lists as a directory is named in one WARNING, since the loader and the config digest may read through it. - Not covered, at least: the walk reads each entry, then lists or opens it by name, so a path - swapped for a link in between is followed. The swaps that reach it include at least these. - A directory swapped for a junction in that gap is descended, as :func:`_walk_unfollowed` - says, and the files behind it are bundled. A parent folder swapped for a junction after the - walk had already decided to descend into the folder lets ``tar.add`` open each name listed - under the folder through the junction. A swapped file adds one member, since ``tar.add`` is - not recursive. This walk does not close that race, and this docstring does not bound who - can win it; closing it is separate work. + Each file is added from a handle :func:`_open_config_file` opened through no link below + ``base`` (vault BACKLOG #6573), and its member is described and filled from that handle, + never by its name again, so a folder or a file swapped for a link after the walk checked it + adds nothing from behind the link to the archive. What a swap still reaches, and when a + file the walk accepted fails the backup, is stated once, in the ``include_config`` row of + ``docs/CONFIGURATION.md``. A config editor's lock file and candidate directories are skipped (vault BACKLOG #2782): a candidate lives only for one validation, so one listed here may be gone by the add, and a @@ -1470,35 +1469,42 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ # The names this walk added as regular members, which a second hard link may name; their # count is the regular files it added. regular_names: set[str] = set() + # Resolved once: every file is opened down from it, never through a link below it. A + # share that cannot resolve leaves the path as given, which on Windows fails the final-path + # compare, so its files are passed over rather than the store backup lost. + try: + root_real = base.resolve() + except OSError: + root_real = base.absolute() # Sorted whole, as the earlier `sorted(rglob)` was, so the member order is unchanged. for path in sorted(found): rel = path.relative_to(base) if _is_config_edit_artifact(rel): continue - try: - st = path.lstat() - regular = stat.S_ISREG(st.st_mode) and not _stat_names_another_path(st) - except FileNotFoundError: + if tar.name is not None and os.path.abspath(path) == tar.name: + continue # the archive being written, which tar.add skipped too + opened = _open_config_file(path, base, root_real) + if opened == "gone": # Gone since the listing, such as an editor's save probe: no longer config. continue - except OSError: - regular = False - if not regular: + if opened == "passed-over": passed_over.add(rel.as_posix()) continue - before = len(tar.getmembers()) - tar.add(path, arcname=f"{_CONFIG_PREFIX}{rel.as_posix()}", recursive=False) - # Counted from the member tar wrote, so a path swapped for a link or a folder after the - # check above does not count as a file, nor one tar skipped, such as a socket. - members = tar.getmembers() - last = members[-1] if len(members) > before else None - # A second name of a file this walk already added is carried too, so it is not passed - # over: tar stores it as a link member naming that one, and a restore writes it as a - # copy of that file's bytes (`_extract_config_members`) (vault BACKLOG #5233). - if last is not None and last.isreg(): - regular_names.add(last.name) - elif not (last is not None and last.islnk() and last.linkname in regular_names): - passed_over.add(rel.as_posix()) + with os.fdopen(opened, "rb") as handle: + # The member is described and filled from the handle opened above, never by name + # again, so a name swapped for a link after that open adds nothing behind it. + info = tar.gettarinfo(arcname=f"{_CONFIG_PREFIX}{rel.as_posix()}", fileobj=handle) + # A second name of a file this walk already added is carried too, so it is not + # passed over: tar stores it as a link member naming that one, and a restore + # writes it as a copy of that file's bytes (`_extract_config_members`) (vault + # BACKLOG #5233). + if info.isreg(): + tar.addfile(info, handle) + regular_names.add(info.name) + elif info.islnk() and info.linkname in regular_names: + tar.addfile(info) + else: + passed_over.add(rel.as_posix()) if passed_over: from messagefoundry.config.fingerprint import describe_left_out @@ -3727,11 +3733,64 @@ def _stat_names_another_path(st: os.stat_result) -> bool: ) +def _open_config_file( + path: Path, base: Path, root_real: Path +) -> int | Literal["gone", "passed-over"]: + """Open the config file ``path``, listed under ``base``, to read, through no link at any + component below ``base`` (vault BACKLOG #6573), and return its descriptor, which the caller + closes. ``root_real`` is ``base`` resolved. ``"gone"`` means the file is gone since it was + listed, and ``"passed-over"`` that the walk passes it over as no regular file reached through + no link. + + The ``lstat`` screen comes first, so what it passes over is what the walk passed over before: + at least a link, a non-regular file and a file whose ``lstat`` fails. The open is the file + connector's confined read (:func:`~messagefoundry.transports.file._open_confined`): POSIX opens + each component relative to its parent's descriptor with ``O_NOFOLLOW``; Windows holds each + folder, opens the file as itself, and requires its final path to be ``root_real`` joined with + the listed names. Its refusal of a link is a pass-over. Any other failure is screened again: a + name that is now gone is ``"gone"``, and one that is now no regular file, or a link, is passed + over. What else is passed over, and what fails the backup, is stated once, in the + ``include_config`` row of ``docs/CONFIGURATION.md``. A failure raised names the file relative + to ``base``, which is operator configuration.""" + try: + st = path.lstat() + except FileNotFoundError: + return "gone" + except OSError: + return "passed-over" + if not stat.S_ISREG(st.st_mode) or _stat_names_another_path(st): + return "passed-over" + try: + fd, _st = _open_confined(path, base, root_real) + except (_Unconfined, _Replaced): + return "passed-over" + except OSError as exc: + # Windows refuses to open a folder or a junction as a file with ERROR_ACCESS_DENIED, and a + # step of the confined open can report a name it did not find although the file is there, + # so the name is screened again rather than read from the error. + try: + again = path.lstat() + except FileNotFoundError: + return "gone" + except OSError: + return "passed-over" + if not stat.S_ISREG(again.st_mode) or _stat_names_another_path(again): + return "passed-over" + if getattr(exc, "winerror", None) in _WIN_UNSUPPORTED: + return "passed-over" # at least a volume that cannot report a final path + name = scrub_log_argument(path.relative_to(base).as_posix()) + raise OSError( + exc.errno, f"the config file {name} cannot be opened: {exc.strerror}" + ) from exc + return fd + + def _tree_size(root: Path) -> int: """The total size of the regular files under ``root``, on the walk ``_add_config_dir`` uses (:func:`_walk_unfollowed`), so a directory link it passes over is not counted. Unlike that walk it does not skip the backup's own staging or a config editor's lock file. 0 when ``root`` - cannot be walked.""" + cannot be walked. It reads each file by name, not through the handle the walk adds it from + (:func:`_open_config_file`, vault BACKLOG #6573).""" total = 0 for dirpath, dirs, files in _walk_unfollowed(root): # Candidate directories are pruned, as _add_config_dir skips their files. diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index 0e6b401f0b..41df353966 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -709,18 +709,20 @@ async def test_add_config_dir_skips_edit_candidates_and_the_lock( golden.mkdir(parents=True) (golden / "a01.hl7").write_text("MSH|^~\\&|") - # The edit finishes after the walk listed its candidate: the directory is gone by its add. - real_add = tarfile.TarFile.add + # The edit finishes after the walk listed its candidate: the directory is gone by its add, + # which opens each file through the confined open (vault BACKLOG #6573). + from messagefoundry.transports.file import _open_confined as real_open + vanished: list[Path] = [] - def add(self: tarfile.TarFile, name: object, *args: object, **kwargs: object) -> None: - if live in Path(str(name)).parents: + def open_confined(path: Path, base: Path, root_real: Path) -> tuple[int, os.stat_result]: + if live in path.parents: shutil.rmtree(live, ignore_errors=True) - vanished.append(Path(str(name))) - real_add(self, name, *args, **kwargs) # type: ignore[arg-type] + vanished.append(path) + return real_open(path, base, root_real) try: - monkeypatch.setattr(tarfile.TarFile, "add", add) + monkeypatch.setattr("messagefoundry.pipeline.dr_backup._open_confined", open_confined) runner = BackupRunner( store, _settings(tmp_path / "b", key_b64), @@ -1326,6 +1328,220 @@ async def test_a_symlink_beside_a_hardlink_pair_is_still_skipped(tmp_path, key_b assert _skipped_everywhere(result, manifest, detail) == ["c.toml"] +# --- config bundle: a name swapped for a link after the walk checked it (vault BACKLOG #6573) --- + +_SWAP_SECRET = b"SMUGGLED-BY-A-SWAP " * 40 + + +def _swap_after_its_first_check( + monkeypatch: pytest.MonkeyPatch, checked: Path, aside: Path, make_link, target: Path +) -> list[Path]: + """Swap ``checked`` for a link to ``target``, made by ``make_link(target, link)``, right after + the first ``lstat`` of it, and answer that ``lstat`` and every later one of ``checked`` with + what the first one read. Every check by ``lstat`` then sees what the operator put there, while + every open by name meets the link: the race at its widest. The original is moved to ``aside``. + ``make_link`` is tried once first, so a platform that cannot make the link skips before the + run, not inside it. Returns the list the swap appends ``checked`` to, so a test can show the + swap ran.""" + probe = aside.with_name(f"{aside.name}-probe") + make_link(target, probe) + try: + os.rmdir(probe) # a folder, a junction or a Windows directory symlink + except OSError: + os.unlink(probe) + real_lstat = os.lstat + key = os.path.normcase(os.fspath(checked)) + seen: list[os.stat_result] = [] + swapped: list[Path] = [] + + def lstat(path, *args, **kwargs): + if ( + args + or kwargs + or not isinstance(path, (str, os.PathLike)) + or os.path.normcase(os.fspath(path)) != key + ): + return real_lstat(path, *args, **kwargs) + if not seen: + seen.append(real_lstat(path)) + os.replace(checked, aside) + make_link(target, checked) + swapped.append(checked) + return seen[0] + + monkeypatch.setattr(os, "lstat", lstat) + return swapped + + +def _make_file_symlink(target: Path, link: Path) -> None: + try: + link.symlink_to(target) + except (OSError, NotImplementedError): + pytest.skip("a file symlink cannot be made here (Windows without the privilege)") + + +def _make_folder(target: Path, link: Path) -> None: + """Not a link: a plain folder at ``link``, for a file swapped for a folder.""" + link.mkdir() + + +async def _pass_with_bytes( + tmp_path: Path, key_b64: str, cfg: Path +) -> tuple[BackupResult, list[str], bytes]: + """One full pass over ``cfg``: the result, the archive's ``config/`` member names, and the + archive's decrypted bytes.""" + import base64 + + store = await _store_with_rows(tmp_path / "msg.db", key_b64) + try: + result = await BackupRunner( + store, + _settings(tmp_path / "b", key_b64), + store_settings=_store_settings(tmp_path / "msg.db", key_b64), + config_dir=cfg, + ).run_once(now=1.0) + finally: + await store.close() + assert result is not None and result.verify is not None and result.verify.status == "PASS" + with open(result.archive_path, "rb") as src: + tar_bytes = _decrypt_to_bytes(src, base64.b64decode(key_b64)) + names = sorted(n for n in _member_names(tar_bytes) if n.startswith("config/")) + return result, names, tar_bytes + + +def _config_for_a_swap(tmp_path: Path) -> tuple[Path, Path]: + """A config dir with a file, ``swapped.toml``, shorter than the host secret, and a folder, + ``sub``, beside a control file and a control folder; and a host folder outside it holding the + secret, ``secret.txt``. Returns both.""" + cfg = tmp_path / "config" + (cfg / "sub").mkdir(parents=True) + (cfg / "keep").mkdir() + (cfg / "feed.py").write_text("# router") + (cfg / "keep" / "plain.txt").write_text("plain subfolder file") + (cfg / "sub" / "secret.txt").write_text("the operator's own sub file") + (cfg / "swapped.toml").write_bytes(b"#" * 100) + host = tmp_path / "host_dir" + host.mkdir() + (host / "secret.txt").write_bytes(_SWAP_SECRET) + return cfg, host + + +async def test_a_file_swapped_for_a_link_after_its_check_adds_nothing_behind_it( + tmp_path, key_b64, monkeypatch +) -> None: + """A file the walk checked, then swapped for a symlink to a host file before the add opened + it, put up to its own size of the host file's bytes in the archive: the add opened it by name + and followed the link. The add now opens what it checked through no link, so nothing behind + the link is added and the name is recorded as passed over. The control files are still + carried.""" + cfg, host = _config_for_a_swap(tmp_path) + swapped = _swap_after_its_first_check( + monkeypatch, + cfg / "swapped.toml", + tmp_path / "aside.toml", + _make_file_symlink, + host / "secret.txt", + ) + result, names, tar_bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) + assert swapped == [cfg / "swapped.toml"], "the swap ran" + assert b"SMUGGLED-BY-A-SWAP" not in tar_bytes + assert names == ["config/feed.py", "config/keep/plain.txt", "config/sub/secret.txt"] + assert result.config_skipped_files == ("swapped.toml",) + + +@pytest.mark.parametrize( + "make_link", + [_make_folder, _make_junction, _make_dir_symlink], + ids=["folder", "junction", "symlink"], +) +async def test_a_file_swapped_for_a_folder_between_its_screen_and_its_open_is_passed_over( + tmp_path, key_b64, monkeypatch, make_link +) -> None: + """A file swapped for a folder, a junction or a directory symlink after the walk listed it + and screened it, just before the add opens it, is passed over and recorded, and the backup + still succeeds. Windows refuses to open such a name as a file with an access error, which + must not read as a locked config file and fail the backup. The swap is made at the open + itself, so it lands in that window and nowhere else. The folder case is the control: it is + no link, and is passed over all the same.""" + from messagefoundry.transports.file import _open_confined as real_open + + cfg, host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + probe = tmp_path / "probe" + make_link(host, probe) # a platform that cannot make the link skips here, before the run + try: + os.rmdir(probe) + except OSError: + os.unlink(probe) + swapped: list[Path] = [] + + def open_after_a_swap(path: Path, base: Path, root_real: Path): + if path == checked and not swapped: + os.replace(checked, tmp_path / "aside.toml") + make_link(host, checked) + swapped.append(checked) + return real_open(path, base, root_real) + + monkeypatch.setattr("messagefoundry.pipeline.dr_backup._open_confined", open_after_a_swap) + result, names, tar_bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) + assert swapped == [checked], "the swap ran" + assert b"SMUGGLED-BY-A-SWAP" not in tar_bytes + assert names == ["config/feed.py", "config/keep/plain.txt", "config/sub/secret.txt"] + assert result.config_skipped_files == ("swapped.toml",) + + +async def test_a_config_file_that_still_reads_as_regular_but_will_not_open_fails_the_backup( + tmp_path, key_b64, monkeypatch +) -> None: + """A file the walk accepted, which still screens as a regular file but whose open fails + with an error that is no refusal of a link, such as a permission error, fails the backup, + naming the file, rather than being passed over: the archive would otherwise lack a config + file with nothing but a WARNING to say so. The control is the same pass with the open left + alone.""" + from messagefoundry.transports.file import _open_confined as real_open + + cfg, _host = _config_for_a_swap(tmp_path) + (tmp_path / "control").mkdir() + _result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) + assert "config/swapped.toml" in names # the control + + def open_confined(path: Path, base: Path, root_real: Path) -> tuple[int, os.stat_result]: + if path.name == "swapped.toml": + raise PermissionError(13, "Permission denied") + return real_open(path, base, root_real) + + monkeypatch.setattr("messagefoundry.pipeline.dr_backup._open_confined", open_confined) + with pytest.raises(BackupError, match="swapped.toml"): + await _pass_with_bytes(tmp_path, key_b64, cfg) + + +@pytest.mark.parametrize( + "make_link", [_make_junction, _make_dir_symlink], ids=["junction", "symlink"] +) +async def test_a_folder_swapped_for_a_link_after_its_check_adds_nothing_behind_it( + tmp_path, key_b64, monkeypatch, make_link +) -> None: + """A folder the walk checked and decided to descend, then swapped for a link to a host + folder, was listed through the link, and the add opened each name under it by name, so the + host folder's files reached the archive. The add now opens each file down from the config dir + through no link, so nothing behind the link is added. Where the walk lists the names behind + it, they are recorded as passed over, never their bytes. The control folder is still + carried.""" + if sys.platform == "win32" and make_link is _make_dir_symlink: + # Windows' os.walk tests a folder for a symlink itself, not by os.lstat, so it never + # descends a symlink swapped in, on the old code or the new: nothing here to show. + pytest.skip("os.walk on Windows does not descend a directory symlink swapped in") + cfg, host = _config_for_a_swap(tmp_path) + swapped = _swap_after_its_first_check( + monkeypatch, cfg / "sub", tmp_path / "aside", make_link, host + ) + result, names, tar_bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) + assert swapped == [cfg / "sub"], "the swap ran" + assert b"SMUGGLED-BY-A-SWAP" not in tar_bytes + assert names == ["config/feed.py", "config/keep/plain.txt", "config/swapped.toml"] + assert result.config_skipped_files == ("sub/secret.txt",) + + def _lose_config_after_its_inspection(monkeypatch: pytest.MonkeyPatch, cfg: Path) -> None: """Remove ``cfg`` once ``_inspect_config`` has read it, before the walk, so its guard does not fire. A pass over any other config dir is left alone.""" From 12fa88b4d316c42ac05b442e1c4a37b888e814c0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:05:48 -0600 Subject: [PATCH 05/49] docs: the include_config row says what a link swap still reaches in the config walk (BACKLOG #6573) The row now states that the walk adds each file from a handle opened through no link below the config dir, and what a swap still reaches, with "at least", on POSIX and Windows alike: names listed behind a folder swapped while the walk lists it, the space estimate read by name, a second hard link, and on Windows the reopen by name of a file whose reparse point names no path. It also states when a file the walk accepted fails the backup and when Windows passes it over. PARTIAL: the listing and the space estimate still read by name; closing them needs a descriptor walk on POSIX and a held walk on Windows. Proposed PR title: The DR config walk adds each file through no link, closing the swap race for content (BACKLOG #6573) Proposed vault banner: PARTIAL on branch b20053-6573 (batch 20053): content from behind a link swapped in after the check no longer reaches the archive; the listing and the space estimate still read by name. Verified-by: tests --- docs/CONFIGURATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 06d86fa2ad..e6568737a4 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. A file the archive walk accepts and then cannot open or read fails the backup. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. A file the archive walk accepts and then cannot open or read fails the backup. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573). A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING, and the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened a second time by name, which can follow a link swapped in between, even to a UNC path, and so reach the host it names before the engine refuses what it reached. When that open fails on a name that still reads as a regular file, the backup fails, naming the file, except that on Windows an `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, as from a volume that cannot report a file's final path, passes the file over. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | From 96cd0fe84b766494e754451949670ce546904c06 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:37:13 -0600 Subject: [PATCH 06/49] dr_backup: a config file the walk accepted fails or is added by name as before, on three faults (BACKLOG #6573) A repair round on the confined config open, each fix restoring the outcome origin/main had: - A confined open that fails because a share or network path cannot be reached (Windows winerror 53 or 67, which Python maps to ENOENT) fails the backup, naming the file. It no longer reads as a file gone since the listing when the second look meets the same fault. A plain ENOENT still means gone. Read with path_reach.is_absent. - A second look at the name after a failed open that fails for any reason but absence (EIO, a stale handle, winerror 64) fails the backup, naming the file, rather than passing it over. - On Windows, a file whose final path alone cannot be read, with an error outside ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED and ERROR_INVALID_PARAMETER (such as winerror 3 on a volume mounted with no drive letter), is added by its name as before, rather than failing every backup. _final_path_fails re-opens the file through no link and reads its final path, so only that step's error takes this route. Each has a test that fails on the unrepaired head. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 89 ++++++++++++---- tests/test_backup_runner.py | 147 +++++++++++++++++++++++++++ 2 files changed, 219 insertions(+), 17 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index d6f8ca3090..162f18cd7c 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -67,6 +67,7 @@ from messagefoundry.config.tls_policy import HopPosture from messagefoundry.controlchars import scrub_log_argument from messagefoundry.last_resort import run_guarded +from messagefoundry.path_reach import is_absent from messagefoundry.pipeline.alerts import AlertSink, LoggingAlertSink, utc_or_unknown from messagefoundry.pipeline.cluster import ClusterCoordinator, NullCoordinator from messagefoundry.redaction import json_loads_or_refusal, safe_exc, safe_text, shown_class_name @@ -108,6 +109,7 @@ from messagefoundry.store.schema_verify import SchemaMismatchError, is_schema_step_error from messagefoundry.terminal_text import escape_for_terminal from messagefoundry.transports.file import ( + _FILE_READ_ATTRIBUTES, _FLAG_BACKUP_SEMANTICS, _FLAG_OPEN_REPARSE_POINT, _NAME_SURROGATE, @@ -117,6 +119,7 @@ _fd_for, _file_id, _handle_final_path, + _listed_parts, _open_confined, _os_handle, _Replaced, @@ -124,6 +127,7 @@ _win_create, _win_hold_dirs, _win_lstat, + _win_open_confined, _win_open_file, _win_release, ) @@ -1429,7 +1433,9 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ Each file is added from a handle :func:`_open_config_file` opened through no link below ``base`` (vault BACKLOG #6573), and its member is described and filled from that handle, never by its name again, so a folder or a file swapped for a link after the walk checked it - adds nothing from behind the link to the archive. What a swap still reaches, and when a + adds nothing from behind the link to the archive. On Windows a file whose final path + cannot be read (:func:`_final_path_fails`) is added by its name instead, as before, which + follows a link swapped in. What a swap still reaches, and when a file the walk accepted fails the backup, is stated once, in the ``include_config`` row of ``docs/CONFIGURATION.md``. @@ -1490,6 +1496,19 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ if opened == "passed-over": passed_over.add(rel.as_posix()) continue + if opened == "by-name": + # Windows could not read this file's final path: added by its name, as before + # vault BACKLOG #6573, and counted from the member tar wrote, so a name swapped for + # a folder does not count as a file, nor one tar skipped, such as a socket. + before = len(tar.getmembers()) + tar.add(path, arcname=f"{_CONFIG_PREFIX}{rel.as_posix()}", recursive=False) + members = tar.getmembers() + last = members[-1] if len(members) > before else None + if last is not None and last.isreg(): + regular_names.add(last.name) + elif not (last is not None and last.islnk() and last.linkname in regular_names): + passed_over.add(rel.as_posix()) + continue with os.fdopen(opened, "rb") as handle: # The member is described and filled from the handle opened above, never by name # again, so a name swapped for a link after that open adds nothing behind it. @@ -3735,22 +3754,26 @@ def _stat_names_another_path(st: os.stat_result) -> bool: def _open_config_file( path: Path, base: Path, root_real: Path -) -> int | Literal["gone", "passed-over"]: +) -> int | Literal["gone", "passed-over", "by-name"]: """Open the config file ``path``, listed under ``base``, to read, through no link at any component below ``base`` (vault BACKLOG #6573), and return its descriptor, which the caller closes. ``root_real`` is ``base`` resolved. ``"gone"`` means the file is gone since it was - listed, and ``"passed-over"`` that the walk passes it over as no regular file reached through - no link. + listed, ``"passed-over"`` that the walk passes it over as no regular file reached through no + link, and ``"by-name"`` that the caller adds it by its name, as the walk did before. The ``lstat`` screen comes first, so what it passes over is what the walk passed over before: at least a link, a non-regular file and a file whose ``lstat`` fails. The open is the file connector's confined read (:func:`~messagefoundry.transports.file._open_confined`): POSIX opens each component relative to its parent's descriptor with ``O_NOFOLLOW``; Windows holds each folder, opens the file as itself, and requires its final path to be ``root_real`` joined with - the listed names. Its refusal of a link is a pass-over. Any other failure is screened again: a - name that is now gone is ``"gone"``, and one that is now no regular file, or a link, is passed - over. What else is passed over, and what fails the backup, is stated once, in the - ``include_config`` row of ``docs/CONFIGURATION.md``. A failure raised names the file relative + the listed names. Its refusal of a link is a pass-over. A share or network path it cannot + reach, which Windows reports as a name not found, fails the backup + (:func:`~messagefoundry.path_reach.is_absent`). Any other failure is screened again: a name + that is now gone is ``"gone"``, one that is now no regular file, or a link, is passed over, + and a screen that fails for any reason but absence fails the backup. On Windows a file whose + final path alone cannot be read, with an error other than the ones that say the volume does + not do that, is ``"by-name"`` (:func:`_final_path_fails`). What else is passed over, and what + fails the backup, is stated once, in the ``include_config`` row of ``docs/CONFIGURATION.md``. A failure raised names the file relative to ``base``, which is operator configuration.""" try: st = path.lstat() @@ -3765,26 +3788,58 @@ def _open_config_file( except (_Unconfined, _Replaced): return "passed-over" except OSError as exc: + if isinstance(exc, FileNotFoundError) and not is_absent(exc): + # A share or network path that cannot be reached, which Windows maps to ENOENT: the + # file was there at the screen, so this is a fault, as the add by name met it before. + raise _config_file_error(path, base, exc) from exc # Windows refuses to open a folder or a junction as a file with ERROR_ACCESS_DENIED, and a # step of the confined open can report a name it did not find although the file is there, # so the name is screened again rather than read from the error. try: again = path.lstat() - except FileNotFoundError: - return "gone" - except OSError: - return "passed-over" + except OSError as screen_exc: + if is_absent(screen_exc): + return "gone" + raise _config_file_error(path, base, screen_exc) from screen_exc if not stat.S_ISREG(again.st_mode) or _stat_names_another_path(again): return "passed-over" - if getattr(exc, "winerror", None) in _WIN_UNSUPPORTED: + winerror = getattr(exc, "winerror", None) + if winerror in _WIN_UNSUPPORTED: return "passed-over" # at least a volume that cannot report a final path - name = scrub_log_argument(path.relative_to(base).as_posix()) - raise OSError( - exc.errno, f"the config file {name} cannot be opened: {exc.strerror}" - ) from exc + if isinstance(winerror, int) and _final_path_fails(path, base, root_real, winerror): + return "by-name" + raise _config_file_error(path, base, exc) from exc return fd +def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: + """The error that fails the backup for the config file ``path``, naming it relative to + ``base`` and keeping ``exc``'s errno and text.""" + name = scrub_log_argument(path.relative_to(base).as_posix()) + return OSError(exc.errno, f"the config file {name} cannot be opened: {exc.strerror}") + + +def _final_path_fails(path: Path, base: Path, root_real: Path, winerror: int) -> bool: + """Windows: whether the confined open of ``path`` fails at its final-path check alone, with + ``winerror``, as on a volume mounted with no drive letter (ERROR_PATH_NOT_FOUND). The file is + opened again through no link, as :func:`_open_confined` does, and its final path read; any + other outcome, the open's own failure included, is False. Always False on POSIX, which has no + final-path check.""" + if sys.platform != "win32": + return False + try: + fd = _win_open_confined(root_real, _listed_parts(path, base), _FILE_READ_ATTRIBUTES) + except OSError: + return False + try: + _handle_final_path(_os_handle(fd)) + except OSError as exc: + return getattr(exc, "winerror", None) == winerror + finally: + os.close(fd) + return False + + def _tree_size(root: Path) -> int: """The total size of the regular files under ``root``, on the walk ``_add_config_dir`` uses (:func:`_walk_unfollowed`), so a directory link it passes over is not counted. Unlike that diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index 41df353966..6d4e31fd62 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1515,6 +1515,153 @@ def open_confined(path: Path, base: Path, root_real: Path) -> tuple[int, os.stat await _pass_with_bytes(tmp_path, key_b64, cfg) +def _os_error(code: int, text: str, winerror: int | None = None) -> OSError: + """An ``OSError`` as the platform raises it for ``code``, carrying ``winerror`` where given. + Windows maps ``winerror`` to the errno itself; POSIX has no such attribute, so it is set.""" + exc = OSError(code, text, None, winerror) if winerror is not None else OSError(code, text) + if winerror is not None and not hasattr(exc, "winerror"): + setattr(exc, "winerror", winerror) # noqa: B010 - not an attribute on POSIX + return exc + + +def _fault_the_open_and_its_screen( + monkeypatch: pytest.MonkeyPatch, checked: Path, open_exc: OSError, screen_exc: OSError +) -> list[Path]: + """Fail the confined open of ``checked`` with ``open_exc``, and from then on every ``lstat`` + of ``checked`` with ``screen_exc``, so the walk's first screen sees the file and the screen + after the failed open meets the fault. Returns the list the open appends ``checked`` to, so a + test can show the fault ran.""" + from messagefoundry.transports.file import _open_confined as real_open + + real_lstat = os.lstat + key = os.path.normcase(os.fspath(checked)) + faulted: list[Path] = [] + + def open_confined(path: Path, base: Path, root_real: Path) -> tuple[int, os.stat_result]: + if path == checked: + faulted.append(path) + raise open_exc + return real_open(path, base, root_real) + + def lstat(path, *args, **kwargs): + if ( + faulted + and not args + and not kwargs + and isinstance(path, (str, os.PathLike)) + and os.path.normcase(os.fspath(path)) == key + ): + raise screen_exc + return real_lstat(path, *args, **kwargs) + + monkeypatch.setattr("messagefoundry.pipeline.dr_backup._open_confined", open_confined) + monkeypatch.setattr(os, "lstat", lstat) + return faulted + + +@pytest.mark.parametrize("winerror", [53, 67], ids=["bad-netpath", "bad-net-name"]) +async def test_a_config_file_on_an_unreachable_share_fails_the_backup( + tmp_path, key_b64, monkeypatch, winerror +) -> None: + """A file the walk screened, whose confined open then fails because its share or network + path cannot be reached (Windows ERROR_BAD_NETPATH or ERROR_BAD_NET_NAME, which Python maps to + ENOENT), fails the backup, naming the file, as the add by name did before vault BACKLOG #6573. + It is not read as a file gone since the listing, though the screen after the open meets the + same fault. The control is a plain ENOENT at both, which is a file gone and is left out.""" + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + + (tmp_path / "control").mkdir() + gone = _os_error(2, "No such file or directory") + faulted = _fault_the_open_and_its_screen(monkeypatch, checked, gone, gone) + result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) + assert faulted == [checked], "the control's fault ran" + assert "config/swapped.toml" not in names # the control: a file gone is left out + assert result.config_skipped_files == () + monkeypatch.undo() + + share = _os_error(2, "The network path was not found", winerror) + faulted = _fault_the_open_and_its_screen(monkeypatch, checked, share, share) + with pytest.raises(BackupError, match="swapped.toml"): + await _pass_with_bytes(tmp_path, key_b64, cfg) + assert faulted == [checked], "the fault ran" + + +@pytest.mark.parametrize( + ("code", "winerror"), [(5, None), (22, 64)], ids=["eio", "netname-deleted"] +) +async def test_a_config_file_whose_screen_fails_after_a_failed_open_fails_the_backup( + tmp_path, key_b64, monkeypatch, code, winerror +) -> None: + """A file the walk screened, whose confined open then fails and whose ``lstat`` after it + fails for a reason other than absence, such as EIO or a Windows share whose name was deleted, + fails the backup, naming the file, as the add by name did before vault BACKLOG #6573. It is + not passed over.""" + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + fault = _os_error(code, "I/O fault", winerror) + faulted = _fault_the_open_and_its_screen( + monkeypatch, checked, _os_error(13, "Permission denied"), fault + ) + with pytest.raises(BackupError, match="swapped.toml"): + await _pass_with_bytes(tmp_path, key_b64, cfg) + assert faulted == [checked], "the fault ran" + + +@pytest.mark.skipif(sys.platform != "win32", reason="the final-path check is Windows-only") +async def test_a_config_file_whose_final_path_cannot_be_read_is_added_by_name( + tmp_path, key_b64, monkeypatch +) -> None: + """On Windows a file whose final path cannot be read with an error other than the ones that + say the volume does not do that, such as ERROR_PATH_NOT_FOUND on a volume mounted with no + drive letter, is added by its name, as it was before vault BACKLOG #6573, rather than failing + every backup of that config dir. The control is the same error from the confined open itself + with the final path readable, which still fails the backup, naming the file.""" + import messagefoundry.pipeline.dr_backup as dr_backup + import messagefoundry.transports.file as file_mod + + cfg, _host = _config_for_a_swap(tmp_path) + checked = os.path.normcase(os.fspath((cfg / "swapped.toml").resolve())) + real_final = file_mod._handle_final_path + failed: list[str] = [] + + def final_path(handle: int) -> str: + found = real_final(handle) + if os.path.normcase(file_mod._plain(found)) == checked: + failed.append(found) + raise _os_error(2, "The system cannot find the path specified", 3) + return found + + monkeypatch.setattr(file_mod, "_handle_final_path", final_path) + monkeypatch.setattr(dr_backup, "_handle_final_path", final_path) + result, names, tar_bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) + assert failed, "the final-path fault ran" + assert names == [ + "config/feed.py", + "config/keep/plain.txt", + "config/sub/secret.txt", + "config/swapped.toml", + ] + with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r") as tar: + member = tar.extractfile("config/swapped.toml") + assert member is not None and member.read() == b"#" * 100 + assert result.config_skipped_files == () + monkeypatch.undo() + + # The control: the open itself fails so, and the final path reads, so the backup fails. + real_open = file_mod._open_confined + + def open_confined(path: Path, base: Path, root_real: Path) -> tuple[int, os.stat_result]: + if path.name == "swapped.toml": + raise _os_error(2, "The system cannot find the path specified", 3) + return real_open(path, base, root_real) + + monkeypatch.setattr(dr_backup, "_open_confined", open_confined) + (tmp_path / "control").mkdir() + with pytest.raises(BackupError, match="swapped.toml"): + await _pass_with_bytes(tmp_path / "control", key_b64, cfg) + + @pytest.mark.parametrize( "make_link", [_make_junction, _make_dir_symlink], ids=["junction", "symlink"] ) From 1608d20e8bb24076d6673a672dfe5e42fde96396 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:37:49 -0600 Subject: [PATCH 07/49] docs: the include_config row states one rule for a config file the walk cannot open or read (BACKLOG #6573) The row said both that such a file fails the backup and, later, that some are passed over. It now states the rule once: fail, naming the file, except a name gone by then (left out), one that no longer reads as a regular file (passed over), the three Windows "volume does not do that" errors (passed over) and a Windows file whose final path alone cannot be read (added by its name, which follows a link swapped in). An unreachable share, a failed second look and a failed read each fail the backup. The swap sentence names the by-name exception. Proposed PR title: DR config walk opens each file through no link, and keeps main's outcome on share, screen and final-path faults (BACKLOG #6573) Proposed vault banner: BUILT on engine branch b20053-6573b: the config walk adds each file from a handle opened through no link; a repair round restored origin/main's outcome for an unreachable share, a failed second screen and a Windows final-path fault. Verified-by: none --- docs/CONFIGURATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index e6568737a4..652d55ace9 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. A file the archive walk accepts and then cannot open or read fails the backup. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573). A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING, and the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened a second time by name, which can follow a link swapped in between, even to a UNC path, and so reach the host it names before the engine refuses what it reached. When that open fails on a name that still reads as a regular file, the backup fails, naming the file, except that on Windows an `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, as from a volume that cannot report a file's final path, passes the file over. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, except a file it adds by its name as stated below, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573). A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING, and the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened a second time by name, which can follow a link swapped in between, even to a UNC path, and so reach the host it names before the engine refuses what it reached. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows an `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, as from a volume that cannot report a file's final path, passes the file over; and a file whose final path alone cannot be read with any other error, as on a volume mounted with no drive letter, is added by its name, which follows a link swapped in. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | From 50661614ecad19d58bd969d75b18ea82d3334985 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:22:56 -0600 Subject: [PATCH 08/49] dr_backup: a config file whose Windows final path cannot be read is added from its handle (BACKLOG #6573) Round 3 of vault BACKLOG #6573. On 6573b a config file the confined open had opened and found regular, whose Windows final-path query alone failed with ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER, was passed over, where origin/main bundled it, and on any other code was opened again by name. transports/file.py: _open_confined takes an opt-in `unverified` list. On it alone, when the final-path query itself fails after the regular-file check, the open descriptor is returned and the query's error appended; a final path that is read and names another path is still refused, and on Windows the root itself is held and tag-checked too (_win_hold_dirs(hold_root=True)). The default, which the file connector uses, is unchanged: the read fails and the file stays in place. The unused _final_path wrapper is gone. pipeline/dr_backup.py: the config walk uses the opt-in, adds such a file from the returned handle, closes the descriptor on every path, a tar failure included, and logs one WARNING per walk counting such files, with the residual stated: a folder above the config dir swapped after resolve() is not detected. _final_path_fails and the by-name tar.add branch are gone. _config_file_error keeps the Windows code and says the file could not be added to the backup. 6573b's fixes for an unreachable share and a failed re-screen stay. tests: the final-path fault on winerror 1, 50, 87 and 3 adds the file from its handle and closes it, also when tar fails; the default path still fails the read and leaves the file; a mismatched final path is still a pass-over on both paths; a root swapped for a junction is refused on the opt-in path; the early unreachable-share raise and the screen-fault test gain the arms and controls they lacked. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 130 +++++------ messagefoundry/transports/file.py | 60 +++-- tests/test_backup_runner.py | 232 ++++++++++++++++---- tests/test_file_open_confined_unverified.py | 208 ++++++++++++++++++ 4 files changed, 494 insertions(+), 136 deletions(-) create mode 100644 tests/test_file_open_confined_unverified.py diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 162f18cd7c..ba0b100e14 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -109,7 +109,6 @@ from messagefoundry.store.schema_verify import SchemaMismatchError, is_schema_step_error from messagefoundry.terminal_text import escape_for_terminal from messagefoundry.transports.file import ( - _FILE_READ_ATTRIBUTES, _FLAG_BACKUP_SEMANTICS, _FLAG_OPEN_REPARSE_POINT, _NAME_SURROGATE, @@ -119,7 +118,6 @@ _fd_for, _file_id, _handle_final_path, - _listed_parts, _open_confined, _os_handle, _Replaced, @@ -127,7 +125,6 @@ _win_create, _win_hold_dirs, _win_lstat, - _win_open_confined, _win_open_file, _win_release, ) @@ -1430,14 +1427,10 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ directory link the walk lists as a directory is named in one WARNING, since the loader and the config digest may read through it. - Each file is added from a handle :func:`_open_config_file` opened through no link below - ``base`` (vault BACKLOG #6573), and its member is described and filled from that handle, - never by its name again, so a folder or a file swapped for a link after the walk checked it - adds nothing from behind the link to the archive. On Windows a file whose final path - cannot be read (:func:`_final_path_fails`) is added by its name instead, as before, which - follows a link swapped in. What a swap still reaches, and when a - file the walk accepted fails the backup, is stated once, in the ``include_config`` row of - ``docs/CONFIGURATION.md``. + Each file is added from the handle :func:`_open_config_file` opened (vault BACKLOG #6573), + and its member is described and filled from that handle, never by its name again. What a + link swapped in still reaches, which files are passed over and which fail the backup, is + stated once, in the ``include_config`` row of ``docs/CONFIGURATION.md``. A config editor's lock file and candidate directories are skipped (vault BACKLOG #2782): a candidate lives only for one validation, so one listed here may be gone by the add, and a @@ -1482,6 +1475,10 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ root_real = base.resolve() except OSError: root_real = base.absolute() + # One entry per file added although Windows could not report its final path, so the check + # that it was reached through no link did not run (vault BACKLOG #6573). + unverified: list[OSError] = [] + unverified_names: list[str] = [] # Sorted whole, as the earlier `sorted(rglob)` was, so the member order is unchanged. for path in sorted(found): rel = path.relative_to(base) @@ -1489,27 +1486,22 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ continue if tar.name is not None and os.path.abspath(path) == tar.name: continue # the archive being written, which tar.add skipped too - opened = _open_config_file(path, base, root_real) + unverified_before = len(unverified) + opened = _open_config_file(path, base, root_real, unverified) if opened == "gone": # Gone since the listing, such as an editor's save probe: no longer config. continue if opened == "passed-over": passed_over.add(rel.as_posix()) continue - if opened == "by-name": - # Windows could not read this file's final path: added by its name, as before - # vault BACKLOG #6573, and counted from the member tar wrote, so a name swapped for - # a folder does not count as a file, nor one tar skipped, such as a socket. - before = len(tar.getmembers()) - tar.add(path, arcname=f"{_CONFIG_PREFIX}{rel.as_posix()}", recursive=False) - members = tar.getmembers() - last = members[-1] if len(members) > before else None - if last is not None and last.isreg(): - regular_names.add(last.name) - elif not (last is not None and last.islnk() and last.linkname in regular_names): - passed_over.add(rel.as_posix()) - continue - with os.fdopen(opened, "rb") as handle: + if len(unverified) > unverified_before: + unverified_names.append(rel.as_posix()) + try: + handle = os.fdopen(opened, "rb") + except BaseException: + os.close(opened) + raise + with handle: # The member is described and filled from the handle opened above, never by name # again, so a name swapped for a link after that open adds nothing behind it. info = tar.gettarinfo(arcname=f"{_CONFIG_PREFIX}{rel.as_posix()}", fileobj=handle) @@ -1524,6 +1516,19 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ tar.addfile(info) else: passed_over.add(rel.as_posix()) + if unverified_names: + log.warning( + "DR backup: the config bundle of %s added %d file(s) whose final path Windows " + "could not report (first: %s), so the check that each was reached through no link " + "did not run for them. The config dir and each folder below it were held as " + "themselves, but a folder above the config dir swapped for a link after the backup " + "resolved the dir is not detected. First %d by name: %s", + base, + len(unverified_names), + safe_exc(unverified[0]), + min(len(unverified_names), _MAX_SKIPPED_RECORDED), + scrub_log_argument(", ".join(unverified_names[:_MAX_SKIPPED_RECORDED])), + ) if passed_over: from messagefoundry.config.fingerprint import describe_left_out @@ -3753,28 +3758,19 @@ def _stat_names_another_path(st: os.stat_result) -> bool: def _open_config_file( - path: Path, base: Path, root_real: Path -) -> int | Literal["gone", "passed-over", "by-name"]: - """Open the config file ``path``, listed under ``base``, to read, through no link at any - component below ``base`` (vault BACKLOG #6573), and return its descriptor, which the caller - closes. ``root_real`` is ``base`` resolved. ``"gone"`` means the file is gone since it was - listed, ``"passed-over"`` that the walk passes it over as no regular file reached through no - link, and ``"by-name"`` that the caller adds it by its name, as the walk did before. - - The ``lstat`` screen comes first, so what it passes over is what the walk passed over before: - at least a link, a non-regular file and a file whose ``lstat`` fails. The open is the file - connector's confined read (:func:`~messagefoundry.transports.file._open_confined`): POSIX opens - each component relative to its parent's descriptor with ``O_NOFOLLOW``; Windows holds each - folder, opens the file as itself, and requires its final path to be ``root_real`` joined with - the listed names. Its refusal of a link is a pass-over. A share or network path it cannot - reach, which Windows reports as a name not found, fails the backup - (:func:`~messagefoundry.path_reach.is_absent`). Any other failure is screened again: a name - that is now gone is ``"gone"``, one that is now no regular file, or a link, is passed over, - and a screen that fails for any reason but absence fails the backup. On Windows a file whose - final path alone cannot be read, with an error other than the ones that say the volume does - not do that, is ``"by-name"`` (:func:`_final_path_fails`). What else is passed over, and what - fails the backup, is stated once, in the ``include_config`` row of ``docs/CONFIGURATION.md``. A failure raised names the file relative - to ``base``, which is operator configuration.""" + path: Path, base: Path, root_real: Path, unverified: list[OSError] +) -> int | Literal["gone", "passed-over"]: + """Open the config file ``path``, listed under ``base``, to read, through no link below + ``base`` (vault BACKLOG #6573), and return its descriptor, which the caller closes. + ``root_real`` is ``base`` resolved. ``"gone"`` means the file is gone since it was listed, and + ``"passed-over"`` that the walk passes it over. + + The open is the file connector's confined open + (:func:`~messagefoundry.transports.file._open_confined`), opted in through ``unverified`` to + return a handle whose final path Windows cannot report, with that query's error appended to + ``unverified``. Which outcome each fault gets, and what a link swapped in still reaches, is + stated once, in the ``include_config`` row of ``docs/CONFIGURATION.md``. A failure raised names + the file relative to ``base``, which is operator configuration.""" try: st = path.lstat() except FileNotFoundError: @@ -3784,7 +3780,7 @@ def _open_config_file( if not stat.S_ISREG(st.st_mode) or _stat_names_another_path(st): return "passed-over" try: - fd, _st = _open_confined(path, base, root_real) + fd, _st = _open_confined(path, base, root_real, unverified=unverified) except (_Unconfined, _Replaced): return "passed-over" except OSError as exc: @@ -3803,41 +3799,21 @@ def _open_config_file( raise _config_file_error(path, base, screen_exc) from screen_exc if not stat.S_ISREG(again.st_mode) or _stat_names_another_path(again): return "passed-over" - winerror = getattr(exc, "winerror", None) - if winerror in _WIN_UNSUPPORTED: - return "passed-over" # at least a volume that cannot report a final path - if isinstance(winerror, int) and _final_path_fails(path, base, root_real, winerror): - return "by-name" + if getattr(exc, "winerror", None) in _WIN_UNSUPPORTED: + return "passed-over" # the volume does not do what a step of the open asked raise _config_file_error(path, base, exc) from exc return fd def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: """The error that fails the backup for the config file ``path``, naming it relative to - ``base`` and keeping ``exc``'s errno and text.""" + ``base`` and keeping ``exc``'s errno, its Windows code where it has one, and its text.""" name = scrub_log_argument(path.relative_to(base).as_posix()) - return OSError(exc.errno, f"the config file {name} cannot be opened: {exc.strerror}") - - -def _final_path_fails(path: Path, base: Path, root_real: Path, winerror: int) -> bool: - """Windows: whether the confined open of ``path`` fails at its final-path check alone, with - ``winerror``, as on a volume mounted with no drive letter (ERROR_PATH_NOT_FOUND). The file is - opened again through no link, as :func:`_open_confined` does, and its final path read; any - other outcome, the open's own failure included, is False. Always False on POSIX, which has no - final-path check.""" - if sys.platform != "win32": - return False - try: - fd = _win_open_confined(root_real, _listed_parts(path, base), _FILE_READ_ATTRIBUTES) - except OSError: - return False - try: - _handle_final_path(_os_handle(fd)) - except OSError as exc: - return getattr(exc, "winerror", None) == winerror - finally: - os.close(fd) - return False + text = f"the config file {name} could not be added to the backup: {exc.strerror}" + winerror = getattr(exc, "winerror", None) + if isinstance(winerror, int): + return OSError(exc.errno, text, None, winerror) + return OSError(exc.errno, text) def _tree_size(root: Path) -> int: diff --git a/messagefoundry/transports/file.py b/messagefoundry/transports/file.py index 7319ebd8b5..0d35638842 100644 --- a/messagefoundry/transports/file.py +++ b/messagefoundry/transports/file.py @@ -3226,7 +3226,12 @@ class _AttributeTag(ctypes.Structure): def _open_confined( - path: Path, directory: Path, root_real: Path, *, for_move: bool = False + path: Path, + directory: Path, + root_real: Path, + *, + for_move: bool = False, + unverified: list[OSError] | None = None, ) -> tuple[int, os.stat_result]: """Open ``path`` to read only if it is a regular file inside the watch root reached through no link (BACKLOG #2507). Returns the descriptor and its ``fstat``; the caller closes the descriptor. @@ -3241,11 +3246,18 @@ def _open_confined( junction below the root is followed, not even to be refused (BACKLOG #2535). The handle's final path, every link and junction resolved, must then still equal the root joined with the listed name. A volume that cannot report a normalized final path fails that check, which leaves the file - in place. + in place, unless the caller opts in through ``unverified``, below. ``for_move`` asks Windows for a handle that can also rename and delete the file, which the move and the delete then act on. POSIX ignores it: there they act relative to the parent's descriptor. + ``unverified``, where given, opts in to trusting a handle whose final path cannot be read (vault + BACKLOG #6573); the file connector never passes it. On Windows the root is then held and + refused if it names another path too, as each folder below it is (:func:`_win_hold_dirs`), and + when the query for the final path itself fails, after the regular-file check passed, the + descriptor is returned all the same and the query's error appended to ``unverified``. A final + path that is read and names another path is still refused. + Either way a link that stays inside the root is refused too. A hard link is not: see :func:`_pin_confined` for why.""" parts = _listed_parts(path, directory) @@ -3256,7 +3268,15 @@ def _open_confined( finally: os.close(parent) elif sys.platform == "win32": - fd = _win_open_confined(root_real, parts, _GENERIC_READ | (_DELETE if for_move else 0)) + access = _GENERIC_READ | (_DELETE if for_move else 0) + if unverified is None: + fd = _win_open_confined(root_real, parts, access) + else: + root_held = _win_hold_dirs(root_real, (), hold_root=True) + try: + fd = _win_open_confined(root_real, parts, access) + finally: + _win_release(root_held) else: # pragma: no cover - no supported platform lands here, and failing closed is the safe arm raise _Unconfined("this platform cannot confine a read to the watch root") try: @@ -3265,8 +3285,16 @@ def _open_confined( raise _Unconfined("not a regular file") if not _WALK_BY_DIR_FD: expected = os.path.normcase(_plain(str(root_real.joinpath(*parts)))) - if os.path.normcase(_plain(_final_path(fd))) != expected: - raise _Unconfined("reached through a link or a junction") + handle = _os_handle(fd) + try: + final = _handle_final_path(handle) + except OSError as exc: + if unverified is None: + raise + unverified.append(exc) + else: + if os.path.normcase(_plain(final)) != expected: + raise _Unconfined("reached through a link or a junction") except OSError: os.close(fd) raise @@ -3604,18 +3632,22 @@ def _win_open_confined(root_real: Path, parts: tuple[str, ...], access: int) -> _win_release(held) -def _win_hold_dirs(root: Path, dirs: tuple[str, ...]) -> list[int]: +def _win_hold_dirs(root: Path, dirs: tuple[str, ...], *, hold_root: bool = False) -> list[int]: """Windows: open each directory ``root/dirs...`` as itself, refuse one that is not a plain directory, and return their handles, held so that none can be renamed (BACKLOG #2535). The caller - passes them to :func:`_win_release`. + passes them to :func:`_win_release`. ``hold_root`` holds and checks ``root`` itself first, the + same way (vault BACKLOG #6573). The DR staging truncate fail-safe holds its directories with this too (BACKLOG #4992), so one Windows walk serves both modules rather than two that drift apart.""" + targets = [root] if hold_root else [] + where = root + for part in dirs: + where = where / part + targets.append(where) held: list[int] = [] try: - where = root - for part in dirs: - where = where / part + for where in targets: handle = _win_create( where, _FILE_LIST_DIRECTORY, @@ -3848,14 +3880,10 @@ def _open_no_link(name: str, flags: int, dir_fd: int) -> int: raise OSError(code, text) -def _final_path(fd: int) -> str: - """Windows: the final path of the file open on ``fd``, every link and junction resolved.""" - return _handle_final_path(_os_handle(fd)) - - def _handle_final_path(handle: int) -> str: """Windows: the final path of the object open on the OS ``handle``, every link and junction - resolved. The DR staging fail-safe reads its held directories' paths with this (BACKLOG #4992).""" + resolved. :func:`_open_confined` checks each file it opens with this, and the DR staging + fail-safe reads its held directories' paths with it (BACKLOG #4992).""" query = _kernel32().GetFinalPathNameByHandleW size = 512 while True: diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index 6d4e31fd62..b82fcdf248 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -715,11 +715,13 @@ async def test_add_config_dir_skips_edit_candidates_and_the_lock( vanished: list[Path] = [] - def open_confined(path: Path, base: Path, root_real: Path) -> tuple[int, os.stat_result]: + def open_confined( + path: Path, base: Path, root_real: Path, **kwargs: object + ) -> tuple[int, os.stat_result]: if live in path.parents: shutil.rmtree(live, ignore_errors=True) vanished.append(path) - return real_open(path, base, root_real) + return real_open(path, base, root_real, **kwargs) # type: ignore[arg-type] try: monkeypatch.setattr("messagefoundry.pipeline.dr_backup._open_confined", open_confined) @@ -1475,12 +1477,12 @@ async def test_a_file_swapped_for_a_folder_between_its_screen_and_its_open_is_pa os.unlink(probe) swapped: list[Path] = [] - def open_after_a_swap(path: Path, base: Path, root_real: Path): + def open_after_a_swap(path: Path, base: Path, root_real: Path, **kwargs: object): if path == checked and not swapped: os.replace(checked, tmp_path / "aside.toml") make_link(host, checked) swapped.append(checked) - return real_open(path, base, root_real) + return real_open(path, base, root_real, **kwargs) # type: ignore[arg-type] monkeypatch.setattr("messagefoundry.pipeline.dr_backup._open_confined", open_after_a_swap) result, names, tar_bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) @@ -1505,10 +1507,12 @@ async def test_a_config_file_that_still_reads_as_regular_but_will_not_open_fails _result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) assert "config/swapped.toml" in names # the control - def open_confined(path: Path, base: Path, root_real: Path) -> tuple[int, os.stat_result]: + def open_confined( + path: Path, base: Path, root_real: Path, **kwargs: object + ) -> tuple[int, os.stat_result]: if path.name == "swapped.toml": raise PermissionError(13, "Permission denied") - return real_open(path, base, root_real) + return real_open(path, base, root_real, **kwargs) # type: ignore[arg-type] monkeypatch.setattr("messagefoundry.pipeline.dr_backup._open_confined", open_confined) with pytest.raises(BackupError, match="swapped.toml"): @@ -1537,11 +1541,13 @@ def _fault_the_open_and_its_screen( key = os.path.normcase(os.fspath(checked)) faulted: list[Path] = [] - def open_confined(path: Path, base: Path, root_real: Path) -> tuple[int, os.stat_result]: + def open_confined( + path: Path, base: Path, root_real: Path, **kwargs: object + ) -> tuple[int, os.stat_result]: if path == checked: faulted.append(path) raise open_exc - return real_open(path, base, root_real) + return real_open(path, base, root_real, **kwargs) # type: ignore[arg-type] def lstat(path, *args, **kwargs): if ( @@ -1566,8 +1572,9 @@ async def test_a_config_file_on_an_unreachable_share_fails_the_backup( """A file the walk screened, whose confined open then fails because its share or network path cannot be reached (Windows ERROR_BAD_NETPATH or ERROR_BAD_NET_NAME, which Python maps to ENOENT), fails the backup, naming the file, as the add by name did before vault BACKLOG #6573. - It is not read as a file gone since the listing, though the screen after the open meets the - same fault. The control is a plain ENOENT at both, which is a file gone and is left out.""" + It is not read as a file gone since the listing, whether the screen after the open meets the + same fault or reads the name as gone: the open's own fault decides, before that screen. The + control is a plain ENOENT at both, which is a file gone and is left out.""" cfg, _host = _config_for_a_swap(tmp_path) checked = cfg / "swapped.toml" @@ -1581,10 +1588,13 @@ async def test_a_config_file_on_an_unreachable_share_fails_the_backup( monkeypatch.undo() share = _os_error(2, "The network path was not found", winerror) - faulted = _fault_the_open_and_its_screen(monkeypatch, checked, share, share) - with pytest.raises(BackupError, match="swapped.toml"): - await _pass_with_bytes(tmp_path, key_b64, cfg) - assert faulted == [checked], "the fault ran" + for arm, screen in (("same-fault", share), ("screen-reads-gone", gone)): + faulted = _fault_the_open_and_its_screen(monkeypatch, checked, share, screen) + (tmp_path / arm).mkdir() + with pytest.raises(BackupError, match="swapped.toml"): + await _pass_with_bytes(tmp_path / arm, key_b64, cfg) + assert faulted == [checked], f"the fault ran ({arm})" + monkeypatch.undo() @pytest.mark.parametrize( @@ -1596,49 +1606,124 @@ async def test_a_config_file_whose_screen_fails_after_a_failed_open_fails_the_ba """A file the walk screened, whose confined open then fails and whose ``lstat`` after it fails for a reason other than absence, such as EIO or a Windows share whose name was deleted, fails the backup, naming the file, as the add by name did before vault BACKLOG #6573. It is - not passed over.""" + not passed over. The control is the same failed open with a screen that reads the name as + gone, which leaves the file out and lets the backup succeed.""" cfg, _host = _config_for_a_swap(tmp_path) checked = cfg / "swapped.toml" - fault = _os_error(code, "I/O fault", winerror) + denied = _os_error(13, "Permission denied") + + (tmp_path / "control").mkdir() faulted = _fault_the_open_and_its_screen( - monkeypatch, checked, _os_error(13, "Permission denied"), fault + monkeypatch, checked, denied, _os_error(2, "No such file or directory") + ) + result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) + assert faulted == [checked], "the control's fault ran" + assert "config/swapped.toml" not in names # the control: a file gone is left out + assert result.config_skipped_files == () + monkeypatch.undo() + + faulted = _fault_the_open_and_its_screen( + monkeypatch, checked, denied, _os_error(code, "I/O fault", winerror) ) with pytest.raises(BackupError, match="swapped.toml"): await _pass_with_bytes(tmp_path, key_b64, cfg) assert faulted == [checked], "the fault ran" -@pytest.mark.skipif(sys.platform != "win32", reason="the final-path check is Windows-only") -async def test_a_config_file_whose_final_path_cannot_be_read_is_added_by_name( - tmp_path, key_b64, monkeypatch -) -> None: - """On Windows a file whose final path cannot be read with an error other than the ones that - say the volume does not do that, such as ERROR_PATH_NOT_FOUND on a volume mounted with no - drive letter, is added by its name, as it was before vault BACKLOG #6573, rather than failing - every backup of that config dir. The control is the same error from the confined open itself - with the final path readable, which still fails the backup, naming the file.""" - import messagefoundry.pipeline.dr_backup as dr_backup +def test_the_error_that_fails_the_backup_for_a_config_file_keeps_its_codes(tmp_path) -> None: + """The error that fails the backup for a config file names the file relative to the config + dir and keeps the errno and, on Windows, the Windows code of the error it replaces, so the + code is not lost to the operator (vault BACKLOG #6573).""" + from messagefoundry.pipeline.dr_backup import _config_file_error + + err = _config_file_error( + tmp_path / "sub" / "a.toml", tmp_path, _os_error(2, "The network path was not found", 53) + ) + assert err.errno == 2 + assert str(err.strerror) == ( + "the config file sub/a.toml could not be added to the backup: " + "The network path was not found" + ) + if sys.platform == "win32": + assert err.winerror == 53 + plain = _config_file_error(tmp_path / "a.toml", tmp_path, _os_error(5, "I/O fault")) + assert plain.errno == 5 and getattr(plain, "winerror", None) in (None, 0) + + +def _fail_the_final_path_of( + monkeypatch: pytest.MonkeyPatch, winerror: int, *checked: Path +) -> list[str]: + """Fail the Windows final-path query of a handle open on any of ``checked`` with ``winerror``, + and leave every other query alone. Returns the list each failed query appends to.""" import messagefoundry.transports.file as file_mod - cfg, _host = _config_for_a_swap(tmp_path) - checked = os.path.normcase(os.fspath((cfg / "swapped.toml").resolve())) + keys = {os.path.normcase(os.fspath(path.resolve())) for path in checked} real_final = file_mod._handle_final_path failed: list[str] = [] def final_path(handle: int) -> str: found = real_final(handle) - if os.path.normcase(file_mod._plain(found)) == checked: + if os.path.normcase(file_mod._plain(found)) in keys: failed.append(found) - raise _os_error(2, "The system cannot find the path specified", 3) + raise _os_error(22, "The volume does not do that", winerror) return found monkeypatch.setattr(file_mod, "_handle_final_path", final_path) - monkeypatch.setattr(dr_backup, "_handle_final_path", final_path) - result, names, tar_bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) - assert failed, "the final-path fault ran" + return failed + + +def _record_handles(monkeypatch: pytest.MonkeyPatch, checked: Path) -> list[io.IOBase]: + """Record the file object the walk wraps around each descriptor the confined open returns + for ``checked``, so a test can show each was closed.""" + import messagefoundry.pipeline.dr_backup as dr_backup + from messagefoundry.transports.file import _open_confined as real_open + + real_fdopen = os.fdopen + fds: list[int] = [] + handles: list[io.IOBase] = [] + + def open_confined( + path: Path, base: Path, root_real: Path, **kwargs: object + ) -> tuple[int, os.stat_result]: + fd, st = real_open(path, base, root_real, **kwargs) # type: ignore[arg-type] + if path == checked: + fds.append(fd) + return fd, st + + def fdopen(fd: int, *args: object, **kwargs: object) -> io.IOBase: + handle = real_fdopen(fd, *args, **kwargs) # type: ignore[call-overload] + if fd in fds: + handles.append(handle) + return handle + + monkeypatch.setattr(dr_backup, "_open_confined", open_confined) + monkeypatch.setattr(os, "fdopen", fdopen) + return handles + + +@pytest.mark.skipif(sys.platform != "win32", reason="the final-path check is Windows-only") +@pytest.mark.parametrize("winerror", [1, 50, 87, 3]) +async def test_a_config_file_whose_final_path_cannot_be_read_is_added_from_its_handle( + tmp_path, key_b64, monkeypatch, caplog, winerror +) -> None: + """On Windows a file the confined open opened and found regular, whose final path alone + cannot be read, is added from the handle that open returned, with its own bytes, and one + WARNING per pass counts it and says the residual (vault BACKLOG #6573). Before, such a file + was passed over on ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER, + which origin/main had bundled, and opened again by name on any other error. The descriptor + is closed.""" + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + (cfg / "other.toml").write_bytes(b"other") + failed = _fail_the_final_path_of(monkeypatch, winerror, checked, cfg / "other.toml") + handles = _record_handles(monkeypatch, checked) + with caplog.at_level(logging.WARNING, logger="messagefoundry.pipeline.dr_backup"): + result, names, tar_bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) + assert len(failed) == 2, "the final-path fault ran for both files" assert names == [ "config/feed.py", "config/keep/plain.txt", + "config/other.toml", "config/sub/secret.txt", "config/swapped.toml", ] @@ -1646,20 +1731,81 @@ def final_path(handle: int) -> str: member = tar.extractfile("config/swapped.toml") assert member is not None and member.read() == b"#" * 100 assert result.config_skipped_files == () + warned = [r.getMessage() for r in caplog.records if "could not report" in r.getMessage()] + assert len(warned) == 1, warned + assert "added 2 file(s)" in warned[0] and "other.toml, swapped.toml" in warned[0] + assert "above the config dir" in warned[0] + assert len(handles) == 1 and handles[0].closed + + +@pytest.mark.skipif(sys.platform != "win32", reason="the final-path check is Windows-only") +async def test_a_tar_failure_closes_the_handle_of_a_file_whose_final_path_cannot_be_read( + tmp_path, key_b64, monkeypatch +) -> None: + """A file added from its handle with its final-path check not run (vault BACKLOG #6573) has + that handle closed when the archive write fails, and the backup fails. The control is the + same pass with the write left alone, which records the same handle closed.""" + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + + (tmp_path / "control").mkdir() + _fail_the_final_path_of(monkeypatch, 50, checked) + handles = _record_handles(monkeypatch, checked) + await _pass_with_bytes(tmp_path / "control", key_b64, cfg) + assert len(handles) == 1 and handles[0].closed # the control monkeypatch.undo() - # The control: the open itself fails so, and the final path reads, so the backup fails. - real_open = file_mod._open_confined + _fail_the_final_path_of(monkeypatch, 50, checked) + handles = _record_handles(monkeypatch, checked) + real_addfile = tarfile.TarFile.addfile + refused: list[str] = [] - def open_confined(path: Path, base: Path, root_real: Path) -> tuple[int, os.stat_result]: - if path.name == "swapped.toml": - raise _os_error(2, "The system cannot find the path specified", 3) - return real_open(path, base, root_real) + def addfile(self: tarfile.TarFile, tarinfo: tarfile.TarInfo, *args: object, **kw: object): + if tarinfo.name == "config/swapped.toml": + refused.append(tarinfo.name) + raise OSError(28, "No space left on device") + return real_addfile(self, tarinfo, *args, **kw) # type: ignore[arg-type] - monkeypatch.setattr(dr_backup, "_open_confined", open_confined) + monkeypatch.setattr(tarfile.TarFile, "addfile", addfile) + with pytest.raises((BackupError, OSError)): + await _pass_with_bytes(tmp_path, key_b64, cfg) + assert refused == ["config/swapped.toml"], "the tar fault ran" + assert len(handles) == 1 and handles[0].closed + + +@pytest.mark.skipif(sys.platform != "win32", reason="the final-path check is Windows-only") +async def test_a_config_file_whose_final_path_names_another_path_is_still_passed_over( + tmp_path, key_b64, monkeypatch, caplog +) -> None: + """A final path that is read and names another path than the config dir joined with the + listed name is still a refusal on the backup's opted-in open (vault BACKLOG #6573): the file + is passed over and recorded, and nothing is said about a check that did not run. The control + is the same pass with the query left alone, which carries the file.""" + import messagefoundry.transports.file as file_mod + + cfg, host = _config_for_a_swap(tmp_path) (tmp_path / "control").mkdir() - with pytest.raises(BackupError, match="swapped.toml"): - await _pass_with_bytes(tmp_path / "control", key_b64, cfg) + _result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) + assert "config/swapped.toml" in names # the control + + key = os.path.normcase(os.fspath((cfg / "swapped.toml").resolve())) + real_final = file_mod._handle_final_path + moved: list[str] = [] + + def final_path(handle: int) -> str: + found = real_final(handle) + if os.path.normcase(file_mod._plain(found)) == key: + moved.append(found) + return "\\\\?\\" + os.fspath((host / "secret.txt").resolve()) + return found + + monkeypatch.setattr(file_mod, "_handle_final_path", final_path) + with caplog.at_level(logging.WARNING, logger="messagefoundry.pipeline.dr_backup"): + result, names, _bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) + assert moved, "the mismatch ran" + assert "config/swapped.toml" not in names + assert result.config_skipped_files == ("swapped.toml",) + assert not [r for r in caplog.records if "could not report" in r.getMessage()] @pytest.mark.parametrize( diff --git a/tests/test_file_open_confined_unverified.py b/tests/test_file_open_confined_unverified.py new file mode 100644 index 0000000000..8c39d0aef1 --- /dev/null +++ b/tests/test_file_open_confined_unverified.py @@ -0,0 +1,208 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""The confined open's opt-in for a handle whose Windows final path cannot be read (vault BACKLOG +#6573). + +The DR backup's config walk opts in: it adds such a file from the handle it opened, with the +root held as itself. The file connector does not: a read whose final path cannot be read still +fails and leaves the file in place. A final path that is read and names another path is refused +either way.""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + +import pytest + +from messagefoundry.config.models import ConnectorType, Source +from messagefoundry.transports import file as file_mod +from messagefoundry.transports.file import FileSource + +_WINDOWS_ONLY = pytest.mark.skipif( + sys.platform != "win32", reason="the final-path check is Windows-only" +) +_VOLUME_CODES = pytest.mark.parametrize("winerror", [1, 50, 87]) + + +def _fail_final_path(monkeypatch: pytest.MonkeyPatch, target: Path, winerror: int) -> list[str]: + """Fail the final-path query of a handle open on ``target`` with ``winerror``; leave every + other query alone. Returns the list each failed query appends to.""" + key = os.path.normcase(os.fspath(target.resolve())) + real = file_mod._handle_final_path + failed: list[str] = [] + + def final_path(handle: int) -> str: + found = real(handle) + if os.path.normcase(file_mod._plain(found)) == key: + failed.append(found) + raise OSError(22, "the volume does not do that", None, winerror) + return found + + monkeypatch.setattr(file_mod, "_handle_final_path", final_path) + return failed + + +def _inbox(tmp_path: Path) -> tuple[Path, Path]: + inbox = tmp_path / "in" + inbox.mkdir() + drop = inbox / "drop.hl7" + drop.write_bytes(b"MSH|^~\\&|LAB|FAC|EHR|FAC|20260930||ADT^A01|CTRL1|P|2.5\rPID|1||SYN01\r") + return inbox, drop + + +def test_the_opt_in_returns_the_file_and_records_nothing_when_the_check_ran( + tmp_path: Path, +) -> None: + """On any platform, an opted-in open of a plain file returns it and appends nothing, since the + final-path check ran (Windows) or there is none (POSIX).""" + inbox, drop = _inbox(tmp_path) + unverified: list[OSError] = [] + fd, st = file_mod._open_confined(drop, inbox, inbox.resolve(), unverified=unverified) + try: + assert os.read(fd, 3) == b"MSH" and st.st_size == drop.stat().st_size + finally: + os.close(fd) + assert unverified == [] + + +@_WINDOWS_ONLY +@_VOLUME_CODES +def test_the_opt_in_returns_the_open_file_when_only_its_final_path_query_fails( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, winerror: int +) -> None: + """With the opt-in, a file opened as itself and found regular, whose final-path query alone + fails, is returned open, and the query's error is appended for the caller.""" + inbox, drop = _inbox(tmp_path) + failed = _fail_final_path(monkeypatch, drop, winerror) + unverified: list[OSError] = [] + fd, _st = file_mod._open_confined(drop, inbox, inbox.resolve(), unverified=unverified) + try: + assert os.read(fd, 3) == b"MSH" + finally: + os.close(fd) + assert len(failed) == 1, "the fault ran" + assert [getattr(exc, "winerror", None) for exc in unverified] == [winerror] + + +@_WINDOWS_ONLY +@_VOLUME_CODES +async def test_the_file_connector_still_fails_a_read_whose_final_path_cannot_be_read( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, winerror: int +) -> None: + """Without the opt-in, which the file connector never passes, a final-path query that fails + still fails the read with that error, and a scan hands nothing on and leaves the file in + place. The control is the same scan with the query left alone, which hands the file on.""" + inbox, drop = _inbox(tmp_path) + failed = _fail_final_path(monkeypatch, drop, winerror) + with pytest.raises(OSError) as raised: + file_mod._read_confined(drop, inbox, inbox.resolve(), 4096) + assert getattr(raised.value, "winerror", None) == winerror + assert not isinstance(raised.value, file_mod._Unconfined) + + got: list[bytes] = [] + + async def handler(raw: bytes) -> str | None: + got.append(raw) + return None + + src = FileSource( + Source(type=ConnectorType.FILE, settings={"directory": str(inbox), "pattern": "*.hl7"}) + ) + src._prepare_subdirs() + src._handler = handler + await src._scan_once() # the settle poll records the stat + await src._scan_once() + assert len(failed) >= 2, "the fault ran on the read" + assert got == [], "a file whose final path could not be read was handed on" + assert drop.is_file(), "the file is left in place" + + monkeypatch.undo() # the control: a later scan, the query left alone, reads it + for _ in range(3): + await src._scan_once() + if got: + break + assert len(got) == 1 + + +@_WINDOWS_ONLY +@pytest.mark.parametrize("opted_in", [False, True], ids=["default", "opted-in"]) +def test_a_final_path_that_names_another_path_is_refused_either_way( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, opted_in: bool +) -> None: + """A final-path query that succeeds and names another path than the root joined with the + listed name is refused as reached through a link, with or without the opt-in, and nothing is + appended.""" + inbox, drop = _inbox(tmp_path) + elsewhere = tmp_path / "elsewhere.hl7" + elsewhere.write_bytes(b"x") + key = os.path.normcase(os.fspath(drop.resolve())) + real = file_mod._handle_final_path + + def final_path(handle: int) -> str: + found = real(handle) + if os.path.normcase(file_mod._plain(found)) == key: + return "\\\\?\\" + os.fspath(elsewhere.resolve()) + return found + + monkeypatch.setattr(file_mod, "_handle_final_path", final_path) + unverified: list[OSError] = [] + with pytest.raises(file_mod._Unconfined): + file_mod._open_confined( + drop, inbox, inbox.resolve(), unverified=unverified if opted_in else None + ) + assert unverified == [] + + +def _make_junction(target: Path, link: Path) -> None: + if sys.platform != "win32": + pytest.skip("an NTFS junction is a Windows feature") + import _winapi + + _winapi.CreateJunction(str(target), str(link)) + + +@_WINDOWS_ONLY +def test_the_opt_in_refuses_a_root_swapped_for_a_junction_the_final_path_would_have_caught( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """With the opt-in, the root itself is held and refused if it names another path, as each + folder below it is, so a root swapped for a junction after it was resolved is refused even + when the final-path query, which would have caught it, fails. The control is the same open + before the swap, which returns the root's own file.""" + root = tmp_path / "config" + root.mkdir() + (root / "a.toml").write_bytes(b"own") + root_real = root.resolve() + host = tmp_path / "host" + host.mkdir() + (host / "a.toml").write_bytes(b"HOST-SECRET") + + real = file_mod._handle_final_path + + def final_path(handle: int) -> str: + found = real(handle) + if found.lower().endswith("a.toml"): + raise OSError(22, "the volume does not do that", None, 50) + return found + + monkeypatch.setattr(file_mod, "_handle_final_path", final_path) + fd, _st = file_mod._open_confined(root / "a.toml", root, root_real, unverified=[]) + try: + assert os.read(fd, 16) == b"own" # the control + finally: + os.close(fd) + + root.rename(tmp_path / "config-aside") + _make_junction(host, root) + unverified: list[OSError] = [] + try: + with pytest.raises(file_mod._Unconfined): + fd, _st = file_mod._open_confined( + root / "a.toml", root, root_real, unverified=unverified + ) + os.close(fd) + finally: + os.rmdir(root) # the junction, not its target + assert unverified == [] From a3754205bae84f2c82089ccf6af4fce389b65be8 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:42:23 -0600 Subject: [PATCH 09/49] dr_backup: the config walk's reader closes a descriptor once, and the WARNING names every code (BACKLOG #6573) Repair round 1 of the code-review on 50661614eca. - _open_config_file returns the descriptor with the final-path error, else None, from a list of its own, so the walk keeps no OSError per file and the WARNING names every distinct code seen, not only the first. - _reader_over builds the reader in two steps, so a failure closes the descriptor once: the earlier guard around os.fdopen could close it a second time after io.open had closed it. - the comment on an unresolvable share root no longer says its files are always passed over. - tests: the reader closes its descriptor once when either layer fails; the WARNING names the code. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 87 +++++++++++++++++----------- tests/test_backup_runner.py | 48 ++++++++++++--- 2 files changed, 94 insertions(+), 41 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index ba0b100e14..bdd3d464c4 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -1469,16 +1469,16 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ # count is the regular files it added. regular_names: set[str] = set() # Resolved once: every file is opened down from it, never through a link below it. A - # share that cannot resolve leaves the path as given, which on Windows fails the final-path - # compare, so its files are passed over rather than the store backup lost. + # share that cannot resolve leaves the path as given, so on Windows its files' final + # paths, where they can be read, do not match it and the files are passed over. try: root_real = base.resolve() except OSError: root_real = base.absolute() - # One entry per file added although Windows could not report its final path, so the check - # that it was reached through no link did not run (vault BACKLOG #6573). - unverified: list[OSError] = [] + # The files added although Windows could not report their final paths, so the check that + # each was reached through no link did not run (vault BACKLOG #6573), and the codes seen. unverified_names: list[str] = [] + unverified_codes: set[str] = set() # Sorted whole, as the earlier `sorted(rglob)` was, so the member order is unchanged. for path in sorted(found): rel = path.relative_to(base) @@ -1486,22 +1486,18 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ continue if tar.name is not None and os.path.abspath(path) == tar.name: continue # the archive being written, which tar.add skipped too - unverified_before = len(unverified) - opened = _open_config_file(path, base, root_real, unverified) - if opened == "gone": - # Gone since the listing, such as an editor's save probe: no longer config. - continue - if opened == "passed-over": - passed_over.add(rel.as_posix()) + opened = _open_config_file(path, base, root_real) + if isinstance(opened, str): + # "gone" is gone since the listing, such as an editor's save probe: no longer + # config. + if opened == "passed-over": + passed_over.add(rel.as_posix()) continue - if len(unverified) > unverified_before: + fd, unread = opened + if unread is not None: unverified_names.append(rel.as_posix()) - try: - handle = os.fdopen(opened, "rb") - except BaseException: - os.close(opened) - raise - with handle: + unverified_codes.add(_error_code(unread)) + with _reader_over(fd) as handle: # The member is described and filled from the handle opened above, never by name # again, so a name swapped for a link after that open adds nothing behind it. info = tar.gettarinfo(arcname=f"{_CONFIG_PREFIX}{rel.as_posix()}", fileobj=handle) @@ -1519,13 +1515,13 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ if unverified_names: log.warning( "DR backup: the config bundle of %s added %d file(s) whose final path Windows " - "could not report (first: %s), so the check that each was reached through no link " - "did not run for them. The config dir and each folder below it were held as " + "could not report (%s), so the check that each was reached through no link did " + "not run for them. The config dir and each folder below it were held as " "themselves, but a folder above the config dir swapped for a link after the backup " "resolved the dir is not detected. First %d by name: %s", base, len(unverified_names), - safe_exc(unverified[0]), + ", ".join(sorted(unverified_codes)), min(len(unverified_names), _MAX_SKIPPED_RECORDED), scrub_log_argument(", ".join(unverified_names[:_MAX_SKIPPED_RECORDED])), ) @@ -3758,19 +3754,19 @@ def _stat_names_another_path(st: os.stat_result) -> bool: def _open_config_file( - path: Path, base: Path, root_real: Path, unverified: list[OSError] -) -> int | Literal["gone", "passed-over"]: + path: Path, base: Path, root_real: Path +) -> tuple[int, OSError | None] | Literal["gone", "passed-over"]: """Open the config file ``path``, listed under ``base``, to read, through no link below - ``base`` (vault BACKLOG #6573), and return its descriptor, which the caller closes. - ``root_real`` is ``base`` resolved. ``"gone"`` means the file is gone since it was listed, and - ``"passed-over"`` that the walk passes it over. + ``base`` (vault BACKLOG #6573), and return its descriptor, which the caller closes, with the + error of a final-path query that failed, else None. ``root_real`` is ``base`` resolved. + ``"gone"`` means the file is gone since it was listed, and ``"passed-over"`` that the walk + passes it over. The open is the file connector's confined open - (:func:`~messagefoundry.transports.file._open_confined`), opted in through ``unverified`` to - return a handle whose final path Windows cannot report, with that query's error appended to - ``unverified``. Which outcome each fault gets, and what a link swapped in still reaches, is - stated once, in the ``include_config`` row of ``docs/CONFIGURATION.md``. A failure raised names - the file relative to ``base``, which is operator configuration.""" + (:func:`~messagefoundry.transports.file._open_confined`), opted in to return a handle whose + final path Windows cannot report. Which outcome each fault gets, and what a link swapped in + still reaches, is stated once, in the ``include_config`` row of ``docs/CONFIGURATION.md``. A + failure raised names the file relative to ``base``, which is operator configuration.""" try: st = path.lstat() except FileNotFoundError: @@ -3779,6 +3775,7 @@ def _open_config_file( return "passed-over" if not stat.S_ISREG(st.st_mode) or _stat_names_another_path(st): return "passed-over" + unverified: list[OSError] = [] try: fd, _st = _open_confined(path, base, root_real, unverified=unverified) except (_Unconfined, _Replaced): @@ -3802,7 +3799,31 @@ def _open_config_file( if getattr(exc, "winerror", None) in _WIN_UNSUPPORTED: return "passed-over" # the volume does not do what a step of the open asked raise _config_file_error(path, base, exc) from exc - return fd + return fd, unverified[0] if unverified else None + + +def _error_code(exc: OSError) -> str: + """``exc``'s Windows code, else its errno, else its class name, for a log line.""" + winerror = getattr(exc, "winerror", None) + if isinstance(winerror, int): + return f"WinError {winerror}" + return f"errno {exc.errno}" if exc.errno is not None else shown_class_name(exc) + + +def _reader_over(fd: int) -> io.BufferedReader: + """A buffered reader that owns ``fd`` and closes it. ``fd`` is closed here if the reader + cannot be built, and never twice: ``FileIO`` does not close a descriptor it was handed when + it fails, and once it is built the reader is closed through it.""" + try: + raw = io.FileIO(fd, "rb") + except BaseException: + os.close(fd) + raise + try: + return io.BufferedReader(raw) + except BaseException: + raw.close() + raise def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index b82fcdf248..b666773cb4 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1650,6 +1650,37 @@ def test_the_error_that_fails_the_backup_for_a_config_file_keeps_its_codes(tmp_p assert plain.errno == 5 and getattr(plain, "winerror", None) in (None, 0) +@pytest.mark.parametrize("fails", ["FileIO", "BufferedReader"]) +def test_the_reader_over_a_config_descriptor_closes_it_once_when_it_cannot_be_built( + tmp_path, monkeypatch, fails +) -> None: + """The reader the config walk builds over a descriptor closes that descriptor when either + layer cannot be built, and closes it once: the descriptor is closed afterwards, and the + failure raised is the build's own, not a second close's EBADF (vault BACKLOG #6573). The + control is the same build left alone, which reads the file and leaves it open until closed.""" + from messagefoundry.pipeline import dr_backup + + target = tmp_path / "a.toml" + target.write_bytes(b"own") + fd = os.open(target, os.O_RDONLY | getattr(os, "O_BINARY", 0)) + with dr_backup._reader_over(fd) as handle: # the control + assert handle.read() == b"own" + with pytest.raises(OSError): + os.fstat(fd) + + fd = os.open(target, os.O_RDONLY | getattr(os, "O_BINARY", 0)) + + def refuse(*_args: object, **_kwargs: object) -> None: + raise MemoryError("refused by the test") + + monkeypatch.setattr(io, fails, refuse) + with pytest.raises(MemoryError, match="refused by the test"): + dr_backup._reader_over(fd) + monkeypatch.undo() + with pytest.raises(OSError): + os.fstat(fd) + + def _fail_the_final_path_of( monkeypatch: pytest.MonkeyPatch, winerror: int, *checked: Path ) -> list[str]: @@ -1672,15 +1703,15 @@ def final_path(handle: int) -> str: return failed -def _record_handles(monkeypatch: pytest.MonkeyPatch, checked: Path) -> list[io.IOBase]: - """Record the file object the walk wraps around each descriptor the confined open returns - for ``checked``, so a test can show each was closed.""" +def _record_handles(monkeypatch: pytest.MonkeyPatch, checked: Path) -> list[io.BufferedReader]: + """Record the reader the walk builds over each descriptor the confined open returns for + ``checked``, so a test can show each was closed.""" import messagefoundry.pipeline.dr_backup as dr_backup from messagefoundry.transports.file import _open_confined as real_open - real_fdopen = os.fdopen + real_reader = dr_backup._reader_over fds: list[int] = [] - handles: list[io.IOBase] = [] + handles: list[io.BufferedReader] = [] def open_confined( path: Path, base: Path, root_real: Path, **kwargs: object @@ -1690,14 +1721,14 @@ def open_confined( fds.append(fd) return fd, st - def fdopen(fd: int, *args: object, **kwargs: object) -> io.IOBase: - handle = real_fdopen(fd, *args, **kwargs) # type: ignore[call-overload] + def reader_over(fd: int) -> io.BufferedReader: + handle = real_reader(fd) if fd in fds: handles.append(handle) return handle monkeypatch.setattr(dr_backup, "_open_confined", open_confined) - monkeypatch.setattr(os, "fdopen", fdopen) + monkeypatch.setattr(dr_backup, "_reader_over", reader_over) return handles @@ -1735,6 +1766,7 @@ async def test_a_config_file_whose_final_path_cannot_be_read_is_added_from_its_h assert len(warned) == 1, warned assert "added 2 file(s)" in warned[0] and "other.toml, swapped.toml" in warned[0] assert "above the config dir" in warned[0] + assert f"WinError {winerror}" in warned[0] assert len(handles) == 1 and handles[0].closed From 1eebfa06e2c8037d1ab992e627f1daa91ba44c7c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:43:32 -0600 Subject: [PATCH 10/49] docs: the include_config row says a file whose final path Windows cannot report is added from its handle (BACKLOG #6573) The by-name add is gone, so the row drops it. It now says, once: - on Windows a file whose final-path query fails is added from its handle with that check not run, and one WARNING per pass counts and names such files and gives the codes; a final path read that names another path still passes the file over; - the residual: a folder above the config dir swapped for a link after the backup resolved the dir is not detected, nor on POSIX the config dir itself; - a cloud placeholder is opened by name at least three times, not "a second time"; - the failure rule's exceptions are "at least these cases", and an open that fails with ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER passes the file over. Proposed PR title: DR config walk adds a file whose Windows final path cannot be read from its handle, and the File connector still refuses it (BACKLOG #6573) Proposed vault banner: BUILT on engine branch b20053-6573c, stacked on b20053-6573b: the config walk adds each file from a handle opened through no link; a Windows final-path query failure adds the file from that handle with one WARNING, the root held as itself; the File connector's default is unchanged. Residual stated in the include_config row: a folder above the config dir swapped after resolve (and on POSIX the dir itself) is not detected. Owed: see the PR's open findings. Verified-by: none --- docs/CONFIGURATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 652d55ace9..0515b88523 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, except a file it adds by its name as stated below, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573). A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING, and the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened a second time by name, which can follow a link swapped in between, even to a UNC path, and so reach the host it names before the engine refuses what it reached. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows an `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, as from a volume that cannot report a file's final path, passes the file over; and a file whose final path alone cannot be read with any other error, as on a volume mounted with no drive letter, is added by its name, which follows a link swapped in. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573). A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space; and a folder above the config dir swapped for a link after the backup resolved the config dir is not detected, nor on POSIX the config dir itself swapped so, and the walk then reads what the link leads to. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name at least three times: by the walk's check, by the open as itself, and again through the placeholder's own filter after that open. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails, as on a volume that cannot report one, the file is added from its handle without that check, and one WARNING per pass counts such files, names at most the first 1000 of them and gives each Windows error code seen. The config dir itself and each folder below it are still held and refused if they are a link while the file is opened, so the residual that check would have caught is the folder above the config dir named above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows an open that fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which say the volume does not do what a step of the open asked, passes the file over. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | From 3469af828055f7cfd07411e281386079f94a2ec3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:59:38 -0600 Subject: [PATCH 11/49] dr_backup: a read or write that fails on a config file's handle names the file (BACKLOG #6573) Repair round 2 of the code-review, on 1eebfa06e2c. - the member's describe and add from the handle are wrapped, so a read that fails once the file is open (a byte-range lock, a file truncated under tar) or a tar write fault fails the backup naming the file, as the include_config row says; _config_file_error falls back to the error's text where it has no strerror. - tests: the tar failure test asks for the file name; the reader test tells a closed descriptor from a number another thread reused. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 35 +++++++++++++++++----------- tests/test_backup_runner.py | 19 +++++++++++---- 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index bdd3d464c4..5614a08f17 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -1499,19 +1499,25 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ unverified_codes.add(_error_code(unread)) with _reader_over(fd) as handle: # The member is described and filled from the handle opened above, never by name - # again, so a name swapped for a link after that open adds nothing behind it. - info = tar.gettarinfo(arcname=f"{_CONFIG_PREFIX}{rel.as_posix()}", fileobj=handle) - # A second name of a file this walk already added is carried too, so it is not - # passed over: tar stores it as a link member naming that one, and a restore - # writes it as a copy of that file's bytes (`_extract_config_members`) (vault - # BACKLOG #5233). - if info.isreg(): - tar.addfile(info, handle) - regular_names.add(info.name) - elif info.islnk() and info.linkname in regular_names: - tar.addfile(info) - else: - passed_over.add(rel.as_posix()) + # again, so a name swapped for a link after that open adds nothing behind it. A + # read or write that fails here fails the backup naming the file. + try: + info = tar.gettarinfo( + arcname=f"{_CONFIG_PREFIX}{rel.as_posix()}", fileobj=handle + ) + # A second name of a file this walk already added is carried too, so it is + # not passed over: tar stores it as a link member naming that one, and a + # restore writes it as a copy of that file's bytes + # (`_extract_config_members`) (vault BACKLOG #5233). + if info.isreg(): + tar.addfile(info, handle) + regular_names.add(info.name) + elif info.islnk() and info.linkname in regular_names: + tar.addfile(info) + else: + passed_over.add(rel.as_posix()) + except OSError as exc: + raise _config_file_error(path, base, exc) from exc if unverified_names: log.warning( "DR backup: the config bundle of %s added %d file(s) whose final path Windows " @@ -3830,7 +3836,8 @@ def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: """The error that fails the backup for the config file ``path``, naming it relative to ``base`` and keeping ``exc``'s errno, its Windows code where it has one, and its text.""" name = scrub_log_argument(path.relative_to(base).as_posix()) - text = f"the config file {name} could not be added to the backup: {exc.strerror}" + reason = exc.strerror if exc.strerror is not None else str(exc) + text = f"the config file {name} could not be added to the backup: {reason}" winerror = getattr(exc, "winerror", None) if isinstance(winerror, int): return OSError(exc.errno, text, None, winerror) diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index b666773cb4..28aa7fc5a6 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1662,11 +1662,21 @@ def test_the_reader_over_a_config_descriptor_closes_it_once_when_it_cannot_be_bu target = tmp_path / "a.toml" target.write_bytes(b"own") + mine = (target.stat().st_dev, target.stat().st_ino) + + def closed(fd: int) -> bool: + # Another thread may have reused the number since; it then names another file. + try: + st = os.fstat(fd) + except OSError: + return True + return (st.st_dev, st.st_ino) != mine + fd = os.open(target, os.O_RDONLY | getattr(os, "O_BINARY", 0)) with dr_backup._reader_over(fd) as handle: # the control assert handle.read() == b"own" - with pytest.raises(OSError): - os.fstat(fd) + assert not closed(fd) + assert closed(fd) fd = os.open(target, os.O_RDONLY | getattr(os, "O_BINARY", 0)) @@ -1677,8 +1687,7 @@ def refuse(*_args: object, **_kwargs: object) -> None: with pytest.raises(MemoryError, match="refused by the test"): dr_backup._reader_over(fd) monkeypatch.undo() - with pytest.raises(OSError): - os.fstat(fd) + assert closed(fd) def _fail_the_final_path_of( @@ -1799,7 +1808,7 @@ def addfile(self: tarfile.TarFile, tarinfo: tarfile.TarInfo, *args: object, **kw return real_addfile(self, tarinfo, *args, **kw) # type: ignore[arg-type] monkeypatch.setattr(tarfile.TarFile, "addfile", addfile) - with pytest.raises((BackupError, OSError)): + with pytest.raises(BackupError, match="swapped.toml"): await _pass_with_bytes(tmp_path, key_b64, cfg) assert refused == ["config/swapped.toml"], "the tar fault ran" assert len(handles) == 1 and handles[0].closed From a9dbd4d33c9667cbd674de5040282d2efb1ed067 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:00:31 -0600 Subject: [PATCH 12/49] docs: the include_config row places the ancestor residual by platform (BACKLOG #6573) Repair round 2 of the code-review, on 1eebfa06e2c. - The ancestor swap leaves the "POSIX and Windows alike" list: on POSIX a folder above the config dir, or the dir itself, swapped after resolve is not detected; on Windows only for a file whose final path cannot be read. - A cloud placeholder is "opened by name more than once", the last time through its filter, with no closed-looking list of the opens. - The root hold is stated as the backup walk's, not as existing behaviour of every confined open. Proposed PR title: DR config walk adds a file whose Windows final path cannot be read from its handle, and the File connector still refuses it (BACKLOG #6573) Proposed vault banner: BUILT on engine branch b20053-6573c, stacked on b20053-6573b: the config walk adds each file from a handle opened through no link; a Windows final-path query failure adds the file from that handle with one WARNING, the root held as itself; the File connector's default is unchanged. Residual stated in the include_config row: a folder above the config dir swapped after resolve (and on POSIX the dir itself) is not detected. Owed: see the PR's open findings. Verified-by: none --- docs/CONFIGURATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 0515b88523..5d47ae1228 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573). A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space; and a folder above the config dir swapped for a link after the backup resolved the config dir is not detected, nor on POSIX the config dir itself swapped so, and the walk then reads what the link leads to. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name at least three times: by the walk's check, by the open as itself, and again through the placeholder's own filter after that open. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails, as on a volume that cannot report one, the file is added from its handle without that check, and one WARNING per pass counts such files, names at most the first 1000 of them and gives each Windows error code seen. The config dir itself and each folder below it are still held and refused if they are a link while the file is opened, so the residual that check would have caught is the folder above the config dir named above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows an open that fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which say the volume does not do what a step of the open asked, passes the file over. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573). A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file whose final path cannot be read, as below. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails, as on a volume that cannot report one, the file is added from its handle without that check, and one WARNING per pass counts such files, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened, so the residual that check would have caught is a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows an open that fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which say the volume does not do what a step of the open asked, passes the file over. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | From df7a6a7800c71287d848898585bb1a56f5a5823a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:50:54 -0600 Subject: [PATCH 13/49] dr_backup: the config walk re-checks held folders after the open (BACKLOG #6573) On the backup's opted-in confined open, each held folder, the root included, is checked again by its handle once the file is open and before release, and the file is refused if one now names another path. The file connector's default open is unchanged. A final-path query is trusted only when it fails with WinError 1, 50 or 87; any other code fails the backup, naming the file. An open step failing with one of those codes opens the file by name only on a volume that reports no reparse points; otherwise the backup fails, naming the file, cause and remedy. A config dir held open for delete by another process is named as the config dir. Tests match readers by path, and a WinError 3 open-step control is restored; the census grades the new open, and the followers lock test faults the walk's own open. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 121 +++++++++-- messagefoundry/transports/file.py | 117 ++++++++++- tests/test_backup_runner.py | 180 +++++++++++++++-- tests/test_file_open_confined_unverified.py | 212 ++++++++++++++++++++ tests/test_file_path_join_census.py | 3 + tests/test_running_config_dir_followers.py | 21 +- 6 files changed, 605 insertions(+), 49 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 5614a08f17..d3714554e1 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -109,6 +109,7 @@ from messagefoundry.store.schema_verify import SchemaMismatchError, is_schema_step_error from messagefoundry.terminal_text import escape_for_terminal from messagefoundry.transports.file import ( + _FILE_SUPPORTS_REPARSE_POINTS, _FLAG_BACKUP_SEMANTICS, _FLAG_OPEN_REPARSE_POINT, _NAME_SURROGATE, @@ -121,12 +122,14 @@ _open_confined, _os_handle, _Replaced, + _RootUnheld, _Unconfined, _win_create, _win_hold_dirs, _win_lstat, _win_open_file, _win_release, + _win_volume_flags, ) __all__ = [ @@ -1475,9 +1478,12 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ root_real = base.resolve() except OSError: root_real = base.absolute() - # The files added although Windows could not report their final paths, so the check that - # each was reached through no link did not run (vault BACKLOG #6573), and the codes seen. + # The files added without the check that each was reached through no link (vault BACKLOG + # #6573): Windows could not report the final path, or the volume reports it holds no + # links and the file was opened by name. Then how many were opened by name, and the + # codes seen. unverified_names: list[str] = [] + by_name_count = 0 unverified_codes: set[str] = set() # Sorted whole, as the earlier `sorted(rglob)` was, so the member order is unchanged. for path in sorted(found): @@ -1493,10 +1499,11 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ if opened == "passed-over": passed_over.add(rel.as_posix()) continue - fd, unread = opened - if unread is not None: + fd, unchecked = opened + if unchecked is not None: unverified_names.append(rel.as_posix()) - unverified_codes.add(_error_code(unread)) + by_name_count += unchecked.by_name + unverified_codes.add(_error_code(unchecked.error)) with _reader_over(fd) as handle: # The member is described and filled from the handle opened above, never by name # again, so a name swapped for a link after that open adds nothing behind it. A @@ -1520,13 +1527,18 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ raise _config_file_error(path, base, exc) from exc if unverified_names: log.warning( - "DR backup: the config bundle of %s added %d file(s) whose final path Windows " - "could not report (%s), so the check that each was reached through no link did " - "not run for them. The config dir and each folder below it were held as " - "themselves, but a folder above the config dir swapped for a link after the backup " - "resolved the dir is not detected. First %d by name: %s", + "DR backup: the config bundle of %s added %d file(s) without the check that each " + "was reached through no link: %d whose final path Windows could not report, and " + "%d opened by name because a step of the confined open is unsupported on a volume " + "that reports it holds no reparse points (%s). At least these go undetected for " + "them: a folder above the config dir swapped for a link after the backup resolved " + "the dir; a held folder swapped for a link and back between a file's open and the " + "re-check of the held folders, which sees one instant; and a link on a volume that " + "reports its reparse-point support falsely. First %d by name: %s", base, len(unverified_names), + len(unverified_names) - by_name_count, + by_name_count, ", ".join(sorted(unverified_codes)), min(len(unverified_names), _MAX_SKIPPED_RECORDED), scrub_log_argument(", ".join(unverified_names[:_MAX_SKIPPED_RECORDED])), @@ -3759,20 +3771,31 @@ def _stat_names_another_path(st: os.stat_result) -> bool: ) +class _Unchecked(NamedTuple): + """Why a config file was added without the check that it was reached through no link (vault + BACKLOG #6573): ``by_name`` is true when it was opened by name on a volume that reports it + holds no reparse points, false when Windows could not report its final path; ``error`` is the + failure that left the check unrun.""" + + by_name: bool + error: OSError + + def _open_config_file( path: Path, base: Path, root_real: Path -) -> tuple[int, OSError | None] | Literal["gone", "passed-over"]: +) -> tuple[int, _Unchecked | None] | Literal["gone", "passed-over"]: """Open the config file ``path``, listed under ``base``, to read, through no link below - ``base`` (vault BACKLOG #6573), and return its descriptor, which the caller closes, with the - error of a final-path query that failed, else None. ``root_real`` is ``base`` resolved. - ``"gone"`` means the file is gone since it was listed, and ``"passed-over"`` that the walk - passes it over. + ``base`` (vault BACKLOG #6573), and return its descriptor, which the caller closes, with why + the check that it was reached through no link did not run, else None. ``root_real`` is + ``base`` resolved. ``"gone"`` means the file is gone since it was listed, and + ``"passed-over"`` that the walk passes it over. The open is the file connector's confined open (:func:`~messagefoundry.transports.file._open_confined`), opted in to return a handle whose final path Windows cannot report. Which outcome each fault gets, and what a link swapped in still reaches, is stated once, in the ``include_config`` row of ``docs/CONFIGURATION.md``. A - failure raised names the file relative to ``base``, which is operator configuration.""" + failure raised names the file relative to ``base``, which is operator configuration, or + ``base`` itself when the config dir could not be held.""" try: st = path.lstat() except FileNotFoundError: @@ -3786,6 +3809,11 @@ def _open_config_file( fd, _st = _open_confined(path, base, root_real, unverified=unverified) except (_Unconfined, _Replaced): return "passed-over" + except _RootUnheld as exc: + if is_absent(exc.error): + return "gone" # the config dir is gone since the listing, so this file is too + # Another process holding the config dir open for delete, say: the fault is the dir's. + raise _config_dir_error(base, exc) from exc except OSError as exc: if isinstance(exc, FileNotFoundError) and not is_absent(exc): # A share or network path that cannot be reached, which Windows maps to ENOENT: the @@ -3803,9 +3831,42 @@ def _open_config_file( if not stat.S_ISREG(again.st_mode) or _stat_names_another_path(again): return "passed-over" if getattr(exc, "winerror", None) in _WIN_UNSUPPORTED: - return "passed-over" # the volume does not do what a step of the open asked + # The volume does not do what a step of the open asked. + return _open_where_no_link_can_be(path, base, root_real, exc) raise _config_file_error(path, base, exc) from exc - return fd, unverified[0] if unverified else None + return fd, _Unchecked(False, unverified[0]) if unverified else None + + +def _open_where_no_link_can_be( + path: Path, base: Path, root_real: Path, exc: OSError +) -> tuple[int, _Unchecked] | Literal["gone"]: + """The config file ``path``, whose confined open failed with ``exc``, a code that says the + volume does not do what a step of the open asked, opened by name as it was before vault + BACKLOG #6573, but only where the config dir's volume reports it holds no reparse points, so + no link can be there to follow. A volume that reports it does, or whose answer cannot be read, + fails the backup, naming the file, the cause and the remedy. The error keeps ``exc``'s codes, + and its text is kept short, because an alert and the audit row cut it at 200 characters.""" + remedy = "use local NTFS or ReFS or include_config = false" + try: + flags = _win_volume_flags(root_real) + except OSError as query_exc: + raise _config_file_error( + path, + base, + exc, + f"volume's link support unreadable ({_error_code(query_exc)}); {remedy}", + ) from query_exc + if flags & _FILE_SUPPORTS_REPARSE_POINTS: + raise _config_file_error( + path, base, exc, f"volume can hold links but refused a no-link open; {remedy}" + ) from exc + try: + fd = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0)) + except OSError as open_exc: + if is_absent(open_exc): + return "gone" + raise _config_file_error(path, base, open_exc) from open_exc + return fd, _Unchecked(True, exc) def _error_code(exc: OSError) -> str: @@ -3832,12 +3893,28 @@ def _reader_over(fd: int) -> io.BufferedReader: raise -def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: +def _config_file_error(path: Path, base: Path, exc: OSError, reason: str | None = None) -> OSError: """The error that fails the backup for the config file ``path``, naming it relative to - ``base`` and keeping ``exc``'s errno, its Windows code where it has one, and its text.""" + ``base`` and keeping ``exc``'s errno, its Windows code where it has one, and ``reason``, + else its text.""" name = scrub_log_argument(path.relative_to(base).as_posix()) - reason = exc.strerror if exc.strerror is not None else str(exc) - text = f"the config file {name} could not be added to the backup: {reason}" + return _error_like(exc, f"the config file {name} could not be added to the backup", reason) + + +def _config_dir_error(base: Path, exc: OSError) -> OSError: + """The error that fails the backup when the config dir ``base`` itself could not be held as + itself (vault BACKLOG #6573), naming the dir rather than a file under it, and keeping + ``exc``'s codes and text.""" + what = f"the config dir {scrub_log_argument(str(base))} could not be held for the backup" + return _error_like(exc, what, None) + + +def _error_like(exc: OSError, what: str, reason: str | None) -> OSError: + """An ``OSError`` reading ``what: reason``, ``reason`` defaulting to ``exc``'s text, with + ``exc``'s errno and its Windows code where it has one.""" + if reason is None: + reason = exc.strerror if exc.strerror is not None else str(exc) + text = f"{what}: {reason}" winerror = getattr(exc, "winerror", None) if isinstance(winerror, int): return OSError(exc.errno, text, None, winerror) diff --git a/messagefoundry/transports/file.py b/messagefoundry/transports/file.py index 0d35638842..c27530e25a 100644 --- a/messagefoundry/transports/file.py +++ b/messagefoundry/transports/file.py @@ -3148,6 +3148,26 @@ class _Replaced(OSError): for the same reason as :class:`_Unconfined`, and its message never carries a file name.""" +class _RootUnheld(OSError): + """The confined open, opted in through ``unverified``, could not hold the root as itself for a + reason other than finding it a link (vault BACKLOG #6573), such as another process holding the + root open for delete. It keeps the hold's errno, Windows code and text, and the hold's own error + as ``error``, so a caller can name the root rather than the file. Its message never carries a + path.""" + + error: OSError + + @classmethod + def from_error(cls, exc: OSError) -> _RootUnheld: + winerror = getattr(exc, "winerror", None) + if isinstance(winerror, int): + made = cls(exc.errno, exc.strerror, None, winerror) + else: + made = cls(exc.errno, exc.strerror) + made.error = exc + return made + + class _OverCap(Exception): """The file read from the handle is larger than ``max_file_bytes`` (BACKLOG #2507). Its message is a size (" bytes" or "more than bytes"), never a name. ``file_id`` is the identity of the @@ -3253,10 +3273,16 @@ def _open_confined( ``unverified``, where given, opts in to trusting a handle whose final path cannot be read (vault BACKLOG #6573); the file connector never passes it. On Windows the root is then held and - refused if it names another path too, as each folder below it is (:func:`_win_hold_dirs`), and - when the query for the final path itself fails, after the regular-file check passed, the - descriptor is returned all the same and the query's error appended to ``unverified``. A final - path that is read and names another path is still refused. + refused if it names another path too, as each folder below it is (:func:`_win_hold_dirs`); a + root that cannot be held for any other reason raises :class:`_RootUnheld`. Once the file is + open, each held folder, the root included, is checked again by its handle before it is + released, and the file is refused if any of them now names another path + (:func:`_win_open_confined_rechecked`). That re-check sees one instant, so a folder swapped for + a link and back between the open and the re-check is not detected, nor is a folder above the + root. When the query for the final path then fails with a code in ``_WIN_UNSUPPORTED``, after + the regular-file check passed, the descriptor is returned all the same and the query's error + appended to ``unverified``; any other failure of that query is raised. A final path that is + read and names another path is still refused. Either way a link that stays inside the root is refused too. A hard link is not: see :func:`_pin_confined` for why.""" @@ -3272,9 +3298,19 @@ def _open_confined( if unverified is None: fd = _win_open_confined(root_real, parts, access) else: - root_held = _win_hold_dirs(root_real, (), hold_root=True) try: - fd = _win_open_confined(root_real, parts, access) + root_held = _win_hold_dirs(root_real, (), hold_root=True) + except _Unconfined: + raise + except OSError as exc: + raise _RootUnheld.from_error(exc) from exc + try: + fd = _win_open_confined_rechecked(root_real, parts, access) + try: + _win_recheck_held(root_held) + except BaseException: + os.close(fd) + raise finally: _win_release(root_held) else: # pragma: no cover - no supported platform lands here, and failing closed is the safe arm @@ -3289,7 +3325,7 @@ def _open_confined( try: final = _handle_final_path(handle) except OSError as exc: - if unverified is None: + if unverified is None or getattr(exc, "winerror", None) not in _WIN_UNSUPPORTED: raise unverified.append(exc) else: @@ -3632,6 +3668,38 @@ def _win_open_confined(root_real: Path, parts: tuple[str, ...], access: int) -> _win_release(held) +def _win_open_confined_rechecked(root_real: Path, parts: tuple[str, ...], access: int) -> int: + """Windows: :func:`_win_open_confined`, then each held folder checked again by its handle once + the file is open and before it is released (vault BACKLOG #6573), and the file refused if any + now names another path. Only the backup's config walk opens this way. + + A held folder cannot be renamed, but an empty one can still be made a junction in place, which + the open by name then follows. The re-check catches a folder still converted when it runs. It + sees one instant, so at least a folder converted and reverted between the open and the re-check + is not detected.""" + held = _win_hold_dirs(root_real, parts[:-1]) + try: + fd = _win_open_file(root_real.joinpath(*parts), access) + try: + _win_recheck_held(held) + except BaseException: + os.close(fd) + raise + return fd + finally: + _win_release(held) + + +def _win_recheck_held(held: list[int]) -> None: + """Windows: refuse, as :func:`_win_hold_dirs` does when it opens them, if any of the folder + handles ``held`` is no longer a plain directory or now names another path (vault BACKLOG + #6573).""" + for handle in held: + attributes, tag = _attribute_tag(handle) + if not attributes & stat.FILE_ATTRIBUTE_DIRECTORY or tag & _NAME_SURROGATE: + raise _Unconfined("a held folder became a link or a junction") + + def _win_hold_dirs(root: Path, dirs: tuple[str, ...], *, hold_root: bool = False) -> list[int]: """Windows: open each directory ``root/dirs...`` as itself, refuse one that is not a plain directory, and return their handles, held so that none can be renamed (BACKLOG #2535). The caller @@ -3778,6 +3846,30 @@ def _attribute_tag(handle: int) -> tuple[int, int]: return int(info.attributes), int(info.tag) +#: ``FILE_SUPPORTS_REPARSE_POINTS``, a volume flag ``GetVolumeInformationByHandleW`` reports. +_FILE_SUPPORTS_REPARSE_POINTS = 0x00000080 + + +def _win_volume_flags(path: Path) -> int: + """Windows: the file-system flags of the volume holding ``path``, read from a handle on + ``path`` opened as itself (``GetVolumeInformationByHandleW``). The DR backup's config walk asks + this whether a volume can hold a link at all (vault BACKLOG #6573). Its error carries the + Windows code and text, never the path.""" + k32 = _kernel32() + handle = _win_create( + path, _FILE_READ_ATTRIBUTES, _SHARE_ALL, _FLAG_OPEN_REPARSE_POINT | _FLAG_BACKUP_SEMANTICS + ) + try: + flags = ctypes.c_ulong() # a DWORD on Windows, which the declared LPDWORD requires + if not k32.GetVolumeInformationByHandleW( + handle, None, 0, None, None, ctypes.byref(flags), None, 0 + ): + raise _win_error() + return int(flags.value) + finally: + k32.CloseHandle(handle) + + def _rename_by_handle(fd: int, target: Path) -> None: """Windows: rename the file open on ``fd`` to ``target``, refusing an existing name with ``FileExistsError``. ``SetFileInformationByHandle(FileRenameInfo)``, which is what ``MoveFileExW`` @@ -3928,6 +4020,17 @@ def _kernel32() -> Any: wintypes.DWORD, ) k32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + k32.GetVolumeInformationByHandleW.argtypes = ( + wintypes.HANDLE, + wintypes.LPWSTR, + wintypes.DWORD, + wintypes.LPDWORD, + wintypes.LPDWORD, + wintypes.LPDWORD, + wintypes.LPWSTR, + wintypes.DWORD, + ) + k32.GetVolumeInformationByHandleW.restype = wintypes.BOOL return k32 diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index 28aa7fc5a6..fb207369f7 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1714,25 +1714,26 @@ def final_path(handle: int) -> str: def _record_handles(monkeypatch: pytest.MonkeyPatch, checked: Path) -> list[io.BufferedReader]: """Record the reader the walk builds over each descriptor the confined open returns for - ``checked``, so a test can show each was closed.""" + ``checked``, so a test can show each was closed. A reader is matched to the path its + descriptor was last opened for, not to the descriptor's number alone, which the next file's + open can reuse once this one is closed.""" import messagefoundry.pipeline.dr_backup as dr_backup from messagefoundry.transports.file import _open_confined as real_open real_reader = dr_backup._reader_over - fds: list[int] = [] + opened_for: dict[int, Path] = {} handles: list[io.BufferedReader] = [] def open_confined( path: Path, base: Path, root_real: Path, **kwargs: object ) -> tuple[int, os.stat_result]: fd, st = real_open(path, base, root_real, **kwargs) # type: ignore[arg-type] - if path == checked: - fds.append(fd) + opened_for[fd] = path return fd, st def reader_over(fd: int) -> io.BufferedReader: handle = real_reader(fd) - if fd in fds: + if opened_for.pop(fd, None) == checked: handles.append(handle) return handle @@ -1742,16 +1743,16 @@ def reader_over(fd: int) -> io.BufferedReader: @pytest.mark.skipif(sys.platform != "win32", reason="the final-path check is Windows-only") -@pytest.mark.parametrize("winerror", [1, 50, 87, 3]) +@pytest.mark.parametrize("winerror", [1, 50, 87]) async def test_a_config_file_whose_final_path_cannot_be_read_is_added_from_its_handle( tmp_path, key_b64, monkeypatch, caplog, winerror ) -> None: """On Windows a file the confined open opened and found regular, whose final path alone - cannot be read, is added from the handle that open returned, with its own bytes, and one - WARNING per pass counts it and says the residual (vault BACKLOG #6573). Before, such a file - was passed over on ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER, - which origin/main had bundled, and opened again by name on any other error. The descriptor - is closed.""" + cannot be read with ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER, + which say the volume cannot report one, is added from the handle that open returned, with its + own bytes, and one WARNING per pass counts it and says the residual (vault BACKLOG #6573). + Before, such a file was passed over, which origin/main had bundled. Any other code fails the + backup instead (the next test). The descriptor is closed.""" cfg, _host = _config_for_a_swap(tmp_path) checked = cfg / "swapped.toml" (cfg / "other.toml").write_bytes(b"other") @@ -1774,11 +1775,166 @@ async def test_a_config_file_whose_final_path_cannot_be_read_is_added_from_its_h warned = [r.getMessage() for r in caplog.records if "could not report" in r.getMessage()] assert len(warned) == 1, warned assert "added 2 file(s)" in warned[0] and "other.toml, swapped.toml" in warned[0] - assert "above the config dir" in warned[0] + assert "above the config dir" in warned[0] and "and back" in warned[0] + assert "2 whose final path" in warned[0] and "0 opened by name" in warned[0] assert f"WinError {winerror}" in warned[0] assert len(handles) == 1 and handles[0].closed +@pytest.mark.skipif(sys.platform != "win32", reason="the final-path check is Windows-only") +@pytest.mark.parametrize("winerror", [3, 5, 6]) +async def test_a_config_file_whose_final_path_query_fails_otherwise_fails_the_backup( + tmp_path, key_b64, monkeypatch, caplog, winerror +) -> None: + """A final-path query that fails with any code but the three that say the volume cannot + report one, such as ERROR_PATH_NOT_FOUND, ERROR_ACCESS_DENIED or ERROR_INVALID_HANDLE, is no + proof the volume lacks the check, so the file is not trusted from its handle: the backup + fails, naming the file (vault BACKLOG #6573). Before, any query error was trusted. The + codes that are trusted are the other arm, in the test above.""" + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + failed = _fail_the_final_path_of(monkeypatch, winerror, checked) + with pytest.raises(BackupError, match="swapped.toml"): + await _pass_with_bytes(tmp_path, key_b64, cfg) + assert len(failed) == 1, "the final-path fault ran" + assert not [r for r in caplog.records if "could not report" in r.getMessage()] + + +async def test_a_config_file_whose_open_step_fails_with_path_not_found_fails_the_backup( + tmp_path, key_b64, monkeypatch +) -> None: + """A step of the confined open that fails with ERROR_PATH_NOT_FOUND while the name still + screens as a regular file fails the backup, naming the file: it is neither a file gone nor a + volume that does not do what the step asked (vault BACKLOG #6573). The control is the same + pass with the open left alone, which carries the file.""" + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + (tmp_path / "control").mkdir() + _result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) + assert "config/swapped.toml" in names # the control + + faulted = _fault_the_open( + monkeypatch, checked, _os_error(2, "The system cannot find the path specified", 3) + ) + with pytest.raises(BackupError, match="swapped.toml"): + await _pass_with_bytes(tmp_path, key_b64, cfg) + assert faulted == [checked], "the fault ran" + + +def _fault_the_open(monkeypatch: pytest.MonkeyPatch, checked: Path, exc: OSError) -> list[Path]: + """Fail the confined open of ``checked`` with ``exc`` and leave every ``lstat`` alone, so the + screen after the failed open still reads a regular file. Returns the list the open appends + ``checked`` to.""" + from messagefoundry.transports.file import _open_confined as real_open + + faulted: list[Path] = [] + + def open_confined( + path: Path, base: Path, root_real: Path, **kwargs: object + ) -> tuple[int, os.stat_result]: + if path == checked: + faulted.append(path) + raise exc + return real_open(path, base, root_real, **kwargs) # type: ignore[arg-type] + + monkeypatch.setattr("messagefoundry.pipeline.dr_backup._open_confined", open_confined) + return faulted + + +def _fake_volume_flags(monkeypatch: pytest.MonkeyPatch, answer: int | OSError) -> list[Path]: + """Answer the walk's question about the config dir's volume with the flags ``answer``, or + fail it with that error. Returns the list each question appends its path to.""" + asked: list[Path] = [] + + def volume_flags(path: Path) -> int: + asked.append(path) + if isinstance(answer, OSError): + raise answer + return answer + + monkeypatch.setattr("messagefoundry.pipeline.dr_backup._win_volume_flags", volume_flags) + return asked + + +@pytest.mark.parametrize("winerror", [1, 50, 87]) +async def test_an_unsupported_open_step_on_a_volume_with_no_reparse_points_adds_the_file_by_name( + tmp_path, key_b64, monkeypatch, caplog, winerror +) -> None: + """A step of the confined open that fails with a code saying the volume does not do what it + asked, on a volume that reports it holds no reparse points, where no link can be, adds the + file opened by name with its own bytes, as origin/main did, and the WARNING counts it (vault + BACKLOG #6573). Before, the file was passed over. Faked, so it runs on POSIX too.""" + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + faulted = _fault_the_open(monkeypatch, checked, _os_error(22, "Not supported", winerror)) + asked = _fake_volume_flags(monkeypatch, 0x2) # case-preserving names, no reparse points + with caplog.at_level(logging.WARNING, logger="messagefoundry.pipeline.dr_backup"): + result, names, tar_bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) + assert faulted == [checked] and asked == [cfg.resolve()], "the fault ran" + assert "config/swapped.toml" in names + with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r") as tar: + member = tar.extractfile("config/swapped.toml") + assert member is not None and member.read() == b"#" * 100 + assert result.config_skipped_files == () + warned = [r.getMessage() for r in caplog.records if "opened by name" in r.getMessage()] + assert len(warned) == 1, warned + assert "added 1 file(s)" in warned[0] and "1 opened by name" in warned[0] + assert f"WinError {winerror}" in warned[0] and "swapped.toml" in warned[0] + assert "falsely" in warned[0] + + +@pytest.mark.parametrize("volume", ["holds-links", "query-fails"]) +async def test_an_unsupported_open_step_on_a_volume_that_may_hold_links_fails_the_backup( + tmp_path, key_b64, monkeypatch, volume +) -> None: + """A step of the confined open that fails with a code saying the volume does not do what it + asked, on a volume that reports it holds reparse points, or whose answer cannot be read, + fails the backup naming the file, the cause and the remedy: a link may be there, and the open + that would refuse it could not run (vault BACKLOG #6573). Before, the file was passed over + and the backup succeeded. Faked, so it runs on POSIX too.""" + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + faulted = _fault_the_open(monkeypatch, checked, _os_error(22, "Not supported", 50)) + answer: int | OSError = 0x80 if volume == "holds-links" else _os_error(5, "denied", 5) + asked = _fake_volume_flags(monkeypatch, answer) + with pytest.raises(BackupError) as raised: + await _pass_with_bytes(tmp_path, key_b64, cfg) + assert faulted == [checked] and asked == [cfg.resolve()], "the fault ran" + # Whole within the 200 characters an alert and the audit row keep. + text = str(raised.value) + assert len(text) < 200, text + assert "swapped.toml" in text and "WinError 50" in text + assert "include_config = false" in text and "NTFS or ReFS" in text + if volume == "holds-links": + assert "can hold links" in text + else: + assert "unreadable (WinError 5)" in text + + +@pytest.mark.skipif(sys.platform != "win32", reason="a Windows sharing violation") +async def test_a_config_dir_another_handle_holds_open_for_delete_fails_naming_the_dir( + tmp_path, key_b64 +) -> None: + """A config dir another process holds open for delete cannot be held as itself by the walk, + and the backup fails naming the config dir, not the first file under it, whose fault it is + not (vault BACKLOG #6573). The control is the same pass once the handle is closed.""" + from tests.test_file_open_confined_unverified import _close, _hold_for_delete + + cfg, _host = _config_for_a_swap(tmp_path) + handle = _hold_for_delete(cfg) + try: + with pytest.raises(BackupError) as raised: + await _pass_with_bytes(tmp_path, key_b64, cfg) + finally: + _close(handle) + text = str(raised.value) + assert "the config dir" in text and "could not be held" in text and str(cfg) in text + assert "feed.py" not in text + (tmp_path / "control").mkdir() + _result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) + assert "config/feed.py" in names # the control + + @pytest.mark.skipif(sys.platform != "win32", reason="the final-path check is Windows-only") async def test_a_tar_failure_closes_the_handle_of_a_file_whose_final_path_cannot_be_read( tmp_path, key_b64, monkeypatch diff --git a/tests/test_file_open_confined_unverified.py b/tests/test_file_open_confined_unverified.py index 8c39d0aef1..fd71d41fe3 100644 --- a/tests/test_file_open_confined_unverified.py +++ b/tests/test_file_open_confined_unverified.py @@ -206,3 +206,215 @@ def final_path(handle: int) -> str: finally: os.rmdir(root) # the junction, not its target assert unverified == [] + + +# --- round 4: the held folders checked again once the file is open, the query's codes, and the +# root held open for delete by another handle (vault BACKLOG #6573) --- + + +def _fail_every_final_path_ending( + monkeypatch: pytest.MonkeyPatch, name: str, winerror: int +) -> list[str]: + """Fail the final-path query of every handle whose final path ends in ``name`` with + ``winerror``, wherever a link led it, so the final-path check cannot catch a link.""" + real = file_mod._handle_final_path + failed: list[str] = [] + + def final_path(handle: int) -> str: + found = real(handle) + if found.lower().endswith(name): + failed.append(found) + raise OSError(22, "the volume does not do that", None, winerror) + return found + + monkeypatch.setattr(file_mod, "_handle_final_path", final_path) + return failed + + +def _convert_at_the_open( + monkeypatch: pytest.MonkeyPatch, folder: Path, emptied: Path, host: Path +) -> list[Path]: + """Just before the file is opened as itself, delete ``emptied`` and make the now empty + ``folder``, which the walk holds, a junction to ``host`` in place, without renaming it, so + the open by name follows it. Returns the list the conversion appends ``folder`` to.""" + from tests.test_b4992_dr_win_staging import _convert_to_junction + + real_open_file = file_mod._win_open_file + converted: list[Path] = [] + + def open_file(path: Path, access: int, **kwargs: object) -> int: + if not converted: + emptied.unlink() + _convert_to_junction(folder, host) + converted.append(folder) + return real_open_file(path, access, **kwargs) # type: ignore[arg-type] + + monkeypatch.setattr(file_mod, "_win_open_file", open_file) + return converted + + +@_WINDOWS_ONLY +@pytest.mark.parametrize("folder", ["sub", "root"]) +@pytest.mark.parametrize("convert", [False, True], ids=["control", "converted"]) +def test_the_opt_in_refuses_a_held_folder_made_a_junction_in_place_after_the_open( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, folder: str, convert: bool +) -> None: + """A held folder cannot be renamed, but once emptied it can be made a junction in place, and + the open by name then follows it. With the final-path query failing, nothing else caught + that, so the opted-in open returned the host's file. Each held folder, the root included, is + now checked again by its handle once the file is open, and the file is refused. The control + is the same open with no conversion, which returns the folder's own file.""" + root = tmp_path / "config" + held = root / "sub" if folder == "sub" else root + held.mkdir(parents=True) + target = held / "a.toml" + target.write_bytes(b"own") + host = tmp_path / "host" + host.mkdir() + (host / "a.toml").write_bytes(b"HOST-SECRET") + failed = _fail_every_final_path_ending(monkeypatch, "a.toml", 50) + converted = _convert_at_the_open(monkeypatch, held, target, host) if convert else [] + unverified: list[OSError] = [] + try: + if convert: + with pytest.raises(file_mod._Unconfined): + fd, _st = file_mod._open_confined( + target, root, root.resolve(), unverified=unverified + ) + os.close(fd) + assert converted == [held], "the conversion ran" + else: + fd, _st = file_mod._open_confined(target, root, root.resolve(), unverified=unverified) + try: + assert os.read(fd, 16) == b"own" + finally: + os.close(fd) + assert len(failed) == 1 and len(unverified) == 1 # the fault ran + finally: + if converted: + os.rmdir(held) # the junction, not its target + assert (host / "a.toml").read_bytes() == b"HOST-SECRET" + + +@_WINDOWS_ONLY +@pytest.mark.parametrize("opted_in", [False, True], ids=["default", "opted-in"]) +def test_the_file_connector_default_path_runs_no_recheck_and_holds_no_root( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, opted_in: bool +) -> None: + """The file connector's default open, without the opt-in, is unchanged by the re-check of + vault BACKLOG #6573: it never holds the root, never checks a held folder again, and a final + path it cannot read still fails it with that query's own error. The opted-in arm is the + control that the spies see the new walk.""" + inbox = tmp_path / "in" + (inbox / "sub").mkdir(parents=True) + drop = inbox / "sub" / "drop.hl7" + drop.write_bytes(b"MSH|^~\\&|LAB|FAC|EHR|FAC|20260930||ADT^A01|CTRL1|P|2.5\r") + _fail_every_final_path_ending(monkeypatch, "drop.hl7", 50) + rechecked: list[int] = [] + root_holds: list[bool] = [] + real_hold = file_mod._win_hold_dirs + + def recheck(held: list[int]) -> None: + rechecked.append(len(held)) + + def hold(root: Path, dirs: tuple[str, ...], **kwargs: bool) -> list[int]: + root_holds.append(bool(kwargs.get("hold_root"))) + return real_hold(root, dirs, **kwargs) + + monkeypatch.setattr(file_mod, "_win_recheck_held", recheck, raising=False) + monkeypatch.setattr(file_mod, "_win_hold_dirs", hold) + if opted_in: + fd, _st = file_mod._open_confined(drop, inbox, inbox.resolve(), unverified=[]) + os.close(fd) + assert root_holds == [True, False] and rechecked == [1, 1] + else: + with pytest.raises(OSError) as raised: + file_mod._open_confined(drop, inbox, inbox.resolve()) + assert getattr(raised.value, "winerror", None) == 50 + assert root_holds == [False] and rechecked == [] + + +@_WINDOWS_ONLY +@pytest.mark.parametrize("winerror", [3, 5, 6]) +def test_the_opt_in_raises_a_final_path_query_that_fails_with_any_other_code( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, winerror: int +) -> None: + """Only a final-path query that fails with ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED or + ERROR_INVALID_PARAMETER, which say the volume cannot report one, is trusted on the opt-in. + Any other code is raised, with nothing appended, so a transient failure cannot open the + check. The codes that are trusted are the other arm, in + ``test_the_opt_in_returns_the_open_file_when_only_its_final_path_query_fails``.""" + inbox, drop = _inbox(tmp_path) + failed = _fail_final_path(monkeypatch, drop, winerror) + unverified: list[OSError] = [] + with pytest.raises(OSError) as raised: + fd, _st = file_mod._open_confined(drop, inbox, inbox.resolve(), unverified=unverified) + os.close(fd) + assert len(failed) == 1, "the fault ran" + assert getattr(raised.value, "winerror", None) == winerror + assert not isinstance(raised.value, file_mod._Unconfined) + assert unverified == [] + + +def _hold_for_delete(path: Path) -> int: + """Open the directory ``path`` with DELETE access, shared for everything, as another process + might, and return the handle, which the caller closes with ``_close``.""" + if sys.platform != "win32": # narrows mypy; every caller is Windows-only + pytest.skip("a Windows handle") + import ctypes + from ctypes import wintypes + + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + k32.CreateFileW.restype = wintypes.HANDLE + k32.CreateFileW.argtypes = [ + wintypes.LPCWSTR, + wintypes.DWORD, + wintypes.DWORD, + ctypes.c_void_p, + wintypes.DWORD, + wintypes.DWORD, + wintypes.HANDLE, + ] + # DELETE, share all, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS. + handle = k32.CreateFileW(str(path), 0x00010000, 0x7, None, 3, 0x02000000, None) + if handle in (None, ctypes.c_void_p(-1).value): + raise ctypes.WinError(ctypes.get_last_error()) + return int(handle) + + +def _close(handle: int) -> None: + if sys.platform != "win32": # narrows mypy; every caller is Windows-only + return + import ctypes + from ctypes import wintypes + + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + k32.CloseHandle.argtypes = [wintypes.HANDLE] + k32.CloseHandle(handle) + + +@_WINDOWS_ONLY +def test_the_opt_in_names_the_root_when_another_handle_holds_it_open_for_delete( + tmp_path: Path, +) -> None: + """With the opt-in, a root another handle holds open for delete cannot be held as itself, + and that is raised as the root's own fault, keeping the sharing violation's code, so the + caller can name the root rather than the file. The control is the default open, which does + not hold the root and opens the file.""" + root = tmp_path / "config" + root.mkdir() + (root / "a.toml").write_bytes(b"own") + handle = _hold_for_delete(root) + try: + with pytest.raises(file_mod._RootUnheld) as raised: + fd, _st = file_mod._open_confined(root / "a.toml", root, root.resolve(), unverified=[]) + os.close(fd) + assert getattr(raised.value, "winerror", None) == 32 + assert getattr(raised.value.error, "winerror", None) == 32 + fd, _st = file_mod._open_confined(root / "a.toml", root, root.resolve()) # the control + try: + assert os.read(fd, 16) == b"own" + finally: + os.close(fd) + finally: + _close(handle) diff --git a/tests/test_file_path_join_census.py b/tests/test_file_path_join_census.py index db6d46afb2..d6c2e67824 100644 --- a/tests/test_file_path_join_census.py +++ b/tests/test_file_path_join_census.py @@ -1074,6 +1074,9 @@ def derived_script_sites() -> dict[str, int]: "messagefoundry/transports/file.py::_win_open_confined": Site( 1, GUARDED, _CONFINED, "messagefoundry/transports/file.py::_listed_parts" ), + "messagefoundry/transports/file.py::_win_open_confined_rechecked": Site( + 1, GUARDED, _CONFINED, "messagefoundry/transports/file.py::_listed_parts" + ), "messagefoundry/transports/remotefile.py::RemoteFileDestination._unique": Site( 1, GUARDED, diff --git a/tests/test_running_config_dir_followers.py b/tests/test_running_config_dir_followers.py index 5e558a1573..bbeab0b155 100644 --- a/tests/test_running_config_dir_followers.py +++ b/tests/test_running_config_dir_followers.py @@ -140,24 +140,29 @@ async def test_a_backup_records_what_its_config_fingerprint_left_out( async def test_a_lock_the_archive_walk_meets_fails_a_bundled_backup( backup_engine: tuple[Engine, Path, Path], monkeypatch: pytest.MonkeyPatch ) -> None: - """``tar.add`` opens each file itself, so a file still locked at the walk fails the run, and + """The archive walk opens each file itself, through the confined open (vault BACKLOG #6573), + so a file still locked at the walk fails the run, naming the file, and ``config_unreadable_files`` is never written for it.""" + from messagefoundry.transports.file import _open_confined as real_open + engine, live, _staging = backup_engine runner = engine._backup_runner assert runner is not None (live / "environments").mkdir() (live / "environments" / "dev.toml").write_text('X = "1"\n', encoding="utf-8") _unreadable(monkeypatch, "dev.toml") - real_open = tarfile.bltn_open # type: ignore[attr-defined] + locked: list[Path] = [] - def _open(name: Any, *args: Any, **kwargs: Any) -> Any: - if Path(name).name == "dev.toml": - raise PermissionError(13, "Permission denied", str(name)) - return real_open(name, *args, **kwargs) + def _open(path: Path, *args: Any, **kwargs: Any) -> Any: + if path.name == "dev.toml": + locked.append(path) + raise PermissionError(13, "Permission denied") + return real_open(path, *args, **kwargs) - monkeypatch.setattr(tarfile, "bltn_open", _open) - with pytest.raises(BackupError) as failed: + monkeypatch.setattr("messagefoundry.pipeline.dr_backup._open_confined", _open) + with pytest.raises(BackupError, match="dev.toml") as failed: await runner.run_once(now=1.0) + assert locked, "the lock ran at the walk" assert failed.value.kind == "write" assert "config_unreadable_files" not in await _last_audit(engine.store) From 58fd4ff02897d42314a88b0faf96dd8fd55006a4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:51:48 -0600 Subject: [PATCH 14/49] docs: the include_config row names the re-check and its residuals (BACKLOG #6573) The row says the held folders are checked again after the open, that the re-check sees one instant, and names with "at least" what it still misses: a folder made a link and back in between, and a folder above the config dir. It says which final-path codes are trusted, what an unsupported open step does on each kind of volume, the misreporting redirector residual, and that a config dir held open for delete is named as the dir. Proposed PR title: DR backup config walk: re-check held folders after the open, trust three final-path codes, open by name only where no link can be (BACKLOG #6573) Proposed vault banner: BUILT round 4 on engine branch b20053-6573d: O1, O2, O4, O8 and O13 fixed; O3, O5-O7, O9-O12 and the 6573b finding 1 owed. Verified-by: none --- docs/CONFIGURATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5d47ae1228..4b37e83714 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573). A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file whose final path cannot be read, as below. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails, as on a volume that cannot report one, the file is added from its handle without that check, and one WARNING per pass counts such files, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened, so the residual that check would have caught is a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows an open that fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which say the volume does not do what a step of the open asked, passes the file over. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file whose final path cannot be read, as below. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which say the volume cannot report one, the file is added from its handle without that check; any other failure of that query fails the backup, naming the file. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name, as before vault BACKLOG #6573, and counted in the same WARNING. Where it reports it does, or the answer cannot be read, the backup fails, naming the file, the cause and the remedy: keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | From bc63960f5652c04899dcb8f4397e32d8c272f09b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:12:22 -0600 Subject: [PATCH 15/49] dr_backup: a root hold the volume does not support asks the volume (BACKLOG #6573) Review round 1 repairs. A hold of the config dir failing with WinError 1, 50 or 87 is raised as a step of the open, so the walk asks the volume about reparse points rather than failing on the dir. A hold reporting no such path while the dir is still there fails naming the dir instead of leaving every file out. The by-name open goes down from the resolved config dir whose volume answered. The re-check reads the tag only where the reparse attribute is set. The refusal texts are shorter and name a filter-driver remedy where the volume holds links. The WARNING says the by-name files held nothing. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 63 ++++++++++++------- messagefoundry/transports/file.py | 15 +++-- tests/test_backup_runner.py | 67 +++++++++++++++++++-- tests/test_file_open_confined_unverified.py | 56 +++++++++-------- tests/test_file_path_join_census.py | 7 +++ 5 files changed, 146 insertions(+), 62 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index d3714554e1..3169097775 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -1530,11 +1530,12 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ "DR backup: the config bundle of %s added %d file(s) without the check that each " "was reached through no link: %d whose final path Windows could not report, and " "%d opened by name because a step of the confined open is unsupported on a volume " - "that reports it holds no reparse points (%s). At least these go undetected for " - "them: a folder above the config dir swapped for a link after the backup resolved " - "the dir; a held folder swapped for a link and back between a file's open and the " - "re-check of the held folders, which sees one instant; and a link on a volume that " - "reports its reparse-point support falsely. First %d by name: %s", + "that reports it holds no reparse points (%s). At least these go undetected: for " + "the first kind, a folder above the config dir swapped for a link after the backup " + "resolved the dir, and a held folder swapped for a link and back between a file's " + "open and the re-check of the held folders, which sees one instant; for the " + "second, which held nothing, any link on a volume that reports its reparse-point " + "support falsely. First %d by name: %s", base, len(unverified_names), len(unverified_names) - by_name_count, @@ -3810,9 +3811,15 @@ def _open_config_file( except (_Unconfined, _Replaced): return "passed-over" except _RootUnheld as exc: - if is_absent(exc.error): - return "gone" # the config dir is gone since the listing, so this file is too # Another process holding the config dir open for delete, say: the fault is the dir's. + # A dir gone since the listing leaves its files gone too, but a step of the hold can + # report a name it did not find although the dir is there, so the dir is screened again. + if is_absent(exc.error): + try: + root_real.lstat() + except OSError as screen_exc: + if is_absent(screen_exc): + return "gone" raise _config_dir_error(base, exc) from exc except OSError as exc: if isinstance(exc, FileNotFoundError) and not is_absent(exc): @@ -3843,25 +3850,34 @@ def _open_where_no_link_can_be( """The config file ``path``, whose confined open failed with ``exc``, a code that says the volume does not do what a step of the open asked, opened by name as it was before vault BACKLOG #6573, but only where the config dir's volume reports it holds no reparse points, so - no link can be there to follow. A volume that reports it does, or whose answer cannot be read, - fails the backup, naming the file, the cause and the remedy. The error keeps ``exc``'s codes, - and its text is kept short, because an alert and the audit row cut it at 200 characters.""" - remedy = "use local NTFS or ReFS or include_config = false" + no link can be there to follow. The file is opened down from ``root_real``, the dir whose + volume answered, so the open crosses no link at ``base`` or above it. A volume that reports it + holds reparse points, or whose answer cannot be read, fails the backup, naming the file, the + cause and the remedy. The error keeps ``exc``'s codes. Its fixed text is short, so with a file + name of up to about 60 characters the remedy survives the 200-character cut an alert and the + audit row make; a longer name pushes the remedy past it.""" + name = scrub_log_argument(path.relative_to(base).as_posix()) + what = f"config file {name} not added" try: flags = _win_volume_flags(root_real) except OSError as query_exc: - raise _config_file_error( - path, - base, - exc, - f"volume's link support unreadable ({_error_code(query_exc)}); {remedy}", - ) from query_exc + reason = ( + f"volume link support unreadable ({_error_code(query_exc)}); " + "use local NTFS or ReFS or include_config = false" + ) + raise _error_like(exc, what, reason) from query_exc if flags & _FILE_SUPPORTS_REPARSE_POINTS: - raise _config_file_error( - path, base, exc, f"volume can hold links but refused a no-link open; {remedy}" - ) from exc + # Usually a local volume whose filter driver refused the step, so moving is no remedy. + reason = ( + "volume can hold links yet refused a no-link open; " + "check its filter drivers or include_config = false" + ) + raise _error_like(exc, what, reason) from exc try: - fd = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0)) + fd = os.open( + root_real.joinpath(*path.relative_to(base).parts), + os.O_RDONLY | getattr(os, "O_BINARY", 0), + ) except OSError as open_exc: if is_absent(open_exc): return "gone" @@ -3904,8 +3920,9 @@ def _config_file_error(path: Path, base: Path, exc: OSError, reason: str | None def _config_dir_error(base: Path, exc: OSError) -> OSError: """The error that fails the backup when the config dir ``base`` itself could not be held as itself (vault BACKLOG #6573), naming the dir rather than a file under it, and keeping - ``exc``'s codes and text.""" - what = f"the config dir {scrub_log_argument(str(base))} could not be held for the backup" + ``exc``'s codes and text. A long path can push the text past the 200-character cut an alert + and the audit row make; the Windows code, ahead of the path, survives it.""" + what = f"the config dir {scrub_log_argument(str(base))} could not be held" return _error_like(exc, what, None) diff --git a/messagefoundry/transports/file.py b/messagefoundry/transports/file.py index c27530e25a..23a6d5a8d7 100644 --- a/messagefoundry/transports/file.py +++ b/messagefoundry/transports/file.py @@ -3274,7 +3274,8 @@ def _open_confined( ``unverified``, where given, opts in to trusting a handle whose final path cannot be read (vault BACKLOG #6573); the file connector never passes it. On Windows the root is then held and refused if it names another path too, as each folder below it is (:func:`_win_hold_dirs`); a - root that cannot be held for any other reason raises :class:`_RootUnheld`. Once the file is + root that cannot be held for any other reason raises :class:`_RootUnheld`, except a code in + ``_WIN_UNSUPPORTED``, which is raised as it came, as a step of the open. Once the file is open, each held folder, the root included, is checked again by its handle before it is released, and the file is refused if any of them now names another path (:func:`_win_open_confined_rechecked`). That re-check sees one instant, so a folder swapped for @@ -3303,6 +3304,8 @@ def _open_confined( except _Unconfined: raise except OSError as exc: + if getattr(exc, "winerror", None) in _WIN_UNSUPPORTED: + raise # the volume does not do what the hold asked: a step of the open raise _RootUnheld.from_error(exc) from exc try: fd = _win_open_confined_rechecked(root_real, parts, access) @@ -3691,12 +3694,14 @@ def _win_open_confined_rechecked(root_real: Path, parts: tuple[str, ...], access def _win_recheck_held(held: list[int]) -> None: - """Windows: refuse, as :func:`_win_hold_dirs` does when it opens them, if any of the folder - handles ``held`` is no longer a plain directory or now names another path (vault BACKLOG - #6573).""" + """Windows: refuse if any of the folder handles ``held`` is no longer a plain directory or is + now a reparse point that names another path (vault BACKLOG #6573). The tag is read only where + the reparse attribute is set, since Windows leaves it undefined otherwise.""" for handle in held: attributes, tag = _attribute_tag(handle) - if not attributes & stat.FILE_ATTRIBUTE_DIRECTORY or tag & _NAME_SURROGATE: + if not attributes & stat.FILE_ATTRIBUTE_DIRECTORY or ( + attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT and tag & _NAME_SURROGATE + ): raise _Unconfined("a held folder became a link or a junction") diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index fb207369f7..e9dc14d6ce 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1903,12 +1903,69 @@ async def test_an_unsupported_open_step_on_a_volume_that_may_hold_links_fails_th # Whole within the 200 characters an alert and the audit row keep. text = str(raised.value) assert len(text) < 200, text - assert "swapped.toml" in text and "WinError 50" in text - assert "include_config = false" in text and "NTFS or ReFS" in text + assert "swapped.toml" in text and "include_config = false" in text + if sys.platform == "win32": # POSIX keeps no Windows code on an OSError it builds + assert "WinError 50" in text if volume == "holds-links": - assert "can hold links" in text + assert "can hold links" in text and "filter drivers" in text else: - assert "unreadable (WinError 5)" in text + assert "unreadable (WinError 5)" in text and "NTFS or ReFS" in text + + +def _fail_the_root_hold(monkeypatch: pytest.MonkeyPatch, exc: OSError) -> list[Path]: + """Fail the confined open's hold of the config dir itself with ``exc``, and leave every other + hold alone. Returns the list each failed hold appends the dir to.""" + import messagefoundry.transports.file as file_mod + + real_hold = file_mod._win_hold_dirs + failed: list[Path] = [] + + def hold(root: Path, dirs: tuple[str, ...], **kwargs: bool) -> list[int]: + if kwargs.get("hold_root"): + failed.append(root) + raise exc + return real_hold(root, dirs, **kwargs) + + monkeypatch.setattr(file_mod, "_win_hold_dirs", hold) + return failed + + +@pytest.mark.skipif(sys.platform != "win32", reason="the root hold is Windows-only") +async def test_a_root_hold_the_volume_does_not_support_asks_the_volume_like_any_open_step( + tmp_path, key_b64, monkeypatch +) -> None: + """The hold of the config dir is a step of the confined open, so when it fails with a code + saying the volume does not do what it asked, the volume is asked whether it holds reparse + points, as for any other step, rather than the backup failing as the dir's own fault (vault + BACKLOG #6573). Here the volume reports it holds none, so each file is added by name.""" + cfg, _host = _config_for_a_swap(tmp_path) + failed = _fail_the_root_hold(monkeypatch, _os_error(22, "Not supported", 50)) + asked = _fake_volume_flags(monkeypatch, 0) + _result, names, _bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) + assert failed and asked, "the fault ran" + assert names == [ + "config/feed.py", + "config/keep/plain.txt", + "config/sub/secret.txt", + "config/swapped.toml", + ] + + +@pytest.mark.skipif(sys.platform != "win32", reason="the root hold is Windows-only") +async def test_a_root_hold_that_reports_no_such_path_while_the_dir_is_there_fails_naming_it( + tmp_path, key_b64, monkeypatch +) -> None: + """A hold of the config dir that reports a path not found while the dir is still there is a + fault, not a dir gone since the listing: the backup fails naming the config dir, rather than + leaving every file out unrecorded (vault BACKLOG #6573).""" + cfg, _host = _config_for_a_swap(tmp_path) + failed = _fail_the_root_hold( + monkeypatch, _os_error(2, "The system cannot find the path specified", 3) + ) + with pytest.raises(BackupError) as raised: + await _pass_with_bytes(tmp_path, key_b64, cfg) + assert failed, "the fault ran" + assert "the config dir" in str(raised.value) and "could not be held" in str(raised.value) @pytest.mark.skipif(sys.platform != "win32", reason="a Windows sharing violation") @@ -1928,7 +1985,7 @@ async def test_a_config_dir_another_handle_holds_open_for_delete_fails_naming_th finally: _close(handle) text = str(raised.value) - assert "the config dir" in text and "could not be held" in text and str(cfg) in text + assert "the config dir" in text and "could not be held" in text and "WinError 32" in text assert "feed.py" not in text (tmp_path / "control").mkdir() _result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) diff --git a/tests/test_file_open_confined_unverified.py b/tests/test_file_open_confined_unverified.py index fd71d41fe3..81384bfe35 100644 --- a/tests/test_file_open_confined_unverified.py +++ b/tests/test_file_open_confined_unverified.py @@ -359,38 +359,13 @@ def test_the_opt_in_raises_a_final_path_query_that_fails_with_any_other_code( def _hold_for_delete(path: Path) -> int: """Open the directory ``path`` with DELETE access, shared for everything, as another process might, and return the handle, which the caller closes with ``_close``.""" - if sys.platform != "win32": # narrows mypy; every caller is Windows-only - pytest.skip("a Windows handle") - import ctypes - from ctypes import wintypes - - k32 = ctypes.WinDLL("kernel32", use_last_error=True) - k32.CreateFileW.restype = wintypes.HANDLE - k32.CreateFileW.argtypes = [ - wintypes.LPCWSTR, - wintypes.DWORD, - wintypes.DWORD, - ctypes.c_void_p, - wintypes.DWORD, - wintypes.DWORD, - wintypes.HANDLE, - ] - # DELETE, share all, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS. - handle = k32.CreateFileW(str(path), 0x00010000, 0x7, None, 3, 0x02000000, None) - if handle in (None, ctypes.c_void_p(-1).value): - raise ctypes.WinError(ctypes.get_last_error()) - return int(handle) + return file_mod._win_create( + path, file_mod._DELETE, file_mod._SHARE_ALL, file_mod._FLAG_BACKUP_SEMANTICS + ) def _close(handle: int) -> None: - if sys.platform != "win32": # narrows mypy; every caller is Windows-only - return - import ctypes - from ctypes import wintypes - - k32 = ctypes.WinDLL("kernel32", use_last_error=True) - k32.CloseHandle.argtypes = [wintypes.HANDLE] - k32.CloseHandle(handle) + file_mod._kernel32().CloseHandle(handle) @_WINDOWS_ONLY @@ -418,3 +393,26 @@ def test_the_opt_in_names_the_root_when_another_handle_holds_it_open_for_delete( os.close(fd) finally: _close(handle) + + +@_WINDOWS_ONLY +@_VOLUME_CODES +def test_a_root_hold_the_volume_does_not_support_is_raised_as_it_came( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, winerror: int +) -> None: + """A hold of the root that fails with a code saying the volume does not do what it asked is + a step of the open like any other, so it is raised as it came, not as the root's own fault, + and the caller can ask the volume whether it holds reparse points.""" + root = tmp_path / "config" + root.mkdir() + (root / "a.toml").write_bytes(b"own") + + def hold(_root: Path, _dirs: tuple[str, ...], **_kwargs: bool) -> list[int]: + raise OSError(22, "the volume does not do that", None, winerror) + + monkeypatch.setattr(file_mod, "_win_hold_dirs", hold) + with pytest.raises(OSError) as raised: + fd, _st = file_mod._open_confined(root / "a.toml", root, root.resolve(), unverified=[]) + os.close(fd) + assert getattr(raised.value, "winerror", None) == winerror + assert not isinstance(raised.value, file_mod._RootUnheld) diff --git a/tests/test_file_path_join_census.py b/tests/test_file_path_join_census.py index d6c2e67824..af96522534 100644 --- a/tests/test_file_path_join_census.py +++ b/tests/test_file_path_join_census.py @@ -944,6 +944,13 @@ def derived_script_sites() -> dict[str, int]: "messagefoundry/pipeline/dr_backup.py::_verify_in_staging": Site( 1, INTERNAL, "A fixed name in a staging directory this module made." ), + "messagefoundry/pipeline/dr_backup.py::_open_where_no_link_can_be": Site( + 1, + OPERATOR, + "A config file's parts below the operator's config directory, as the archive walk listed " + "them, joined to that directory resolved, and opened by name only where its volume " + "reports it holds no reparse points (vault BACKLOG #6573).", + ), "messagefoundry/pipeline/dr_backup.py::_walk_unfollowed": Site( 1, OPERATOR, From 16a28c06cd020982215e934a287ed1a1fb4ce817 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:12:49 -0600 Subject: [PATCH 16/49] docs: the include_config row names the root hold and each remedy (BACKLOG #6573) The row says a hold of the config dir that the volume does not support is a step of the open, that a file opened by name goes down from the resolved config dir and holds nothing, which remedy each refusal names, and that a config dir that cannot be held while it is still there is named as the dir. Proposed PR title: DR backup config walk: re-check held folders after the open, trust three final-path codes, open by name only where no link can be (BACKLOG #6573) Proposed vault banner: BUILT round 4 on engine branch b20053-6573d: O1, O2, O4, O8 and O13 fixed; O3, O5-O7, O9-O12 and the 6573b finding 1 owed. Verified-by: none --- docs/CONFIGURATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 4b37e83714..752474e311 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file whose final path cannot be read, as below. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which say the volume cannot report one, the file is added from its handle without that check; any other failure of that query fails the backup, naming the file. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name, as before vault BACKLOG #6573, and counted in the same WARNING. Where it reports it does, or the answer cannot be read, the backup fails, naming the file, the cause and the remedy: keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file whose final path cannot be read, as below. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which say the volume cannot report one, the file is added from its handle without that check; any other failure of that query fails the backup, naming the file. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the file, the cause and the remedy: find the filter driver that refused the step, or set `include_config = false`. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | From d83236bdecc8a3cd08ad09cedb94cf258009d39f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:28:08 -0600 Subject: [PATCH 17/49] dr_backup: a name swapped for a folder before the open by name is passed over (BACKLOG #6573) Review round 2 repairs. On a volume with no reparse points, an open by name that fails while the name now reads as no regular file passes the file over, as the confined open does. The refusal on a volume that can hold links names the filter or the share. The docstring no longer says the open by name crosses no link above the config dir. The WARNING names that residual for files opened by name and puts the codes last. The unused reason argument of the file error is gone. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 41 +++++++++++++++++----------- tests/test_backup_runner.py | 28 ++++++++++++++++++- 2 files changed, 52 insertions(+), 17 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 3169097775..b322f3d106 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -1530,12 +1530,13 @@ def _add_config_dir(self, tar: tarfile.TarFile, base: Path) -> tuple[int, tuple[ "DR backup: the config bundle of %s added %d file(s) without the check that each " "was reached through no link: %d whose final path Windows could not report, and " "%d opened by name because a step of the confined open is unsupported on a volume " - "that reports it holds no reparse points (%s). At least these go undetected: for " - "the first kind, a folder above the config dir swapped for a link after the backup " + "that reports it holds no reparse points. At least these go undetected: for the " + "first kind, a folder above the config dir swapped for a link after the backup " "resolved the dir, and a held folder swapped for a link and back between a file's " "open and the re-check of the held folders, which sees one instant; for the " - "second, which held nothing, any link on a volume that reports its reparse-point " - "support falsely. First %d by name: %s", + "second, which held nothing, a folder above the config dir or the dir itself " + "swapped for a link, and any link on a volume that reports its reparse-point " + "support falsely. Codes seen for both kinds: %s. First %d by name: %s", base, len(unverified_names), len(unverified_names) - by_name_count, @@ -3846,16 +3847,17 @@ def _open_config_file( def _open_where_no_link_can_be( path: Path, base: Path, root_real: Path, exc: OSError -) -> tuple[int, _Unchecked] | Literal["gone"]: +) -> tuple[int, _Unchecked] | Literal["gone", "passed-over"]: """The config file ``path``, whose confined open failed with ``exc``, a code that says the volume does not do what a step of the open asked, opened by name as it was before vault BACKLOG #6573, but only where the config dir's volume reports it holds no reparse points, so no link can be there to follow. The file is opened down from ``root_real``, the dir whose - volume answered, so the open crosses no link at ``base`` or above it. A volume that reports it - holds reparse points, or whose answer cannot be read, fails the backup, naming the file, the - cause and the remedy. The error keeps ``exc``'s codes. Its fixed text is short, so with a file - name of up to about 60 characters the remedy survives the 200-character cut an alert and the - audit row make; a longer name pushes the remedy past it.""" + volume answered, not through ``base`` again. Nothing is held, so at least a folder above + ``root_real``, or ``root_real`` itself, swapped for a link before the open is still followed. + A volume that reports it holds reparse points, or whose answer cannot be read, fails the + backup, naming the file, the cause and the remedy. The error keeps ``exc``'s codes. Its fixed + text is short, so with a file name of up to about 60 characters the remedy survives the + 200-character cut an alert and the audit row make; a longer name pushes the remedy past it.""" name = scrub_log_argument(path.relative_to(base).as_posix()) what = f"config file {name} not added" try: @@ -3867,10 +3869,10 @@ def _open_where_no_link_can_be( ) raise _error_like(exc, what, reason) from query_exc if flags & _FILE_SUPPORTS_REPARSE_POINTS: - # Usually a local volume whose filter driver refused the step, so moving is no remedy. + # A local filter driver, or a share's client, refused the step. reason = ( "volume can hold links yet refused a no-link open; " - "check its filter drivers or include_config = false" + "fix its filter or share, or include_config = false" ) raise _error_like(exc, what, reason) from exc try: @@ -3881,6 +3883,14 @@ def _open_where_no_link_can_be( except OSError as open_exc: if is_absent(open_exc): return "gone" + # Windows refuses to open a folder as a file with an access error, so a name swapped + # for a folder since the screen is passed over, as the confined open's failure is. + try: + again = path.lstat() + except OSError: + raise _config_file_error(path, base, open_exc) from open_exc + if not stat.S_ISREG(again.st_mode) or _stat_names_another_path(again): + return "passed-over" raise _config_file_error(path, base, open_exc) from open_exc return fd, _Unchecked(True, exc) @@ -3909,12 +3919,11 @@ def _reader_over(fd: int) -> io.BufferedReader: raise -def _config_file_error(path: Path, base: Path, exc: OSError, reason: str | None = None) -> OSError: +def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: """The error that fails the backup for the config file ``path``, naming it relative to - ``base`` and keeping ``exc``'s errno, its Windows code where it has one, and ``reason``, - else its text.""" + ``base`` and keeping ``exc``'s errno, its Windows code where it has one, and its text.""" name = scrub_log_argument(path.relative_to(base).as_posix()) - return _error_like(exc, f"the config file {name} could not be added to the backup", reason) + return _error_like(exc, f"the config file {name} could not be added to the backup", None) def _config_dir_error(base: Path, exc: OSError) -> OSError: diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index e9dc14d6ce..59ab9c032d 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1907,11 +1907,37 @@ async def test_an_unsupported_open_step_on_a_volume_that_may_hold_links_fails_th if sys.platform == "win32": # POSIX keeps no Windows code on an OSError it builds assert "WinError 50" in text if volume == "holds-links": - assert "can hold links" in text and "filter drivers" in text + assert "can hold links" in text and "filter or share" in text else: assert "unreadable (WinError 5)" in text and "NTFS or ReFS" in text +async def test_a_name_swapped_for_a_folder_before_the_open_by_name_is_passed_over( + tmp_path, key_b64, monkeypatch +) -> None: + """On a volume that reports it holds no reparse points, a config file swapped for a folder + after the walk screened it and before the open by name is passed over and recorded, and the + backup succeeds, as on the confined open: Windows refuses to open a folder as a file with an + access error, which must not read as a locked config file (vault BACKLOG #6573). Faked, so it + runs on POSIX too, where the folder opens and the walk passes it over as no regular file.""" + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + faulted = _fault_the_open(monkeypatch, checked, _os_error(22, "Not supported", 50)) + swapped: list[Path] = [] + + def volume_flags(path: Path) -> int: + os.replace(checked, tmp_path / "aside.toml") + checked.mkdir() + swapped.append(checked) + return 0 + + monkeypatch.setattr("messagefoundry.pipeline.dr_backup._win_volume_flags", volume_flags) + result, names, _bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) + assert faulted == [checked] and swapped == [checked], "the swap ran" + assert "config/swapped.toml" not in names + assert result.config_skipped_files == ("swapped.toml",) + + def _fail_the_root_hold(monkeypatch: pytest.MonkeyPatch, exc: OSError) -> list[Path]: """Fail the confined open's hold of the config dir itself with ``exc``, and leave every other hold alone. Returns the list each failed hold appends the dir to.""" From 214ff764a0a4deccd38189131885ae150d367c7b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:28:43 -0600 Subject: [PATCH 18/49] docs: the include_config row says the three codes are a reading, not a proof (BACKLOG #6573) The row says the walk reads the three final-path codes as a volume that cannot report one, which is not a proof; that a file opened by name also follows a swap of the config dir itself; the filter-or-share remedy; and that a name turned into a non-file before the open by name is passed over. Proposed PR title: DR backup config walk: re-check held folders after the open, trust three final-path codes, open by name only where no link can be (BACKLOG #6573) Proposed vault banner: BUILT round 4 on engine branch b20053-6573d: O1, O2, O4, O8 and O13 fixed; O3, O5-O7, O9-O12 and the 6573b finding 1 owed. Verified-by: none --- docs/CONFIGURATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 752474e311..1869b88234 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file whose final path cannot be read, as below. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which say the volume cannot report one, the file is added from its handle without that check; any other failure of that query fails the backup, naming the file. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the file, the cause and the remedy: find the filter driver that refused the step, or set `include_config = false`. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the file, the cause and the remedy: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | From 6f7b00c7a17ab1f97d851012976f9b2fa18f7bd6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:52:00 -0600 Subject: [PATCH 19/49] dr_backup: the open by name passes over a descriptor that reached a folder (BACKLOG #6573) The by-name fallback on a volume that reports no reparse points now checks what it opened by its descriptor. POSIX opens a name swapped for a folder, and the reader built over that descriptor raised outside the per-file handler, so the whole backup failed and the Linux test leg went red. A descriptor that is not a regular file is closed and passed over; an fstat that fails closes it and fails the backup naming the file. The new test fakes the open to reach a folder, so it fails before the fix on Windows too. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 10 ++++++ tests/test_backup_runner.py | 53 ++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index b322f3d106..019496246a 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -3892,6 +3892,16 @@ def _open_where_no_link_can_be( if not stat.S_ISREG(again.st_mode) or _stat_names_another_path(again): return "passed-over" raise _config_file_error(path, base, open_exc) from open_exc + # POSIX opens a name swapped for a folder, so what was opened is checked by its descriptor, + # as the confined open checks it, before a reader that would fail the backup is built on it. + try: + regular = stat.S_ISREG(os.fstat(fd).st_mode) + except OSError as stat_exc: + os.close(fd) + raise _config_file_error(path, base, stat_exc) from stat_exc + if not regular: + os.close(fd) + return "passed-over" return fd, _Unchecked(True, exc) diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index 59ab9c032d..77eed31720 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1938,6 +1938,59 @@ def volume_flags(path: Path) -> int: assert result.config_skipped_files == ("swapped.toml",) +def _directory_fd(path: Path) -> int: + """A descriptor open on the folder ``path``, as POSIX ``os.open`` gives one. Windows + ``os.open`` refuses a folder, so there the descriptor is built over a handle the file + connector's own ``CreateFileW`` opens.""" + if sys.platform != "win32": + return os.open(path, os.O_RDONLY) + import messagefoundry.transports.file as file_mod + + handle = file_mod._win_create( + path, file_mod._FILE_READ_ATTRIBUTES, file_mod._SHARE_ALL, file_mod._FLAG_BACKUP_SEMANTICS + ) + return file_mod._fd_for(handle) + + +def test_an_open_by_name_that_reaches_a_folder_passes_it_over_and_closes_it( + tmp_path, monkeypatch +) -> None: + """The open by name on a volume that reports no reparse points checks what it opened, by its + descriptor: one that reached a folder, as POSIX ``os.open`` does for a name swapped for a + folder, is passed over and its descriptor closed, rather than handed to a reader that fails + the whole backup (vault BACKLOG #6573). The open is faked to reach a folder, so it runs on + Windows, whose own ``os.open`` refuses one. The control is the same call left alone, which + returns the file's descriptor.""" + from messagefoundry.pipeline import dr_backup + + cfg = tmp_path / "config" + cfg.mkdir() + checked = cfg / "a.toml" + checked.write_bytes(b"own") + (tmp_path / "folder").mkdir() + step = _os_error(22, "Not supported", 50) + _fake_volume_flags(monkeypatch, 0) + + opened = dr_backup._open_where_no_link_can_be(checked, cfg, cfg.resolve(), step) + assert not isinstance(opened, str) # the control + os.close(opened[0]) + + real_open = os.open + reached: list[int] = [] + + def open_by_name(path, flags, *args, **kwargs): + if os.fspath(path) == os.fspath(cfg.resolve() / "a.toml"): + reached.append(_directory_fd(tmp_path / "folder")) + return reached[-1] + return real_open(path, flags, *args, **kwargs) + + monkeypatch.setattr(os, "open", open_by_name) + assert dr_backup._open_where_no_link_can_be(checked, cfg, cfg.resolve(), step) == "passed-over" + assert len(reached) == 1, "the fault ran" + with pytest.raises(OSError): + os.fstat(reached[0]) # closed + + def _fail_the_root_hold(monkeypatch: pytest.MonkeyPatch, exc: OSError) -> list[Path]: """Fail the confined open's hold of the config dir itself with ``exc``, and leave every other hold alone. Returns the list each failed hold appends the dir to.""" From d3c8ff3e6ece7a0c885619748e2037a5fdf2cc2d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:52:37 -0600 Subject: [PATCH 20/49] file: the confined open's docstring gives its re-check residuals as at least (BACKLOG #6573) The opt-in's re-check sees one instant. Its docstring listed two residuals as a closed set, while the WARNING, the sibling docstring and the include_config row give them with at least. Docstring only. Verified-by: tests --- messagefoundry/transports/file.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/messagefoundry/transports/file.py b/messagefoundry/transports/file.py index 23a6d5a8d7..76d34e9547 100644 --- a/messagefoundry/transports/file.py +++ b/messagefoundry/transports/file.py @@ -3278,9 +3278,9 @@ def _open_confined( ``_WIN_UNSUPPORTED``, which is raised as it came, as a step of the open. Once the file is open, each held folder, the root included, is checked again by its handle before it is released, and the file is refused if any of them now names another path - (:func:`_win_open_confined_rechecked`). That re-check sees one instant, so a folder swapped for - a link and back between the open and the re-check is not detected, nor is a folder above the - root. When the query for the final path then fails with a code in ``_WIN_UNSUPPORTED``, after + (:func:`_win_open_confined_rechecked`). That re-check sees one instant, so at least these go + undetected: a folder swapped for a link and back between the open and the re-check, and a + folder above the root. When the query for the final path then fails with a code in ``_WIN_UNSUPPORTED``, after the regular-file check passed, the descriptor is returned all the same and the query's error appended to ``unverified``; any other failure of that query is raised. A final path that is read and names another path is still refused. From 34d775c7ab0fb890f2e38447d998664116d13f21 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:55:44 -0600 Subject: [PATCH 21/49] dr_backup: a final path a volume with no drive letter cannot give names the remedy (BACKLOG #6573) On a volume reached only by its GUID path, the query of every config file's final path fails with ERROR_PATH_NOT_FOUND, and every backup failed with the system's text alone, which says nothing of the query or the fix. The refusal stays: that code is no proof the volume lacks the check. The confined open, opted in, now raises the query's failure as _FinalPathUnread, which keeps its codes; _RootUnheld and it share one base that copies them. The DR walk names the final-path query for that code and gives the remedy: assign the volume a drive letter, or set include_config = false. Any other code keeps the system's text. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 28 +++++++++++++++++++ messagefoundry/transports/file.py | 31 +++++++++++++++------ tests/test_backup_runner.py | 11 ++++++-- tests/test_file_open_confined_unverified.py | 4 +++ 4 files changed, 63 insertions(+), 11 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 019496246a..cca0171e51 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -118,6 +118,7 @@ _attribute_tag, _fd_for, _file_id, + _FinalPathUnread, _handle_final_path, _open_confined, _os_handle, @@ -3783,6 +3784,11 @@ class _Unchecked(NamedTuple): error: OSError +#: Windows ERROR_PATH_NOT_FOUND, which at least a volume with no drive letter gives for a query of +#: a file's final path. +_ERROR_PATH_NOT_FOUND = 3 + + def _open_config_file( path: Path, base: Path, root_real: Path ) -> tuple[int, _Unchecked | None] | Literal["gone", "passed-over"]: @@ -3822,6 +3828,16 @@ def _open_config_file( if is_absent(screen_exc): return "gone" raise _config_dir_error(base, exc) from exc + except _FinalPathUnread as exc: + # The file is open and regular; only the query for its final path failed, which at least a + # volume with no drive letter does for every file, so the text names that and the remedy. + if getattr(exc, "winerror", None) != _ERROR_PATH_NOT_FOUND: + raise _config_file_error(path, base, exc.error) from exc + reason = ( + "final path unreadable, as at least on a volume with no drive letter; " + "assign the volume a drive letter, or set include_config = false" + ) + raise _refusal(exc.error, "config file not added", reason, _rel_name(path, base)) from exc except OSError as exc: if isinstance(exc, FileNotFoundError) and not is_absent(exc): # A share or network path that cannot be reached, which Windows maps to ENOENT: the @@ -3945,6 +3961,18 @@ def _config_dir_error(base: Path, exc: OSError) -> OSError: return _error_like(exc, what, None) +def _rel_name(path: Path, base: Path) -> str: + """The config file ``path`` named relative to ``base``, scrubbed for a log line.""" + return scrub_log_argument(path.relative_to(base).as_posix()) + + +def _refusal(exc: OSError, what: str, reason: str, where: str) -> OSError: + """An ``OSError`` reading ``what: reason: where``, with ``exc``'s codes as :func:`_error_like` + keeps them. ``where``, a name whose length is not fixed, comes last, so the cut a failure + record makes takes it before the cause and the remedy in ``reason``.""" + return _error_like(exc, what, f"{reason}: {where}") + + def _error_like(exc: OSError, what: str, reason: str | None) -> OSError: """An ``OSError`` reading ``what: reason``, ``reason`` defaulting to ``exc``'s text, with ``exc``'s errno and its Windows code where it has one.""" diff --git a/messagefoundry/transports/file.py b/messagefoundry/transports/file.py index 76d34e9547..82a8addebf 100644 --- a/messagefoundry/transports/file.py +++ b/messagefoundry/transports/file.py @@ -3148,17 +3148,15 @@ class _Replaced(OSError): for the same reason as :class:`_Unconfined`, and its message never carries a file name.""" -class _RootUnheld(OSError): - """The confined open, opted in through ``unverified``, could not hold the root as itself for a - reason other than finding it a link (vault BACKLOG #6573), such as another process holding the - root open for delete. It keeps the hold's errno, Windows code and text, and the hold's own error - as ``error``, so a caller can name the root rather than the file. Its message never carries a - path.""" +class _StepFailed(OSError): + """A step of the confined open, opted in through ``unverified``, that failed with ``error`` + (vault BACKLOG #6573), raised as its own class so a caller can say which step it was. It keeps + ``error``'s errno, Windows code and text. Its message never carries a path.""" error: OSError @classmethod - def from_error(cls, exc: OSError) -> _RootUnheld: + def from_error(cls, exc: OSError) -> Self: winerror = getattr(exc, "winerror", None) if isinstance(winerror, int): made = cls(exc.errno, exc.strerror, None, winerror) @@ -3168,6 +3166,18 @@ def from_error(cls, exc: OSError) -> _RootUnheld: return made +class _RootUnheld(_StepFailed): + """The confined open, opted in, could not hold the root as itself for a reason other than + finding it a link, such as another process holding the root open for delete, so a caller can + name the root rather than the file.""" + + +class _FinalPathUnread(_StepFailed): + """The confined open, opted in, opened a regular file whose final path Windows could not + report, with a code that does not say the volume cannot report one, such as the + ERROR_PATH_NOT_FOUND at least a volume with no drive letter gives.""" + + class _OverCap(Exception): """The file read from the handle is larger than ``max_file_bytes`` (BACKLOG #2507). Its message is a size (" bytes" or "more than bytes"), never a name. ``file_id`` is the identity of the @@ -3282,7 +3292,8 @@ def _open_confined( undetected: a folder swapped for a link and back between the open and the re-check, and a folder above the root. When the query for the final path then fails with a code in ``_WIN_UNSUPPORTED``, after the regular-file check passed, the descriptor is returned all the same and the query's error - appended to ``unverified``; any other failure of that query is raised. A final path that is + appended to ``unverified``; any other failure of that query raises :class:`_FinalPathUnread`. + A final path that is read and names another path is still refused. Either way a link that stays inside the root is refused too. A hard link is not: see @@ -3328,8 +3339,10 @@ def _open_confined( try: final = _handle_final_path(handle) except OSError as exc: - if unverified is None or getattr(exc, "winerror", None) not in _WIN_UNSUPPORTED: + if unverified is None: raise + if getattr(exc, "winerror", None) not in _WIN_UNSUPPORTED: + raise _FinalPathUnread.from_error(exc) from exc unverified.append(exc) else: if os.path.normcase(_plain(final)) != expected: diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index 77eed31720..e1a01f7dd1 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1790,14 +1790,21 @@ async def test_a_config_file_whose_final_path_query_fails_otherwise_fails_the_ba report one, such as ERROR_PATH_NOT_FOUND, ERROR_ACCESS_DENIED or ERROR_INVALID_HANDLE, is no proof the volume lacks the check, so the file is not trusted from its handle: the backup fails, naming the file (vault BACKLOG #6573). Before, any query error was trusted. The - codes that are trusted are the other arm, in the test above.""" + codes that are trusted are the other arm, in the test above. ERROR_PATH_NOT_FOUND, which + at least a volume with no drive letter gives for every file, also names the query and the + remedy, since nothing else in the text would; the other codes keep the system's text.""" cfg, _host = _config_for_a_swap(tmp_path) checked = cfg / "swapped.toml" failed = _fail_the_final_path_of(monkeypatch, winerror, checked) - with pytest.raises(BackupError, match="swapped.toml"): + with pytest.raises(BackupError) as raised: await _pass_with_bytes(tmp_path, key_b64, cfg) assert len(failed) == 1, "the final-path fault ran" assert not [r for r in caplog.records if "could not report" in r.getMessage()] + text = str(raised.value) + assert "swapped.toml" in text and f"WinError {winerror}" in text + remedy = "assign the volume a drive letter, or set include_config = false" + assert (remedy in text) is (winerror == 3), text + assert ("final path" in text) is (winerror == 3), text async def test_a_config_file_whose_open_step_fails_with_path_not_found_fails_the_backup( diff --git a/tests/test_file_open_confined_unverified.py b/tests/test_file_open_confined_unverified.py index 81384bfe35..2e2020a763 100644 --- a/tests/test_file_open_confined_unverified.py +++ b/tests/test_file_open_confined_unverified.py @@ -354,6 +354,10 @@ def test_the_opt_in_raises_a_final_path_query_that_fails_with_any_other_code( assert getattr(raised.value, "winerror", None) == winerror assert not isinstance(raised.value, file_mod._Unconfined) assert unverified == [] + # Raised as the final-path query's own failure, keeping its code, so the caller can say it + # was that query and give the remedy, rather than a bare text naming no step. + assert isinstance(raised.value, file_mod._FinalPathUnread) + assert getattr(raised.value.error, "winerror", None) == winerror def _hold_for_delete(path: Path) -> int: From a4b7ed7644fa885d6d716cc98116f4d1bca9e8ac Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:00:56 -0600 Subject: [PATCH 22/49] dr_backup: a root hold the volume refuses names the config dir, after the remedy (BACKLOG #6573) When the hold of the config dir failed with a code saying the volume does not do what it asked, and the volume then reported it holds reparse points or its answer could not be read, the backup failed naming the first file under the dir, whose fault it was not. The confined open, opted in, now raises every root-hold failure as _RootUnheld, keeping its codes. The DR walk sends one of the three unsupported codes to the volume's answer as before, and a refusal there names the config dir after the cause and the remedy, so a long path is what the 200-character cut drops. The holds-links cause is shortened to leave the dir more of that room. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 30 ++++++++++++++------- messagefoundry/transports/file.py | 6 ++--- tests/test_backup_runner.py | 29 +++++++++++++++++++- tests/test_file_open_confined_unverified.py | 10 ++++--- 4 files changed, 57 insertions(+), 18 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index cca0171e51..72956339b6 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -3818,6 +3818,10 @@ def _open_config_file( except (_Unconfined, _Replaced): return "passed-over" except _RootUnheld as exc: + if getattr(exc, "winerror", None) in _WIN_UNSUPPORTED: + # The volume does not do what the hold asked: the volume is asked, as for any step of + # the open, and a refusal names the config dir, whose step it was. + return _open_where_no_link_can_be(path, base, root_real, exc.error, dir_step=True) # Another process holding the config dir open for delete, say: the fault is the dir's. # A dir gone since the listing leaves its files gone too, but a step of the hold can # report a name it did not find although the dir is there, so the dir is screened again. @@ -3862,7 +3866,7 @@ def _open_config_file( def _open_where_no_link_can_be( - path: Path, base: Path, root_real: Path, exc: OSError + path: Path, base: Path, root_real: Path, exc: OSError, *, dir_step: bool = False ) -> tuple[int, _Unchecked] | Literal["gone", "passed-over"]: """The config file ``path``, whose confined open failed with ``exc``, a code that says the volume does not do what a step of the open asked, opened by name as it was before vault @@ -3871,11 +3875,19 @@ def _open_where_no_link_can_be( volume answered, not through ``base`` again. Nothing is held, so at least a folder above ``root_real``, or ``root_real`` itself, swapped for a link before the open is still followed. A volume that reports it holds reparse points, or whose answer cannot be read, fails the - backup, naming the file, the cause and the remedy. The error keeps ``exc``'s codes. Its fixed - text is short, so with a file name of up to about 60 characters the remedy survives the - 200-character cut an alert and the audit row make; a longer name pushes the remedy past it.""" - name = scrub_log_argument(path.relative_to(base).as_posix()) - what = f"config file {name} not added" + backup, naming the file, the cause and the remedy; where ``dir_step`` says the step was the + hold of the config dir, it names the config dir instead, after the cause and the remedy. The + error keeps ``exc``'s codes. Its fixed text is short, so with a file name of up to about 60 + characters the remedy survives the 200-character cut an alert and the audit row make; a + longer name pushes the remedy past it.""" + name = _rel_name(path, base) + + def refused(reason: str) -> OSError: + if dir_step: + where = scrub_log_argument(str(base)) + return _refusal(exc, "config dir not held", reason, where) + return _error_like(exc, f"config file {name} not added", reason) + try: flags = _win_volume_flags(root_real) except OSError as query_exc: @@ -3883,14 +3895,14 @@ def _open_where_no_link_can_be( f"volume link support unreadable ({_error_code(query_exc)}); " "use local NTFS or ReFS or include_config = false" ) - raise _error_like(exc, what, reason) from query_exc + raise refused(reason) from query_exc if flags & _FILE_SUPPORTS_REPARSE_POINTS: # A local filter driver, or a share's client, refused the step. reason = ( - "volume can hold links yet refused a no-link open; " + "volume holds links but refused a no-link open; " "fix its filter or share, or include_config = false" ) - raise _error_like(exc, what, reason) from exc + raise refused(reason) from exc try: fd = os.open( root_real.joinpath(*path.relative_to(base).parts), diff --git a/messagefoundry/transports/file.py b/messagefoundry/transports/file.py index 82a8addebf..f2c08345da 100644 --- a/messagefoundry/transports/file.py +++ b/messagefoundry/transports/file.py @@ -3284,8 +3284,8 @@ def _open_confined( ``unverified``, where given, opts in to trusting a handle whose final path cannot be read (vault BACKLOG #6573); the file connector never passes it. On Windows the root is then held and refused if it names another path too, as each folder below it is (:func:`_win_hold_dirs`); a - root that cannot be held for any other reason raises :class:`_RootUnheld`, except a code in - ``_WIN_UNSUPPORTED``, which is raised as it came, as a step of the open. Once the file is + root that cannot be held for any other reason raises :class:`_RootUnheld`, keeping the hold's + codes, so a caller can tell a code in ``_WIN_UNSUPPORTED`` apart. Once the file is open, each held folder, the root included, is checked again by its handle before it is released, and the file is refused if any of them now names another path (:func:`_win_open_confined_rechecked`). That re-check sees one instant, so at least these go @@ -3315,8 +3315,6 @@ def _open_confined( except _Unconfined: raise except OSError as exc: - if getattr(exc, "winerror", None) in _WIN_UNSUPPORTED: - raise # the volume does not do what the hold asked: a step of the open raise _RootUnheld.from_error(exc) from exc try: fd = _win_open_confined_rechecked(root_real, parts, access) diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index e1a01f7dd1..e2efa2f38a 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -24,6 +24,7 @@ import pytest from messagefoundry.config.settings import BackupSettings, StoreSettings +from messagefoundry.controlchars import scrub_log_argument from messagefoundry.pipeline.cluster import NullCoordinator from messagefoundry.pipeline.dr_backup import BackupError, BackupResult, BackupRunner, _day_key from messagefoundry.store import MessageStore @@ -1914,7 +1915,7 @@ async def test_an_unsupported_open_step_on_a_volume_that_may_hold_links_fails_th if sys.platform == "win32": # POSIX keeps no Windows code on an OSError it builds assert "WinError 50" in text if volume == "holds-links": - assert "can hold links" in text and "filter or share" in text + assert "holds links" in text and "filter or share" in text else: assert "unreadable (WinError 5)" in text and "NTFS or ReFS" in text @@ -2037,6 +2038,32 @@ async def test_a_root_hold_the_volume_does_not_support_asks_the_volume_like_any_ ] +@pytest.mark.skipif(sys.platform != "win32", reason="the root hold is Windows-only") +@pytest.mark.parametrize("volume", ["holds-links", "query-fails"]) +async def test_a_root_hold_the_volume_does_not_support_on_a_volume_that_may_hold_links_names_the_dir( + tmp_path, key_b64, monkeypatch, volume +) -> None: + """When the hold of the config dir fails with a code saying the volume does not do what it + asked, and the volume reports it holds reparse points or its answer cannot be read, the + backup fails naming the config dir, whose step it was, after the cause and the remedy, and + not the first file, whose fault it is not (vault BACKLOG #6573). Before, the text named + ``feed.py``.""" + cfg, _host = _config_for_a_swap(tmp_path) + failed = _fail_the_root_hold(monkeypatch, _os_error(22, "Not supported", 50)) + answer: int | OSError = 0x80 if volume == "holds-links" else _os_error(5, "denied", 5) + asked = _fake_volume_flags(monkeypatch, answer) + with pytest.raises(BackupError) as raised: + await _pass_with_bytes(tmp_path, key_b64, cfg) + assert failed and asked == [cfg.resolve()], "the fault ran" + text = str(raised.value) + assert text.startswith("OSError: [WinError 50] config dir not held: volume "), text + assert "include_config = false" in text and "feed.py" not in text + # The dir comes after the remedy; the 200-character cut drops this test's long path whole. + err = raised.value.__cause__ + assert isinstance(err, OSError) + assert str(err).endswith(f"include_config = false: {scrub_log_argument(str(cfg))}"), err + + @pytest.mark.skipif(sys.platform != "win32", reason="the root hold is Windows-only") async def test_a_root_hold_that_reports_no_such_path_while_the_dir_is_there_fails_naming_it( tmp_path, key_b64, monkeypatch diff --git a/tests/test_file_open_confined_unverified.py b/tests/test_file_open_confined_unverified.py index 2e2020a763..1f9b81b4b6 100644 --- a/tests/test_file_open_confined_unverified.py +++ b/tests/test_file_open_confined_unverified.py @@ -401,12 +401,13 @@ def test_the_opt_in_names_the_root_when_another_handle_holds_it_open_for_delete( @_WINDOWS_ONLY @_VOLUME_CODES -def test_a_root_hold_the_volume_does_not_support_is_raised_as_it_came( +def test_a_root_hold_the_volume_does_not_support_is_raised_as_the_roots_keeping_its_code( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, winerror: int ) -> None: """A hold of the root that fails with a code saying the volume does not do what it asked is - a step of the open like any other, so it is raised as it came, not as the root's own fault, - and the caller can ask the volume whether it holds reparse points.""" + raised as the root's, keeping that code, so the caller can both ask the volume whether it + holds reparse points, as for any step of the open, and name the root rather than the file + when the answer fails the backup.""" root = tmp_path / "config" root.mkdir() (root / "a.toml").write_bytes(b"own") @@ -419,4 +420,5 @@ def hold(_root: Path, _dirs: tuple[str, ...], **_kwargs: bool) -> list[int]: fd, _st = file_mod._open_confined(root / "a.toml", root, root.resolve(), unverified=[]) os.close(fd) assert getattr(raised.value, "winerror", None) == winerror - assert not isinstance(raised.value, file_mod._RootUnheld) + assert isinstance(raised.value, file_mod._RootUnheld) + assert getattr(raised.value.error, "winerror", None) == winerror From dd9f38e2a0336e29e58734f87cbb296213ab4cc6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:07:07 -0600 Subject: [PATCH 23/49] dr_backup: a config refusal puts its cause and remedy before the name, lengths measured (BACKLOG #6573) The docstring said a file name of up to about 60 characters left the remedy inside the 200-character cut. It left out the class and code prefixes, so the real figure was about 53, and an ordinary relative name pushed the remedy out of the audit row and the alert. Every refusal of a config file or the config dir on the walk's open steps now reads ": : ", the dir's sharing-violation refusal included, so the cut takes the name, whole, before the remedy. The final-path cause is shortened. The lengths are measured from the final text as safe_exc renders it twice, as BackupError and the audit row do: a name survives whole up to 55 to 68 characters by arm, 30 for the final-path refusal. A test pins each arm's length through safe_exc at the 200-character cut, one longer, and a 150-character name. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 37 ++++++----- tests/test_backup_runner.py | 98 +++++++++++++++++++++++++++- 2 files changed, 117 insertions(+), 18 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 72956339b6..bbed433338 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -3834,11 +3834,13 @@ def _open_config_file( raise _config_dir_error(base, exc) from exc except _FinalPathUnread as exc: # The file is open and regular; only the query for its final path failed, which at least a - # volume with no drive letter does for every file, so the text names that and the remedy. + # volume with no drive letter does for every file, so the text names that and the remedy, + # before the name; as safe_exc renders it, a name of up to 30 characters survives whole + # the 200-character cut _open_where_no_link_can_be names. if getattr(exc, "winerror", None) != _ERROR_PATH_NOT_FOUND: raise _config_file_error(path, base, exc.error) from exc reason = ( - "final path unreadable, as at least on a volume with no drive letter; " + "final path unreadable, as without a drive letter; " "assign the volume a drive letter, or set include_config = false" ) raise _refusal(exc.error, "config file not added", reason, _rel_name(path, base)) from exc @@ -3876,17 +3878,20 @@ def _open_where_no_link_can_be( ``root_real``, or ``root_real`` itself, swapped for a link before the open is still followed. A volume that reports it holds reparse points, or whose answer cannot be read, fails the backup, naming the file, the cause and the remedy; where ``dir_step`` says the step was the - hold of the config dir, it names the config dir instead, after the cause and the remedy. The - error keeps ``exc``'s codes. Its fixed text is short, so with a file name of up to about 60 - characters the remedy survives the 200-character cut an alert and the audit row make; a - longer name pushes the remedy past it.""" - name = _rel_name(path, base) + hold of the config dir, it names the config dir instead. The error keeps ``exc``'s codes. + The name comes last (:func:`_refusal`), so the cause and the remedy survive the + 200-character cut the ``dr_backup`` audit row's error makes, whatever the name's length. As + ``safe_exc`` renders the error, its class included, with a Windows code of up to two digits + for the step and for the volume query, the text before the name is at most 145 characters, + so a name of up to 55 characters survives whole beside them, and a longer one with no space + in it is dropped whole (``tests/test_backup_runner.py`` pins each arm's length). Where the + failed run also left its staging behind, that row's error starts with 18 more characters, + and the alert's text starts with the leftover, so neither is measured here.""" def refused(reason: str) -> OSError: if dir_step: - where = scrub_log_argument(str(base)) - return _refusal(exc, "config dir not held", reason, where) - return _error_like(exc, f"config file {name} not added", reason) + return _refusal(exc, "config dir not held", reason, scrub_log_argument(str(base))) + return _refusal(exc, "config file not added", reason, _rel_name(path, base)) try: flags = _win_volume_flags(root_real) @@ -3960,17 +3965,17 @@ def _reader_over(fd: int) -> io.BufferedReader: def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: """The error that fails the backup for the config file ``path``, naming it relative to ``base`` and keeping ``exc``'s errno, its Windows code where it has one, and its text.""" - name = scrub_log_argument(path.relative_to(base).as_posix()) - return _error_like(exc, f"the config file {name} could not be added to the backup", None) + what = f"the config file {_rel_name(path, base)} could not be added to the backup" + return _error_like(exc, what, None) def _config_dir_error(base: Path, exc: OSError) -> OSError: """The error that fails the backup when the config dir ``base`` itself could not be held as itself (vault BACKLOG #6573), naming the dir rather than a file under it, and keeping - ``exc``'s codes and text. A long path can push the text past the 200-character cut an alert - and the audit row make; the Windows code, ahead of the path, survives it.""" - what = f"the config dir {scrub_log_argument(str(base))} could not be held" - return _error_like(exc, what, None) + ``exc``'s codes and text. The dir comes after the system's text (:func:`_refusal`), so the + 200-character cut an alert and the audit row make takes a long path before the cause.""" + cause = exc.strerror if exc.strerror is not None else str(exc) + return _refusal(exc, "config dir not held", cause, scrub_log_argument(str(base))) def _rel_name(path: Path, base: Path) -> str: diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index e2efa2f38a..2e9ba3bd79 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1999,6 +1999,100 @@ def open_by_name(path, flags, *args, **kwargs): os.fstat(reached[0]) # closed +#: Each refusal of a config file or the config dir whose cause and remedy must survive the cut: +#: what the confined open raises, what the volume answers, the text that must survive, whether +#: the dir is named rather than the file, and the longest name that survives whole beside them. +_REFUSALS = { + "file-holds-links": ("step", 0x80, "fix its filter or share, or include_config = false", 0), + "file-unreadable": ("step", 5, "use local NTFS or ReFS or include_config = false", 0), + "dir-holds-links": ("root", 0x80, "fix its filter or share, or include_config = false", 1), + "dir-unreadable": ("root", 5, "use local NTFS or ReFS or include_config = false", 1), + "dir-held-open": ("held", None, "being used by another process", 1), + "final-path": ( + "final", + None, + "assign the volume a drive letter, or set include_config = false", + 0, + ), +} + + +@pytest.mark.skipif(sys.platform != "win32", reason="the steps that reach these are Windows-only") +@pytest.mark.parametrize( + ("arm", "survives"), + [ + ("file-holds-links", 55), + ("file-unreadable", 59), + ("dir-holds-links", 57), + ("dir-unreadable", 61), + ("dir-held-open", 68), + ("final-path", 30), + ], +) +def test_a_config_refusal_keeps_its_cause_and_remedy_through_the_200_character_cut( + tmp_path, monkeypatch, arm, survives +) -> None: + """A refusal of a config file or of the config dir puts the cause and the remedy before the + name, so the text an alert and the ``dr_backup`` audit row keep, cut at 200 characters by + ``safe_exc``, holds them whatever the name's length (vault BACKLOG #6573). Before, the name + came first and a name of ordinary length pushed the remedy past the cut. The name itself + survives whole up to the length the docstrings state, and one character longer it is + dropped whole: the measured lengths are pinned here, so a longer text moves them.""" + from messagefoundry.pipeline import dr_backup + from messagefoundry.redaction import safe_exc + from messagefoundry.transports import file as file_mod + + kind, answer, kept, names_dir = _REFUSALS[arm] + step = _os_error(22, "Not supported", 50) + raised = { + "step": step, + "root": file_mod._RootUnheld.from_error(step), + "held": file_mod._RootUnheld.from_error( + _os_error( + 13, + "The process cannot access the file because it is being used by another process", + 32, + ) + ), + "final": file_mod._FinalPathUnread.from_error( + _os_error(2, "The system cannot find the path specified", 3) + ), + }[kind] + + def open_confined(*_args: object, **_kwargs: object) -> tuple[int, os.stat_result]: + raise raised + + monkeypatch.setattr(dr_backup, "_open_confined", open_confined) + if answer is not None: + _fake_volume_flags(monkeypatch, answer if answer != 5 else _os_error(5, "denied", 5)) + monkeypatch.chdir(tmp_path) + + def rendered(length: int) -> tuple[str, str]: + # A relative name of ``length`` characters: the config dir's when the dir is named, + # else the file's below a one-letter dir. + name = "c" * length if names_dir else "c" * (length - 5) + ".toml" + base = Path(name) if names_dir else Path("d") + path = base / ("a.toml" if names_dir else name) + base.mkdir() + path.write_bytes(b"own") + try: + with pytest.raises(OSError) as err: + dr_backup._open_config_file(path, base, base.resolve()) + finally: + path.unlink() + base.rmdir() + # What an alert and the audit row record: the failure as safe_exc renders it, which + # BackupError carries and safe_exc renders again, each cut at 200 characters. + return name, safe_exc(BackupError("write", safe_exc(err.value))) + + name, text = rendered(survives) + assert kept in text and text.endswith(f": {name}"), text + name, text = rendered(survives + 1) + assert kept in text and name not in text, text + name, text = rendered(150) + assert kept in text and name not in text, text + + def _fail_the_root_hold(monkeypatch: pytest.MonkeyPatch, exc: OSError) -> list[Path]: """Fail the confined open's hold of the config dir itself with ``exc``, and leave every other hold alone. Returns the list each failed hold appends the dir to.""" @@ -2078,7 +2172,7 @@ async def test_a_root_hold_that_reports_no_such_path_while_the_dir_is_there_fail with pytest.raises(BackupError) as raised: await _pass_with_bytes(tmp_path, key_b64, cfg) assert failed, "the fault ran" - assert "the config dir" in str(raised.value) and "could not be held" in str(raised.value) + assert "config dir not held: The system cannot find the path" in str(raised.value) @pytest.mark.skipif(sys.platform != "win32", reason="a Windows sharing violation") @@ -2098,7 +2192,7 @@ async def test_a_config_dir_another_handle_holds_open_for_delete_fails_naming_th finally: _close(handle) text = str(raised.value) - assert "the config dir" in text and "could not be held" in text and "WinError 32" in text + assert "config dir not held" in text and "WinError 32" in text assert "feed.py" not in text (tmp_path / "control").mkdir() _result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) From b2d71033f06b8694e753e48a2fcbb054aca9bc43 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:08:39 -0600 Subject: [PATCH 24/49] docs: the include_config row names the order of each refusal's text (BACKLOG #6573) The row now says that a final-path query failing with ERROR_PATH_NOT_FOUND, which at least a volume with no drive letter gives, names the query and the remedy; that a refusal after an unsupported root hold names the config dir; that an open by name reaching no regular file is passed over; and that each refusal gives the cause and any remedy before the name, so the audit row's 200-character cut drops a long name rather than them. Only the include_config row changes. Proposed PR title: DR config walk: refusals lead with cause and remedy, a refused root hold names the dir, an open by name passes a folder over (BACKLOG #6573) Proposed vault banner: PARTIAL, round 5 on engine branch b20053-6573e, stacked on b20053-6573d: the by-name open checks its descriptor; a refused root hold names the config dir; a volume with no drive letter gets a remedy; refusals lead with cause and remedy, with lengths pinned by test. Round-3 findings F2, F3, F5 and the rest are owed, as is a GUID volume-name fallback for the final-path check. Verified-by: none --- docs/CONFIGURATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 1869b88234..8ec060c4be 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the file, the cause and the remedy: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and the remedy: assign the volume a drive letter, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these failures, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | From 89b3861da970f1b46b9cb8a17e1280afa39a691d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:33:51 -0600 Subject: [PATCH 25/49] dr_backup: repair round 1 on the config refusals (BACKLOG #6573) Review round 1 (code-review xhigh) found, and this fixes: - A final-path query failing with ERROR_PATH_NOT_FOUND, and a root hold the volume does not support, skipped the screen of the file's name that every other failed open runs, so a name gone or swapped since the listing failed the backup where the base branch left it out or passed it over. Both now take that screen first. - The final-path remedy named a cause the walk never checked. It now reads as a condition: if the volume has no drive letter, assign it one, or set include_config = false. - The config dir's refusal kept the period Windows ends its text with, and read ".:" before the dir. Its docstring named an alert's cut, which a staging leftover can lead. - The fstat comment claimed a POSIX path production never reaches; the _open_confined docstring paragraph is reflowed to 100 columns. - The length test used Windows' own sharing-violation text, and a long name short enough to stay under MAX_PATH; the final-path length is now 41. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 102 +++++++++++++++------------ messagefoundry/transports/file.py | 25 ++++--- tests/test_backup_runner.py | 94 +++++++++++++++++++++--- 3 files changed, 150 insertions(+), 71 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index bbed433338..bd67b3c1cf 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -3813,58 +3813,61 @@ def _open_config_file( if not stat.S_ISREG(st.st_mode) or _stat_names_another_path(st): return "passed-over" unverified: list[OSError] = [] + dir_step = False try: fd, _st = _open_confined(path, base, root_real, unverified=unverified) except (_Unconfined, _Replaced): return "passed-over" except _RootUnheld as exc: - if getattr(exc, "winerror", None) in _WIN_UNSUPPORTED: - # The volume does not do what the hold asked: the volume is asked, as for any step of - # the open, and a refusal names the config dir, whose step it was. - return _open_where_no_link_can_be(path, base, root_real, exc.error, dir_step=True) - # Another process holding the config dir open for delete, say: the fault is the dir's. - # A dir gone since the listing leaves its files gone too, but a step of the hold can - # report a name it did not find although the dir is there, so the dir is screened again. - if is_absent(exc.error): - try: - root_real.lstat() - except OSError as screen_exc: - if is_absent(screen_exc): - return "gone" - raise _config_dir_error(base, exc) from exc - except _FinalPathUnread as exc: - # The file is open and regular; only the query for its final path failed, which at least a - # volume with no drive letter does for every file, so the text names that and the remedy, - # before the name; as safe_exc renders it, a name of up to 30 characters survives whole - # the 200-character cut _open_where_no_link_can_be names. - if getattr(exc, "winerror", None) != _ERROR_PATH_NOT_FOUND: - raise _config_file_error(path, base, exc.error) from exc - reason = ( - "final path unreadable, as without a drive letter; " - "assign the volume a drive letter, or set include_config = false" - ) - raise _refusal(exc.error, "config file not added", reason, _rel_name(path, base)) from exc + if getattr(exc, "winerror", None) not in _WIN_UNSUPPORTED: + # Another process holding the config dir open for delete, say: the dir's fault. A dir + # gone since the listing leaves its files gone too, but a step of the hold can report + # a name it did not find although the dir is there, so the dir is screened again. + if is_absent(exc.error): + try: + root_real.lstat() + except OSError as screen_exc: + if is_absent(screen_exc): + return "gone" + raise _config_dir_error(base, exc) from exc + # The volume does not do what the hold asked: a step of the open, as below, except that a + # refusal names the config dir, whose step it was. + failed: OSError = exc + dir_step = True except OSError as exc: if isinstance(exc, FileNotFoundError) and not is_absent(exc): # A share or network path that cannot be reached, which Windows maps to ENOENT: the # file was there at the screen, so this is a fault, as the add by name met it before. raise _config_file_error(path, base, exc) from exc - # Windows refuses to open a folder or a junction as a file with ERROR_ACCESS_DENIED, and a - # step of the confined open can report a name it did not find although the file is there, - # so the name is screened again rather than read from the error. - try: - again = path.lstat() - except OSError as screen_exc: - if is_absent(screen_exc): - return "gone" - raise _config_file_error(path, base, screen_exc) from screen_exc - if not stat.S_ISREG(again.st_mode) or _stat_names_another_path(again): - return "passed-over" - if getattr(exc, "winerror", None) in _WIN_UNSUPPORTED: - # The volume does not do what a step of the open asked. - return _open_where_no_link_can_be(path, base, root_real, exc) - raise _config_file_error(path, base, exc) from exc - return fd, _Unchecked(False, unverified[0]) if unverified else None + failed = exc + else: + return fd, _Unchecked(False, unverified[0]) if unverified else None + # Windows refuses to open a folder or a junction as a file with ERROR_ACCESS_DENIED, and a + # step of the confined open can report a name it did not find although the file is there, so + # the name is screened again rather than read from the error. + try: + again = path.lstat() + except OSError as screen_exc: + if is_absent(screen_exc): + return "gone" + raise _config_file_error(path, base, screen_exc) from screen_exc + if not stat.S_ISREG(again.st_mode) or _stat_names_another_path(again): + return "passed-over" + winerror = getattr(failed, "winerror", None) + if winerror in _WIN_UNSUPPORTED: + # The volume does not do what a step of the open asked. + return _open_where_no_link_can_be(path, base, root_real, failed, dir_step=dir_step) + if isinstance(failed, _FinalPathUnread) and winerror == _ERROR_PATH_NOT_FOUND: + # The file was open and regular; only the query for its final path failed, which at least + # a volume with no drive letter does for every file, so the text names that and a remedy, + # before the name (_open_where_no_link_can_be says which cut that is for). As safe_exc + # renders it, a name of up to 41 characters survives that cut whole. + reason = ( + "final path unreadable; if the volume has no drive letter, " + "assign it one, or set include_config = false" + ) + raise _refusal(failed, "config file not added", reason, _rel_name(path, base)) from failed + raise _config_file_error(path, base, failed) from failed def _open_where_no_link_can_be( @@ -3925,8 +3928,10 @@ def refused(reason: str) -> OSError: if not stat.S_ISREG(again.st_mode) or _stat_names_another_path(again): return "passed-over" raise _config_file_error(path, base, open_exc) from open_exc - # POSIX opens a name swapped for a folder, so what was opened is checked by its descriptor, - # as the confined open checks it, before a reader that would fail the backup is built on it. + # What was opened is checked by its descriptor, as the confined open checks it, before a + # reader is built on it: a reader over a folder fails the whole backup. Only Windows reaches + # this open, where os.open refuses a folder, so this guards at least an object such as a + # device; POSIX os.open would open a folder, which the tests fake here. try: regular = stat.S_ISREG(os.fstat(fd).st_mode) except OSError as stat_exc: @@ -3972,10 +3977,13 @@ def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: def _config_dir_error(base: Path, exc: OSError) -> OSError: """The error that fails the backup when the config dir ``base`` itself could not be held as itself (vault BACKLOG #6573), naming the dir rather than a file under it, and keeping - ``exc``'s codes and text. The dir comes after the system's text (:func:`_refusal`), so the - 200-character cut an alert and the audit row make takes a long path before the cause.""" + ``exc``'s codes and text, less the period Windows ends it with. The dir comes after that text + (:func:`_refusal`), so the 200-character cut the ``dr_backup`` audit row's error makes takes a + long path before the cause.""" cause = exc.strerror if exc.strerror is not None else str(exc) - return _refusal(exc, "config dir not held", cause, scrub_log_argument(str(base))) + return _refusal( + exc, "config dir not held", cause.rstrip().removesuffix("."), scrub_log_argument(str(base)) + ) def _rel_name(path: Path, base: Path) -> str: diff --git a/messagefoundry/transports/file.py b/messagefoundry/transports/file.py index f2c08345da..13e29b0f55 100644 --- a/messagefoundry/transports/file.py +++ b/messagefoundry/transports/file.py @@ -3282,19 +3282,18 @@ def _open_confined( the delete then act on. POSIX ignores it: there they act relative to the parent's descriptor. ``unverified``, where given, opts in to trusting a handle whose final path cannot be read (vault - BACKLOG #6573); the file connector never passes it. On Windows the root is then held and - refused if it names another path too, as each folder below it is (:func:`_win_hold_dirs`); a - root that cannot be held for any other reason raises :class:`_RootUnheld`, keeping the hold's - codes, so a caller can tell a code in ``_WIN_UNSUPPORTED`` apart. Once the file is - open, each held folder, the root included, is checked again by its handle before it is - released, and the file is refused if any of them now names another path - (:func:`_win_open_confined_rechecked`). That re-check sees one instant, so at least these go - undetected: a folder swapped for a link and back between the open and the re-check, and a - folder above the root. When the query for the final path then fails with a code in ``_WIN_UNSUPPORTED``, after - the regular-file check passed, the descriptor is returned all the same and the query's error - appended to ``unverified``; any other failure of that query raises :class:`_FinalPathUnread`. - A final path that is - read and names another path is still refused. + BACKLOG #6573); the file connector never passes it. On Windows the root is then held and refused + if it names another path too, as each folder below it is (:func:`_win_hold_dirs`); a root that + cannot be held for any other reason raises :class:`_RootUnheld`, keeping the hold's codes, so a + caller can tell a code in ``_WIN_UNSUPPORTED`` apart. Once the file is open, each held folder, + the root included, is checked again by its handle before it is released, and the file is refused + if any of them now names another path (:func:`_win_open_confined_rechecked`). That re-check sees + one instant, so at least these go undetected: a folder swapped for a link and back between the + open and the re-check, and a folder above the root. When the query for the final path then fails + with a code in ``_WIN_UNSUPPORTED``, after the regular-file check passed, the descriptor is + returned all the same and the query's error appended to ``unverified``; any other failure of + that query raises :class:`_FinalPathUnread`. A final path that is read and names another path is + still refused. Either way a link that stays inside the root is refused too. A hard link is not: see :func:`_pin_confined` for why.""" diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index 2e9ba3bd79..43ab891f6e 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1566,6 +1566,67 @@ def lstat(path, *args, **kwargs): return faulted +@pytest.mark.skipif(sys.platform != "win32", reason="the steps that raise these are Windows-only") +@pytest.mark.parametrize("step", ["final-path", "root-hold"]) +@pytest.mark.parametrize("screen", ["gone", "folder"]) +async def test_a_name_gone_or_swapped_after_a_failed_final_path_or_root_hold_is_screened_again( + tmp_path, key_b64, monkeypatch, step, screen +) -> None: + """A final-path query that fails with ERROR_PATH_NOT_FOUND, or a hold of the config dir + the volume does not support on a volume that reports it holds links, is screened again by + the file's name first, as any other failed open is: a name gone since the listing leaves the + file out unrecorded, and a name now a folder passes it over, and the backup succeeds, rather + than failing it as a refusal (vault BACKLOG #6573). The control is each fault with the name + still a regular file, which fails the backup.""" + from messagefoundry.transports import file as file_mod + + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + if step == "final-path": + fault: OSError = file_mod._FinalPathUnread.from_error( + _os_error(2, "The system cannot find the path specified", 3) + ) + else: + fault = file_mod._RootUnheld.from_error(_os_error(22, "Not supported", 50)) + _fake_volume_flags(monkeypatch, 0x80) + + (tmp_path / "control").mkdir() + faulted = _fault_the_open(monkeypatch, checked, fault) + with pytest.raises(BackupError): + await _pass_with_bytes(tmp_path / "control", key_b64, cfg) + assert faulted == [checked], "the control's fault ran" + monkeypatch.undo() + + if step == "root-hold": + _fake_volume_flags(monkeypatch, 0x80) + if screen == "gone": + faulted = _fault_the_open_and_its_screen( + monkeypatch, checked, fault, _os_error(2, "No such file or directory") + ) + else: + faulted = _fault_the_open(monkeypatch, checked, fault) + real_lstat = os.lstat + key = os.path.normcase(os.fspath(checked)) + + def lstat(path, *args, **kwargs): + if ( + faulted + and not args + and not kwargs + and isinstance(path, (str, os.PathLike)) + and os.path.normcase(os.fspath(path)) == key + ): + return real_lstat(cfg / "sub") # a folder now + return real_lstat(path, *args, **kwargs) + + monkeypatch.setattr(os, "lstat", lstat) + result, names, _bytes = await _pass_with_bytes(tmp_path, key_b64, cfg) + assert faulted == [checked], "the fault ran" + assert "config/swapped.toml" not in names + expected = () if screen == "gone" else ("swapped.toml",) + assert result.config_skipped_files == expected + + @pytest.mark.parametrize("winerror", [53, 67], ids=["bad-netpath", "bad-net-name"]) async def test_a_config_file_on_an_unreachable_share_fails_the_backup( tmp_path, key_b64, monkeypatch, winerror @@ -1631,6 +1692,19 @@ async def test_a_config_file_whose_screen_fails_after_a_failed_open_fails_the_ba assert faulted == [checked], "the fault ran" +def test_the_error_that_fails_the_backup_for_the_config_dir_drops_the_period_before_the_dir( + tmp_path, +) -> None: + """The error that fails the backup when the config dir could not be held gives the system's + text without the period Windows ends it with, then the dir, so it does not read ``.:`` + (vault BACKLOG #6573). Its codes are kept.""" + from messagefoundry.pipeline.dr_backup import _config_dir_error + + err = _config_dir_error(tmp_path, _os_error(13, "Access is denied.", 5)) + assert str(err.strerror) == f"config dir not held: Access is denied: {tmp_path}" + assert err.errno == 13 + + def test_the_error_that_fails_the_backup_for_a_config_file_keeps_its_codes(tmp_path) -> None: """The error that fails the backup for a config file names the file relative to the config dir and keeps the errno and, on Windows, the Windows code of the error it replaces, so the @@ -1803,7 +1877,7 @@ async def test_a_config_file_whose_final_path_query_fails_otherwise_fails_the_ba assert not [r for r in caplog.records if "could not report" in r.getMessage()] text = str(raised.value) assert "swapped.toml" in text and f"WinError {winerror}" in text - remedy = "assign the volume a drive letter, or set include_config = false" + remedy = "if the volume has no drive letter, assign it one, or set include_config = false" assert (remedy in text) is (winerror == 3), text assert ("final path" in text) is (winerror == 3), text @@ -2011,7 +2085,7 @@ def open_by_name(path, flags, *args, **kwargs): "final-path": ( "final", None, - "assign the volume a drive letter, or set include_config = false", + "if the volume has no drive letter, assign it one, or set include_config = false", 0, ), } @@ -2026,7 +2100,7 @@ def open_by_name(path, flags, *args, **kwargs): ("dir-holds-links", 57), ("dir-unreadable", 61), ("dir-held-open", 68), - ("final-path", 30), + ("final-path", 41), ], ) def test_a_config_refusal_keeps_its_cause_and_remedy_through_the_200_character_cut( @@ -2038,6 +2112,8 @@ def test_a_config_refusal_keeps_its_cause_and_remedy_through_the_200_character_c came first and a name of ordinary length pushed the remedy past the cut. The name itself survives whole up to the length the docstrings state, and one character longer it is dropped whole: the measured lengths are pinned here, so a longer text moves them.""" + import ctypes + from messagefoundry.pipeline import dr_backup from messagefoundry.redaction import safe_exc from messagefoundry.transports import file as file_mod @@ -2047,13 +2123,8 @@ def test_a_config_refusal_keeps_its_cause_and_remedy_through_the_200_character_c raised = { "step": step, "root": file_mod._RootUnheld.from_error(step), - "held": file_mod._RootUnheld.from_error( - _os_error( - 13, - "The process cannot access the file because it is being used by another process", - 32, - ) - ), + # Windows' own text, which ends in a period. + "held": file_mod._RootUnheld.from_error(ctypes.WinError(32)), "final": file_mod._FinalPathUnread.from_error( _os_error(2, "The system cannot find the path specified", 3) ), @@ -2089,7 +2160,8 @@ def rendered(length: int) -> tuple[str, str]: assert kept in text and text.endswith(f": {name}"), text name, text = rendered(survives + 1) assert kept in text and name not in text, text - name, text = rendered(150) + # Long, but short enough that the file's path stays under MAX_PATH under tmp_path. + name, text = rendered(120) assert kept in text and name not in text, text From 7ec73d8d51459c6d606005eb6d0b46784243ed6b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:34:40 -0600 Subject: [PATCH 26/49] docs: the include_config row gives the final-path remedy as a condition (BACKLOG #6573) The ERROR_PATH_NOT_FOUND remedy now reads as the refusal does: if the volume has no drive letter, assign it one, or set include_config = false. The row also says that the screen of the name after a failed open covers that final-path failure and a refused hold of the config dir. Only the include_config row changes. Proposed PR title: DR config walk: refusals lead with cause and remedy, a refused root hold names the dir, an open by name passes a folder over (BACKLOG #6573) Proposed vault banner: PARTIAL, round 5 on engine branch b20053-6573e, stacked on b20053-6573d: the by-name open checks its descriptor; a refused root hold names the config dir; a final path a volume with no drive letter cannot give gets a remedy; refusals lead with cause and remedy, lengths pinned by test. Round-3 findings F2, F3, F5 and the rest are owed, as are a GUID volume-name fallback for the final-path check and the round-5 review findings left open. Verified-by: none --- docs/CONFIGURATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 8ec060c4be..2baaf9cb98 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and the remedy: assign the volume a drive letter, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these failures, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and a remedy: if the volume has no drive letter, assign it one, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails, that final-path failure and a refused hold of the config dir included, and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these failures, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | From 0fc8356bc8d2ef32790c7b7c5d6a5a539d32efd5 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:47:52 -0600 Subject: [PATCH 27/49] dr_backup: repair round 2 on the config refusals (BACKLOG #6573) Review round 2 (code-review xhigh) found, and this fixes: - A final-path query that failed because its share could not be reached came wrapped in _FinalPathUnread, which the unreachable-share guard did not see through, so a screen that then read the name as gone left the file out unrecorded. The guard now reads the wrapped error, and the backup fails naming the file, as on the base branch. - The ERROR_PATH_NOT_FOUND constant is file.py's _WIN_PATH_NOT_FOUND, imported with the others, not a third copy. - The config dir's refusal is built in one place, _config_dir_error, which now takes the reason the volume arm gives. - The length test shows a name one character too long is dropped whole, not cut part-way. Verified-by: tests --- messagefoundry/pipeline/dr_backup.py | 24 ++++++++++------------ tests/test_backup_runner.py | 30 ++++++++++++++++++++++++++-- 2 files changed, 39 insertions(+), 15 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index bd67b3c1cf..28ecce1b27 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -114,6 +114,7 @@ _FLAG_OPEN_REPARSE_POINT, _NAME_SURROGATE, _SHARE_ALL, + _WIN_PATH_NOT_FOUND, _WIN_UNSUPPORTED, _attribute_tag, _fd_for, @@ -3784,11 +3785,6 @@ class _Unchecked(NamedTuple): error: OSError -#: Windows ERROR_PATH_NOT_FOUND, which at least a volume with no drive letter gives for a query of -#: a file's final path. -_ERROR_PATH_NOT_FOUND = 3 - - def _open_config_file( path: Path, base: Path, root_real: Path ) -> tuple[int, _Unchecked | None] | Literal["gone", "passed-over"]: @@ -3835,7 +3831,9 @@ def _open_config_file( failed: OSError = exc dir_step = True except OSError as exc: - if isinstance(exc, FileNotFoundError) and not is_absent(exc): + # The final-path query's own failure is wrapped in the class that names its step. + cause = exc.error if isinstance(exc, _FinalPathUnread) else exc + if isinstance(cause, FileNotFoundError) and not is_absent(cause): # A share or network path that cannot be reached, which Windows maps to ENOENT: the # file was there at the screen, so this is a fault, as the add by name met it before. raise _config_file_error(path, base, exc) from exc @@ -3857,7 +3855,7 @@ def _open_config_file( if winerror in _WIN_UNSUPPORTED: # The volume does not do what a step of the open asked. return _open_where_no_link_can_be(path, base, root_real, failed, dir_step=dir_step) - if isinstance(failed, _FinalPathUnread) and winerror == _ERROR_PATH_NOT_FOUND: + if isinstance(failed, _FinalPathUnread) and winerror == _WIN_PATH_NOT_FOUND: # The file was open and regular; only the query for its final path failed, which at least # a volume with no drive letter does for every file, so the text names that and a remedy, # before the name (_open_where_no_link_can_be says which cut that is for). As safe_exc @@ -3893,7 +3891,7 @@ def _open_where_no_link_can_be( def refused(reason: str) -> OSError: if dir_step: - return _refusal(exc, "config dir not held", reason, scrub_log_argument(str(base))) + return _config_dir_error(base, exc, reason) return _refusal(exc, "config file not added", reason, _rel_name(path, base)) try: @@ -3974,13 +3972,13 @@ def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: return _error_like(exc, what, None) -def _config_dir_error(base: Path, exc: OSError) -> OSError: +def _config_dir_error(base: Path, exc: OSError, reason: str | None = None) -> OSError: """The error that fails the backup when the config dir ``base`` itself could not be held as itself (vault BACKLOG #6573), naming the dir rather than a file under it, and keeping - ``exc``'s codes and text, less the period Windows ends it with. The dir comes after that text - (:func:`_refusal`), so the 200-character cut the ``dr_backup`` audit row's error makes takes a - long path before the cause.""" - cause = exc.strerror if exc.strerror is not None else str(exc) + ``exc``'s codes. It gives ``reason``, else ``exc``'s text less the period Windows ends it + with. The dir comes after that (:func:`_refusal`), so the 200-character cut the ``dr_backup`` + audit row's error makes takes a long path before the cause.""" + cause = reason if reason is not None else exc.strerror if exc.strerror is not None else str(exc) return _refusal( exc, "config dir not held", cause.rstrip().removesuffix("."), scrub_log_argument(str(base)) ) diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index 43ab891f6e..85205d3be4 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1627,6 +1627,31 @@ def lstat(path, *args, **kwargs): assert result.config_skipped_files == expected +@pytest.mark.skipif(sys.platform != "win32", reason="the final-path query is Windows-only") +@pytest.mark.parametrize("winerror", [53, 67], ids=["bad-netpath", "bad-net-name"]) +async def test_a_final_path_query_on_an_unreachable_share_fails_the_backup_whatever_the_screen( + tmp_path, key_b64, monkeypatch, winerror +) -> None: + """A final-path query that fails because the share cannot be reached is a fault, as the open + that meets it is, so the backup fails naming the file even when the screen of the name then + reads it as gone, rather than leaving the file out unrecorded (vault BACKLOG #6573). The + query's failure comes wrapped in the class that names its step, which must not hide it.""" + from messagefoundry.transports import file as file_mod + + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + share = _os_error(2, "The network path was not found", winerror) + faulted = _fault_the_open_and_its_screen( + monkeypatch, + checked, + file_mod._FinalPathUnread.from_error(share), + _os_error(2, "No such file or directory"), + ) + with pytest.raises(BackupError, match="swapped.toml"): + await _pass_with_bytes(tmp_path, key_b64, cfg) + assert faulted == [checked], "the fault ran" + + @pytest.mark.parametrize("winerror", [53, 67], ids=["bad-netpath", "bad-net-name"]) async def test_a_config_file_on_an_unreachable_share_fails_the_backup( tmp_path, key_b64, monkeypatch, winerror @@ -2158,11 +2183,12 @@ def rendered(length: int) -> tuple[str, str]: name, text = rendered(survives) assert kept in text and text.endswith(f": {name}"), text + # Dropped whole: no part of the name, which is all "c", follows its colon. name, text = rendered(survives + 1) - assert kept in text and name not in text, text + assert kept in text and ": c" not in text, text # Long, but short enough that the file's path stays under MAX_PATH under tmp_path. name, text = rendered(120) - assert kept in text and name not in text, text + assert kept in text and ": c" not in text, text def _fail_the_root_hold(monkeypatch: pytest.MonkeyPatch, exc: OSError) -> list[Path]: From 8ac775b7f4089326a7b0295547d5086fa27fad19 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:48:21 -0600 Subject: [PATCH 28/49] docs: the include_config row screens a name only after a hold refused as unsupported (BACKLOG #6573) Review round 2 found the row said a name gone after any refused hold of the config dir is left out unrecorded. Only a hold refused with one of the three unsupported-volume codes screens the name; any other refused hold fails the backup naming the dir, as the row says further on. The sentence on what comes before the name now says refusals, not failures, since a file's other failures still name it first. Only the include_config row changes. Proposed PR title: DR config walk: refusals lead with cause and remedy, a refused root hold names the dir, an open by name passes a folder over (BACKLOG #6573) Proposed vault banner: PARTIAL, round 5 on engine branch b20053-6573e, stacked on b20053-6573d: the by-name open checks its descriptor; a refused root hold names the config dir; a final path a volume with no drive letter cannot give gets a remedy; refusals lead with cause and remedy, lengths pinned by test. Round-3 findings F2, F3, F5 and the rest are owed, as are a GUID volume-name fallback for the final-path check and the round-5 review findings left open. Verified-by: none --- docs/CONFIGURATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 2baaf9cb98..5ca2f96196 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and a remedy: if the volume has no drive letter, assign it one, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails, that final-path failure and a refused hold of the config dir included, and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these failures, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and a remedy: if the volume has no drive letter, assign it one, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails, that final-path failure and a hold of the config dir refused with one of the three codes below included, and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these refusals, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | From da0571f3c910fe06772cdef4308afe95b197f153 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:52:59 -0600 Subject: [PATCH 29/49] tests: the length test builds Windows' own text where mypy can see the platform (BACKLOG #6573) ctypes.WinError exists only on Windows, so the tests mypy leg, which runs for linux, refused the call. The test is Windows-only by its skip; a platform check now narrows it for mypy too. Test only. Proposed PR title: DR config walk: refusals lead with cause and remedy, a refused root hold names the dir, an open by name passes a folder over (BACKLOG #6573) Proposed vault banner: PARTIAL, round 5 on engine branch b20053-6573e, stacked on b20053-6573d: the by-name open checks its descriptor; a refused root hold names the config dir; a final path a volume with no drive letter cannot give gets a remedy; refusals lead with cause and remedy, lengths pinned by test. Round-3 findings F2, F3, F5 and the rest are owed, as are a GUID volume-name fallback for the final-path check and the round-5 review findings left open. Verified-by: tests --- tests/test_backup_runner.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index 85205d3be4..ada7d61344 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -2145,11 +2145,14 @@ def test_a_config_refusal_keeps_its_cause_and_remedy_through_the_200_character_c kind, answer, kept, names_dir = _REFUSALS[arm] step = _os_error(22, "Not supported", 50) + if sys.platform == "win32": # always, by the skip; it narrows the platform for mypy + held = ctypes.WinError(32) # Windows' own text, which ends in a period + else: # pragma: no cover - skipped + held = OSError(13, "held") raised = { "step": step, "root": file_mod._RootUnheld.from_error(step), - # Windows' own text, which ends in a period. - "held": file_mod._RootUnheld.from_error(ctypes.WinError(32)), + "held": file_mod._RootUnheld.from_error(held), "final": file_mod._FinalPathUnread.from_error( _os_error(2, "The system cannot find the path specified", 3) ), From f58c78a726c5ca8856be7c9485589ec26b4e6e9c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:41:59 -0600 Subject: [PATCH 30/49] store: every backend refuses reference keys some backend cannot hold (BACKLOG #6613) The trailing-space reference-key refusal moves from SQL Server's width guard into store/reference_keys.py, which all three backends call before the snapshot transaction, and gains a U+0000 key refusal for Postgres. Both raise ReferenceSnapshotRefused (ReferenceKeyCollision is now its subclass), naming the set and 0-based key ordinals only; reference_sync logs it whole. Registry.add_reference refuses a set name ending in a space or holding U+0000, which SQL Server would merge or Postgres refuse. SQL Server: the open-time collation report (now _report_key_collations) covers reference and reference_version too, says a failed metadata read aborts the open, and the state-cache note rides only an UnauthenticatedCipherError, folded into _load_state_cache. The width guard uses _utf16_units and named width constants. SetState names any surrogate code point, not "lone surrogate", since half a pair is refused too. StateKeyError is exported from messagefoundry; both reference errors are in store.base.__all__. The reply_dropped test docstrings cite #3462. Not built: a refusal at open for a non-binary state key collation. It would refuse a store whose pre-#1588 state table opens today. BACKLOG #6613 Verified-by: tests --- changelog.d/6613.changed.md | 14 ++ messagefoundry/__init__.py | 3 + messagefoundry/config/wiring.py | 24 ++- messagefoundry/pipeline/reference_sync.py | 17 +- messagefoundry/store/base.py | 11 +- messagefoundry/store/postgres.py | 5 +- messagefoundry/store/reference_keys.py | 68 +++++++ messagefoundry/store/sqlserver.py | 189 +++++++++--------- messagefoundry/store/store.py | 5 +- tests/test_postgres_store.py | 2 +- tests/test_reference_key_guard.py | 96 +++++++++ tests/test_reference_sets.py | 52 +++++ ...test_sqlserver_state_key_limits_offline.py | 141 ++++++++----- tests/test_sqlserver_store.py | 7 +- tests/test_sqlserver_store_open_pool_leak.py | 2 +- tests/test_transform_state.py | 12 +- 16 files changed, 470 insertions(+), 178 deletions(-) create mode 100644 changelog.d/6613.changed.md create mode 100644 messagefoundry/store/reference_keys.py create mode 100644 tests/test_reference_key_guard.py diff --git a/changelog.d/6613.changed.md b/changelog.d/6613.changed.md new file mode 100644 index 0000000000..88eae6f6b6 --- /dev/null +++ b/changelog.d/6613.changed.md @@ -0,0 +1,14 @@ +- **Every store backend refuses a reference snapshot whose keys some backend could not hold + exactly, and a set name SQL Server would merge.** SQLite and Postgres now refuse, before the + snapshot's transaction, two keys that differ only by trailing spaces, as SQL Server already + did, and every backend refuses a key holding U+0000 (NUL), which Postgres text cannot store. + Both are a `ReferenceSnapshotRefused` (the collision is its subclass `ReferenceKeyCollision`), + naming the set and the keys by 0-based ordinal, never a key, and logged whole; the last-good + snapshot stays active and the sync fails every interval until the source changes. A + `Reference(...)` name that ends in a space or holds U+0000 is refused at load on every backend, + since SQL Server would compare `npi` and `npi ` as one set. A SQL Server open now also reports + a non-binary collation on the `reference` and `reference_version` key columns, at WARNING, and + repairs nothing. The note naming a folding `state` collation now rides only a failed + authentication tag, the one error a merged row can cause. `SetState`'s refusal of a surrogate + code point now says so rather than "lone surrogate", since half of a pair is refused too, and + `StateKeyError` is exported from `messagefoundry`. (`BACKLOG #6613`) diff --git a/messagefoundry/__init__.py b/messagefoundry/__init__.py index ece7fd274b..43f1fa50f2 100644 --- a/messagefoundry/__init__.py +++ b/messagefoundry/__init__.py @@ -80,6 +80,7 @@ SetState, Sftp, Soap, + StateKeyError, Tcp, Timer, code_set, @@ -185,6 +186,7 @@ "Send": "messagefoundry.config.wiring", "SetMeta": "messagefoundry.config.wiring", "SetState": "messagefoundry.config.wiring", + "StateKeyError": "messagefoundry.config.wiring", "Sftp": "messagefoundry.config.wiring", "Soap": "messagefoundry.config.wiring", "Tcp": "messagefoundry.config.wiring", @@ -263,6 +265,7 @@ def __dir__() -> list[str]: "split_by_obr", "Send", "SetState", + "StateKeyError", "SetMeta", "state_get", "response_get", diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index 2ffa0499be..d9c09bec21 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -5982,8 +5982,9 @@ def __post_init__(self) -> None: if "\x00" in text: raise StateKeyError(f"SetState {name} must not contain U+0000 (NUL)") # NVARCHAR counts UTF-16 code units. ASCII is one unit per char, so the usual MRN-style - # key skips the encode. A strict encode refuses a lone surrogate (U+D800..U+DFFF): no - # backend stores one, and the backend's bind would raise it inside the handoff, a + # key skips the encode. A strict encode refuses any surrogate code point (U+D800..U+DFFF), + # a lone one or half of a pair held as two code points: no backend stores either, and + # the backend's bind would raise it inside the handoff, a # store error the runner retries rather than a content fault it dead-letters. A key # already over the limit in code points is refused unencoded: each is at least a unit, # so a huge content-derived key costs no copy. @@ -5993,16 +5994,17 @@ def __post_init__(self) -> None: elif len(text) > STATE_KEY_MAX_UNITS: field_units, at_least = len(text), "at least " else: - lone_surrogate = False + surrogate = False try: field_units = len(text.encode("utf-16-le")) // 2 except UnicodeEncodeError: # Raised outside the handler: the encode error's `.object` is the whole key, so # it must not ride the chain as __context__ (nor would `from None` stop that). - lone_surrogate = True - if lone_surrogate: + surrogate = True + if surrogate: raise StateKeyError( - f"SetState {name} must not contain a lone surrogate (U+D800..U+DFFF)" + f"SetState {name} must not contain a surrogate code point (U+D800..U+DFFF);" + " write a character beyond U+FFFF as one code point" ) if field_units > STATE_KEY_MAX_UNITS: raise StateKeyError( @@ -7573,6 +7575,16 @@ def add_handler(self, name: str, fn: HandlerFn, accepts: HandlerAccepts | None = self.handler_accepts[name] = accepts def add_reference(self, spec: ReferenceSpec) -> None: + # BACKLOG #6613: SQL Server pads a trailing space when it compares reference_version.name + # (the `state` comment in store/sqlserver.py's _SCHEMA says why), so `npi` and `npi ` would + # be one set there, each sync overwriting the other's; Postgres text cannot hold U+0000. + # Refused on every backend, as SetState refuses such a key. + if spec.name.endswith(" "): + raise WiringError(f"reference set {spec.name!r}: a set name must not end with a space") + if "\x00" in spec.name: + raise WiringError( + f"reference set {spec.name!r}: a set name must not contain U+0000 (NUL)" + ) self._add(self.references, spec.name, spec, "reference set") def add_lookup(self, spec: DatabaseLookupSpec) -> None: diff --git a/messagefoundry/pipeline/reference_sync.py b/messagefoundry/pipeline/reference_sync.py index 4f5f66c178..d6c799e934 100644 --- a/messagefoundry/pipeline/reference_sync.py +++ b/messagefoundry/pipeline/reference_sync.py @@ -59,7 +59,7 @@ from messagefoundry.store import Store from messagefoundry.store.base import ( DEFAULT_STORE_ACQUIRE_TIMEOUT, - ReferenceKeyCollision, + ReferenceSnapshotRefused, acquire_pooled, ) from messagefoundry.transports.base import NegativeAckError, count_setting, float_setting @@ -121,14 +121,14 @@ class ReferenceColumnMismatch(ReferenceSyncError): column name twice. The message holds the set's name and which check failed, never a column's name, so - ``_sync_one`` logs it whole, as it does ``ReferenceKeyCollision``.""" + ``_sync_one`` logs it whole, as it does ``ReferenceSnapshotRefused``.""" class ReferenceKeyRefused(ReferenceSyncError): """A ``DatabaseRef`` statement returned a NULL key, or two rows with one key. The message holds the set's name and row ordinals, never a key, so ``_sync_one`` logs it - whole, as it does ``ReferenceKeyCollision``.""" + whole, as it does ``ReferenceSnapshotRefused``.""" #: The SQLSTATE a statement that ran past its ODBC query timeout fails with. @@ -904,7 +904,7 @@ async def _sync_one(self, spec: ReferenceSpec, *, generation: int | None = None) abandoned=self._abandoned_calls, ) except (ReferenceColumnMismatch, ReferenceKeyRefused) as exc: - # Logged whole, as ReferenceKeyCollision is below: the text holds the set's name and, + # Logged whole, as ReferenceSnapshotRefused is below: the text holds the set's name and, # by refusal, the column setting, or the row ordinals, never a column name or a key. log.error("%s (not synced)", exc) raise @@ -930,10 +930,11 @@ async def _sync_one(self, spec: ReferenceSpec, *, generation: int | None = None) await self._store.write_reference_snapshot( name=spec.name, version=version, rows=rows ) - except ReferenceKeyCollision as exc: - # BACKLOG #4917: sync_all logs only the class. This text holds the set's name and - # two ordinals, never a key, so it is logged whole: the ordinals find the rows in - # the source. + except ReferenceSnapshotRefused as exc: + # BACKLOG #4917, #6613: sync_all logs only the class. This text holds the set's + # name, the rule and key ordinals, never a key, so it is logged whole. An ordinal + # is the key's 0-based position among the keys the source yielded, in its order, + # not a file line number. log.error("%s (not synced)", exc) raise # Only after the store returned, so a refused write claims nothing. diff --git a/messagefoundry/store/base.py b/messagefoundry/store/base.py index cf79fbb942..82ff5b3281 100644 --- a/messagefoundry/store/base.py +++ b/messagefoundry/store/base.py @@ -90,6 +90,7 @@ probe_failure, sqlite_not_applicable, ) +from messagefoundry.store.reference_keys import ReferenceKeyCollision, ReferenceSnapshotRefused from messagefoundry.store.row_seal import AnyRowSealer, ResealOutcome from messagefoundry.store.store import ( ANY_CLAIM_OWNER, @@ -196,6 +197,8 @@ "ResendSourceAmbiguous", "ResendSourceEmpty", "ResendSourceNotFound", + "ReferenceKeyCollision", + "ReferenceSnapshotRefused", "RestoreRecord", "RevokeResult", "Row", @@ -269,14 +272,6 @@ def seed_filter_clause(table: str) -> str: return "" if seed is None else f" WHERE {seed}" -class ReferenceKeyCollision(ValueError): - """Two keys of one reference snapshot differ only by trailing spaces, which SQL Server compares - as equal (BACKLOG #4917), so its ``write_reference_snapshot`` refuses before the transaction. - - The message holds the set name and the two keys' ordinals, never a key or a hash of one, so - ``reference_sync`` logs it whole where it logs any other source error by class name only.""" - - class Row(Protocol): """A read result: key access + ``keys()`` (satisfied by ``aiosqlite.Row`` and ``dict``).""" diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 9d8d39f235..031ac83095 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -213,6 +213,7 @@ reseal_unless_tag_failure, set_aside_deadline, ) +from messagefoundry.store.reference_keys import refuse_unstorable_reference_keys from messagefoundry.store.row_seal import ( SEAL_PREFIX, USER_KIND, @@ -5507,7 +5508,9 @@ async def write_reference_snapshot( """Materialize a new reference snapshot and atomically make it active (ADR 0006). In one transaction: drop the set's prior rows, insert the new snapshot (each value JSON-encoded then encrypted), and upsert the ``reference_version`` pointer. The read cache swaps only after - commit, so a failed sync leaves the last-good snapshot live. Ported, not stubbed.""" + commit, so a failed sync leaves the last-good snapshot live. Ported, not stubbed. A key some + backend could not hold exactly, a NUL among them, is refused first (BACKLOG #6613).""" + refuse_unstorable_reference_keys(name, rows) encoded = [(k, encode_reference_value(v)) for k, v in rows.items()] encrypted = [ ( diff --git a/messagefoundry/store/reference_keys.py b/messagefoundry/store/reference_keys.py new file mode 100644 index 0000000000..e99a2a4e09 --- /dev/null +++ b/messagefoundry/store/reference_keys.py @@ -0,0 +1,68 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""The reference-snapshot key rules every store backend applies before its transaction (BACKLOG +#4917, #6613). + +A key some backend could not hold exactly is refused on every backend, as ``SetState`` refuses +such a state key, so a set behaves the same wherever it runs. A leaf module, so each backend's +``write_reference_snapshot`` imports it at module level; ``store.base`` re-exports the two error +classes. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +__all__ = [ + "ReferenceKeyCollision", + "ReferenceSnapshotRefused", + "refuse_unstorable_reference_keys", +] + + +class ReferenceSnapshotRefused(ValueError): + """A reference snapshot refused before its transaction, because some store backend could not + hold one of its keys exactly (BACKLOG #6613). The last-good snapshot stays active. + + The message holds the set name, the rule and key ordinals, never a key or a hash of one, so + ``reference_sync`` logs it whole where it logs any other source error by class name only. An + ordinal is the key's 0-based position in the snapshot as the source yielded it, not a file line + number.""" + + +class ReferenceKeyCollision(ReferenceSnapshotRefused): + """Two keys of one reference snapshot differ only by trailing spaces, which SQL Server compares + as equal (the ``state`` comment in ``store/sqlserver.py``'s ``_SCHEMA`` says why), so its + ``pk_reference`` would raise a duplicate mid-transaction. Refused on every backend.""" + + +def refuse_unstorable_reference_keys(name: str, rows: Mapping[str, Any]) -> None: + """Raise :class:`ReferenceSnapshotRefused` for a key holding U+0000, which Postgres text cannot + store, and :class:`ReferenceKeyCollision` for two keys equal once trailing U+0020 is stripped. + + One pass. Only a key ending in a space can pad onto another, so only those are stripped and + held: usually none, so a large set costs a containment test and an ``endswith`` per key.""" + padded: dict[str, int] = {} # stripped form of a space-ending key -> its ordinal + for ordinal, key in enumerate(rows): + if "\x00" in key: + raise ReferenceSnapshotRefused( + f"reference set {name!r}: key #{ordinal} contains U+0000 (NUL), which Postgres" + " text cannot store; refusing the snapshot (key value withheld: reference keys" + " may be PHI)" + ) + if not key.endswith(" "): + continue + stripped = key.rstrip(" ") + first = padded.get(stripped) + if first is None and stripped in rows: + first = next(i for i, k in enumerate(rows) if k == stripped) + if first is not None: + later, first = max(ordinal, first), min(ordinal, first) + # No digest: an MRN-shaped key is guessable from a short unsalted hash. + raise ReferenceKeyCollision( + f"reference set {name!r}: keys #{first} and #{later} differ only by trailing" + " spaces, which SQL Server compares as equal; refusing the snapshot (key values" + " withheld: reference keys may be PHI)" + ) + padded[stripped] = ordinal diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index 5135677155..98696296b9 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -98,7 +98,6 @@ PROVISION_SCHEMA_COMMAND, UPLOAD_RESERVATION_STALE_AFTER, ConnectionFlagLockTimeout, - ReferenceKeyCollision, SchemaDdlLockTimeout, SchemaLockTimeout, SchemaNotProvisionedError, @@ -144,6 +143,7 @@ CipherInfo, IdentityCipher, StoreKeylessError, + UnauthenticatedCipherError, allows_unmarked, cell_aad, cipher_info, @@ -208,6 +208,7 @@ reseal_unless_tag_failure, set_aside_deadline, ) +from messagefoundry.store.reference_keys import refuse_unstorable_reference_keys from messagefoundry.store.row_seal import ( SEAL_PREFIX, USER_KIND, @@ -798,6 +799,13 @@ def _utf16_units(text: str) -> int: return len(text.encode("utf-16-le")) // 2 +#: ``reference.name``'s width in ``_SCHEMA``, in UTF-16 code units. +_REFERENCE_NAME_MAX_UNITS: Final = 256 +#: ``reference.[key]``'s width in ``_SCHEMA``, in UTF-16 code units: the widest that keeps +#: ``pk_reference`` under SQL Server's 1700-byte nonclustered key cap. +_REFERENCE_KEY_MAX_UNITS: Final = 450 + + def _keep_matchable_lanes(lanes: Sequence[str]) -> list[str]: """Drop requested lane names that exceed the NVARCHAR(256) lane column (AC-11). @@ -2656,9 +2664,9 @@ async def _hold_account_row(cur: Any, user_id: str, hints: _AccountRowHints) -> # MERGE matched another spelling and kept it, while the value was sealed to the incoming one, so a # keyed reopen failed closed. BIN2 does NOT fix trailing spaces: `=` and the PK pad them under # every collation, so 'k' and 'k ' would still be one row. SetState refuses a trailing space instead. - # This is the one statement of that padding fact for the state and reference tables; the other - # comments point here. The CREATE runs only where `state` is absent, so an older table keeps its - # collation: _report_state_key_collation says so at open (BACKLOG #4917). pk_state is clustered, + # Comments elsewhere point here for that padding fact. The CREATE runs only where `state` is + # absent, so an older table keeps its collation: _report_key_collations says so at open + # (BACKLOG #4917). pk_state is clustered, # so its key is capped at 900 bytes: SetState bounds the pair (STATE_KEY_MAX_PAIR_UNITS). """IF OBJECT_ID('state','U') IS NULL CREATE TABLE state ( namespace NVARCHAR(256) COLLATE Latin1_General_100_BIN2 NOT NULL, @@ -2676,8 +2684,9 @@ async def _hold_account_row(cur: Any, user_id: str, hints: _AccountRowHints) -> # binary collation (BIN2) makes key equality case- and accent-exact like SQLite/Postgres: under a # case-insensitive database default, externally-sourced keys differing only by case would raise a # PK duplicate MID-transaction — a perpetual per-interval sync-failure alert. BIN2 does NOT fix a - # trailing space (the `state` comment above says why), so _guard_reference_widths refuses keys - # that differ only by one. value is ciphertext at rest (snapshot values may carry PHI). + # trailing space (the `state` comment above says why), so refuse_unstorable_reference_keys + # (store/reference_keys.py) refuses keys that differ only by one, on every backend (BACKLOG + # #6613). value is ciphertext at rest (snapshot values may carry PHI). # reference_version.name/version carry the same collation so the active-snapshot LEFT JOIN can # never hit a cross-column collation conflict. """IF OBJECT_ID('reference','U') IS NULL CREATE TABLE reference ( @@ -4598,7 +4607,7 @@ async def open( await store._ensure_schema(create=create, read_only=read_only) # Right after the schema, so a later open step that fails still leaves the report # logged; read-only included, since it reads metadata only (BACKLOG #4917). - folded = await store._report_state_key_collation() + folded = await store._report_key_collations() if store._fifo_claim_proc: # ADR 0114 sub-lever A startup gate (AC-7): verify the deployed procs (existence + # body hash + compat) — a miss degrades LOUDLY to the shipped batch, never a failed @@ -4635,7 +4644,7 @@ async def open( if not read_only: # A read-only handle loads no cache, as on SQLite: each decrypts every cell (#1780). # ADR 0005 read-through cache warm-up - await store._load_state_cache_noting(folded) + await store._load_state_cache(folded_collation=folded) await store._load_reference_cache() # ADR 0006 reference-snapshot read cache except BaseException as exc: # Don't leak the pool if first-open initialization fails (M-6), a cancel included @@ -10520,45 +10529,75 @@ def state_view(self) -> Mapping[tuple[str, str], Any]: resolves cross-message; ``transform_handoff`` refreshes it post-commit.""" return MappingProxyType(self._state_cache) - async def _report_state_key_collation(self) -> str | None: - """Log a WARNING for a ``state`` table whose key columns are not binary (BACKLOG #4917; the - ``state`` comment in ``_SCHEMA`` says how one arises). Repairs nothing, and the open goes - on. Returns the collation found, or ``None`` when both are BIN2 or the table is absent.""" + async def _report_key_collations(self) -> str | None: + """Log a WARNING for each key table whose key columns are not binary: ``state`` (BACKLOG + #4917; the ``state`` comment in ``_SCHEMA`` says how one arises), and ``reference`` with + ``reference_version`` (BACKLOG #6613). Repairs nothing, and a finding does not stop the + open. The metadata read is not optional: an error from it aborts the open, as any other + open step's does. Returns ``state``'s folding collation, the one the state-cache note + names, or ``None`` when its key columns are binary or the table is absent.""" rows = await self._fetchall( - "SELECT name, collation_name FROM sys.columns" - " WHERE object_id = OBJECT_ID('state') AND name IN ('namespace', 'key')" - ) - # Any binary collation compares code points, as the cache does; only a linguistic one folds. - found = sorted( - { - str(r["collation_name"]) - for r in rows - # A token, not a suffix: Latin1_General_100_BIN2_UTF8 is binary too. - if not {"BIN", "BIN2"} & set(str(r["collation_name"]).upper().split("_")) - } - ) - if not found: - return None - collation = ", ".join(found) - log.warning( - "sqlserver: the state table's namespace/key columns use collation %s, not a binary one" - " such as the %s the shipped DDL names. Keys this collation compares as equal, such as" - " ones differing only in case under a case-insensitive collation, may have been merged" - " into one row; the engine does not repair them. Remedy, which loses every state row:" - " drop the state table and delete the schema_meta row, so the next open (or" - " provision-schema) re-runs the DDL batch and creates the table again", - collation, - _STATE_KEY_COLLATION, + "SELECT OBJECT_NAME(object_id) AS table_name, name, collation_name FROM sys.columns" + " WHERE object_id IN (OBJECT_ID('state'), OBJECT_ID('reference')," + " OBJECT_ID('reference_version'))" + " AND name IN ('namespace', 'key', 'name', 'version')" ) - return collation + # Any binary collation compares code points, as the caches do; only a linguistic one folds. + found: dict[str, set[str]] = {} + for r in rows: + collation = str(r["collation_name"]) + # A token, not a suffix: Latin1_General_100_BIN2_UTF8 is binary too. + if not {"BIN", "BIN2"} & set(collation.upper().split("_")): + group = "state" if r["table_name"] == "state" else "reference" + found.setdefault(group, set()).add(collation) + state = ", ".join(sorted(found["state"])) if "state" in found else None + if state is not None: + log.warning( + "sqlserver: the state table's namespace/key columns use collation %s, not a binary" + " one such as the %s the shipped DDL names. Keys this collation compares as equal," + " such as ones differing only in case under a case-insensitive collation, may have" + " been merged into one row; the engine does not repair them. Remedy, which loses" + " every state row: drop the state table and delete the schema_meta row, so the next" + " open (or provision-schema) re-runs the DDL batch and creates the table again", + state, + _STATE_KEY_COLLATION, + ) + if "reference" in found: + log.warning( + "sqlserver: the reference, reference_version tables' key columns use collation %s," + " not a binary one such as the %s the shipped DDL names. Keys this collation" + " compares as equal, such as ones differing only in case under a case-insensitive" + " collation, collide there, so a sync of a set holding both fails; the engine does" + " not repair them. Remedy: drop both tables and delete the schema_meta row, so the" + " next open (or provision-schema) re-runs the DDL batch and creates them again;" + " the next sync then materializes each set from its source", + ", ".join(sorted(found["reference"])), + _STATE_KEY_COLLATION, + ) + return state - async def _load_state_cache(self) -> None: - """Warm the transform-state read-through cache from the ``state`` table at open (ADR 0005).""" - self._state_cache = await cipher_bulk_call( - self._cipher, - self._decode_state_rows, - await self._fetchall("SELECT namespace, [key], value FROM state"), - ) + async def _load_state_cache(self, *, folded_collation: str | None = None) -> None: + """Warm the transform-state read-through cache from the ``state`` table at open (ADR 0005). + + A failed AEAD tag (:class:`UnauthenticatedCipherError`) is how a row merged across a case + or accent variant shows: its value was sealed to the other spelling. When + :meth:`_report_key_collations` found a folding ``folded_collation``, that error carries a + note naming it (BACKLOG #4917, #6613). Any other ``CipherError``, a corrupt cell or a key + not supplied, is not such a merge and carries no note.""" + try: + self._state_cache = await cipher_bulk_call( + self._cipher, + self._decode_state_rows, + await self._fetchall("SELECT namespace, [key], value FROM state"), + ) + except UnauthenticatedCipherError as exc: + if folded_collation is not None: + exc.add_note( + f"the state table's key columns use collation {folded_collation}, not a" + " binary one, so this row may have been merged across a case or accent variant" + " and sealed to the other spelling (BACKLOG #1588, #4917)" + ) + raise def _decode_state_rows( self, rows: Sequence[Mapping[str, Any]] @@ -10580,20 +10619,6 @@ def _decode_state_rows( ) return cache - async def _load_state_cache_noting(self, folded_collation: str | None) -> None: - """:meth:`_load_state_cache`, with a note on a ``CipherError`` naming the folding collation - :meth:`_report_state_key_collation` found, a possible cause (BACKLOG #4917).""" - try: - await self._load_state_cache() - except CipherError as exc: - if folded_collation is not None: - exc.add_note( - f"the state table's key columns use collation {folded_collation}, not a" - " binary one, so this row may have been merged across a case or accent variant" - " and sealed to the other spelling (BACKLOG #1588, #4917)" - ) - raise - async def _load_reference_cache(self) -> None: """Populate the in-memory reference cache from the ACTIVE snapshot of each set (ADR 0006). @@ -10672,53 +10697,32 @@ def _guard_reference_widths(self, name: str, rows: Mapping[str, Any]) -> None: (NVARCHAR's unit — a naive ``len()`` counts code points and passes astral-plane keys straight into that truncation). The error NEVER carries a raw key: keys may be PHI for a patient-keyed set (CLAUDE.md §9), so it names the set + the key's ordinal, code-unit length, and a truncated - hash only. - - It also refuses two keys equal once trailing U+0020 is stripped (BACKLOG #4917): - ``pk_reference`` pads them (the ``state`` comment in ``_SCHEMA`` says why), so the second - INSERT would raise a PK duplicate mid-transaction, every interval. It raises - :class:`ReferenceKeyCollision`, naming the keys by ordinal only, because ``reference_sync`` - logs that class's message whole, where it logs any other source error by class name only.""" - if len(name.encode("utf-16-le")) // 2 > 256: + hash only. The key rules every backend shares are + :func:`~messagefoundry.store.reference_keys.refuse_unstorable_reference_keys`.""" + name_units = _utf16_units(name) + if name_units > _REFERENCE_NAME_MAX_UNITS: raise ValueError( - f"reference set name exceeds NVARCHAR(256) " - f"({len(name.encode('utf-16-le')) // 2} UTF-16 code units); refusing the snapshot" + f"reference set name exceeds NVARCHAR({_REFERENCE_NAME_MAX_UNITS}) " + f"({name_units} UTF-16 code units); refusing the snapshot" ) - # Only a key ending in a space can pad onto another, so only those are stripped and held: - # usually none, so a large set costs one endswith per key, not a second dict of every key. - padded: dict[str, int] = {} # stripped form of a space-ending key -> its ordinal for ordinal, key in enumerate(rows): - units = len(key.encode("utf-16-le")) // 2 - if units > 450: + units = _utf16_units(key) + if units > _REFERENCE_KEY_MAX_UNITS: digest = hashlib.sha256(key.encode()).hexdigest()[:12] raise ValueError( - f"reference set {name!r}: key #{ordinal} exceeds NVARCHAR(450) " - f"({units} UTF-16 code units, sha256:{digest}); refusing the snapshot " + f"reference set {name!r}: key #{ordinal} exceeds " + f"NVARCHAR({_REFERENCE_KEY_MAX_UNITS}) ({units} UTF-16 code units, " + f"sha256:{digest}); refusing the snapshot " "(key value withheld: reference keys may be PHI)" ) - if not key.endswith(" "): - continue - stripped = key.rstrip(" ") - first = padded.get(stripped) - if first is None and stripped in rows: - first = next(i for i, k in enumerate(rows) if k == stripped) - if first is not None: - later, first = max(ordinal, first), min(ordinal, first) - # No digest: an MRN-shaped key is guessable from a short unsalted hash, and the two - # ordinals already find the rows in the source. - raise ReferenceKeyCollision( - f"reference set {name!r}: keys #{first} and #{later} differ only by trailing" - " spaces, which SQL Server compares as equal; refusing the snapshot (key" - " values withheld: reference keys may be PHI)" - ) - padded[stripped] = ordinal async def write_reference_snapshot( self, *, name: str, version: str, rows: Mapping[str, Any] ) -> None: """Materialize a new reference snapshot and atomically make it active (ADR 0006, BACKLOG #235). - Fail-closed width guard first (see :meth:`_guard_reference_widths`), then ONE transaction: + The key rules every backend shares, then the fail-closed width guard (see + :meth:`_guard_reference_widths`), then ONE transaction: drop the set's prior rows, insert every ``(name, version, [key], value)`` of the new snapshot (each value JSON-encoded then cipher-encrypted — it may carry PHI), and upsert the ``reference_version`` pointer via ``MERGE WITH (HOLDLOCK)`` (the ``SqlServerCoordinator`` @@ -10727,6 +10731,7 @@ async def write_reference_snapshot( (and its Track B Step 6 version token) swaps ONLY after commit — a rolled-back write never leaks into :meth:`reference_view`. Same build-new-then-flip contract as SQLite/Postgres, so it is idempotent on a re-run with the same rows.""" + refuse_unstorable_reference_keys(name, rows) # BACKLOG #6613: every backend's rules self._guard_reference_widths(name, rows) encoded = [(k, encode_reference_value(v)) for k, v in rows.items()] encrypted = [ diff --git a/messagefoundry/store/store.py b/messagefoundry/store/store.py index 514d66537e..d4a0c73d2d 100644 --- a/messagefoundry/store/store.py +++ b/messagefoundry/store/store.py @@ -209,6 +209,7 @@ reseal_unless_tag_failure, set_aside_deadline, ) +from messagefoundry.store.reference_keys import refuse_unstorable_reference_keys from messagefoundry.store.row_seal import ( ADSET_KIND, APPROVAL_KIND, @@ -15679,7 +15680,9 @@ async def write_reference_snapshot( (served from the in-memory cache) until this commits; a **failed** sync rolls back wholesale, so the last-good snapshot stays active (graceful degradation). The cache is swapped **only after** commit — a rolled-back write never leaks into :meth:`reference_view`. Replaces the whole set - (build-new-then-flip), so it is idempotent on a re-run with the same rows.""" + (build-new-then-flip), so it is idempotent on a re-run with the same rows. A key some backend + could not hold exactly is refused first, as on every backend (BACKLOG #6613).""" + refuse_unstorable_reference_keys(name, rows) encoded = [(k, encode_reference_value(v)) for k, v in rows.items()] encrypted = [ ( diff --git a/tests/test_postgres_store.py b/tests/test_postgres_store.py index 19a8d0c4a1..0d468b7e51 100644 --- a/tests/test_postgres_store.py +++ b/tests/test_postgres_store.py @@ -2056,7 +2056,7 @@ async def test_mark_done_writes_reply_dropped_with_the_delivery(store, verbosity rides the DONE flip beside ``delivered``. Controls: a vanished row writes nothing and returns False, and a plain ``mark_done`` writes no ``reply_dropped``. Events are read through ``events_for``, which decrypts ``detail``. Parametrized over the event verbosity as the - SQLite test is (BACKLOG #4917): ``delivered`` is thinned below ``all`` and ``reply_dropped`` + SQLite test is (BACKLOG #3462): ``delivered`` is thinned below ``all`` and ``reply_dropped`` is not. Set on the fixture's store, since each backend reads it at write time.""" store._message_events = verbosity delivered = [("delivered", "OB1", None)] if verbosity == "all" else [] diff --git a/tests/test_reference_key_guard.py b/tests/test_reference_key_guard.py new file mode 100644 index 0000000000..fddaa957b6 --- /dev/null +++ b/tests/test_reference_key_guard.py @@ -0,0 +1,96 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""BACKLOG #6613: every store backend refuses a reference snapshot whose keys some backend could not +hold exactly, before its transaction, as ``SetState`` refuses such a state key on every backend. + +The rules: two keys that differ only by trailing spaces (SQL Server pads them in ``pk_reference``), +and a key holding U+0000 (Postgres text cannot store it). The SQLite store is opened for real; the +Postgres and SQL Server stores are built bare with ``object.__new__``, so each test shows the guard +runs before the store touches its cipher or its database. Not env-gated. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest + +from messagefoundry.store.base import ReferenceKeyCollision, ReferenceSnapshotRefused +from messagefoundry.store.postgres import PostgresStore +from messagefoundry.store.reference_keys import refuse_unstorable_reference_keys +from messagefoundry.store.sqlserver import SqlServerStore +from messagefoundry.store.store import MessageStore + +#: Each refused shape, with the two ordinals (or the one) the refusal must name. +_COLLISIONS: tuple[tuple[dict[str, Any], int, int], ...] = ( + ({"MRN-1": 1, "MRN-1 ": 2}, 0, 1), + ({"MRN-1 ": 1, "other": 2, "MRN-1 ": 3}, 0, 2), # two padded keys, no bare one + ({"MRN-1 ": 1, "other": 2, "MRN-1": 3}, 0, 2), # the bare key comes later +) + + +def test_padded_keys_are_refused_naming_both_ordinals_and_no_key() -> None: + for rows, first, later in _COLLISIONS: + with pytest.raises(ReferenceKeyCollision, match="only by trailing spaces") as exc: + refuse_unstorable_reference_keys("set", rows) + text = str(exc.value) + assert f"keys #{first} and #{later} differ" in text + assert "MRN" not in text and "sha256" not in text # nothing of the key (PHI) + assert isinstance(exc.value, ReferenceSnapshotRefused) + + +def test_a_nul_in_a_key_is_refused_naming_its_ordinal_and_no_key() -> None: + with pytest.raises(ReferenceSnapshotRefused, match=r"key #1 contains U\+0000") as exc: + refuse_unstorable_reference_keys("set", {"A": 1, "MRN\x00-2": 2}) + assert "MRN" not in str(exc.value) + assert not isinstance(exc.value, ReferenceKeyCollision) + + +def test_keys_that_every_backend_holds_exactly_pass() -> None: + """The controls: a lone trailing space, a leading space, a trailing tab, a case variant and + another control character are each distinct on every backend and pass.""" + refuse_unstorable_reference_keys("set", {"a ": 1, " a": 2, "a\t": 3, "A": 4, "b\x01": 5}) + refuse_unstorable_reference_keys("set", {}) + + +@pytest.mark.parametrize("rows", [{"MRN-1": 1, "MRN-1 ": 2}, {"MRN\x00": 1}]) +async def test_the_sqlite_store_refuses_and_keeps_the_last_good_snapshot( + tmp_path: Path, rows: dict[str, Any] +) -> None: + """SQLite stores both keys, so before this it took the snapshot. The refusal comes before the + transaction: the prior snapshot stays active, in the view and in the table.""" + store = await MessageStore.open(tmp_path / "r.db") + try: + await store.write_reference_snapshot(name="codes", version="v1", rows={"A": "1"}) + with pytest.raises(ReferenceSnapshotRefused): + await store.write_reference_snapshot(name="codes", version="v2", rows=rows) + assert store.reference_view()["codes"] == {"A": "1"} + stored = await (await store._db.execute("SELECT version, key FROM reference")).fetchall() + assert [(r["version"], r["key"]) for r in stored] == [("v1", "A")] + finally: + await store.close() + + +@pytest.mark.parametrize("store_class", [PostgresStore, SqlServerStore]) +@pytest.mark.parametrize("rows", [{"MRN-1": 1, "MRN-1 ": 2}, {"MRN\x00": 1}]) +async def test_the_server_stores_refuse_before_touching_anything( + store_class: type[Any], rows: dict[str, Any] +) -> None: + """A bare store has no cipher, pool or cache, so any work before the guard would fail with an + AttributeError instead of the refusal.""" + store = object.__new__(store_class) + with pytest.raises(ReferenceSnapshotRefused): + await store.write_reference_snapshot(name="codes", version="v1", rows=rows) + + +def test_the_key_refusals_are_exported_where_callers_look() -> None: + """BACKLOG #6613: ``StateKeyError`` is raised in a Handler author's own code, so it is on the + package root beside ``SetState``; the reference refusals are in ``store.base.__all__``.""" + import messagefoundry + from messagefoundry.config.wiring import StateKeyError + from messagefoundry.store import base + + assert "StateKeyError" in messagefoundry.__all__ + assert messagefoundry.StateKeyError is StateKeyError + assert {"ReferenceKeyCollision", "ReferenceSnapshotRefused"} <= set(base.__all__) diff --git a/tests/test_reference_sets.py b/tests/test_reference_sets.py index 563c8183b2..3d7bfc499b 100644 --- a/tests/test_reference_sets.py +++ b/tests/test_reference_sets.py @@ -30,6 +30,7 @@ ReferenceSpec, Registry, Send, + WiringError, env, ) from messagefoundry.parsing.message import Message @@ -653,6 +654,24 @@ def test_reference_declaration_registers() -> None: assert reg.references["provider_npi"].refresh_seconds == 600 +@pytest.mark.parametrize( + ("name", "rule"), + [("npi ", "must not end with a space"), ("np\x00i", r"must not contain U\+0000")], +) +def test_a_reference_set_name_some_backend_cannot_hold_is_refused(name: str, rule: str) -> None: + """BACKLOG #6613: SQL Server pads a trailing space when it compares ``reference_version.name``, + so ``npi`` and ``npi `` would be one set there, the later sync overwriting the earlier; Postgres + text cannot hold U+0000. Refused at declaration on every backend, as ``SetState`` refuses such a + key. The control: a name with an inner space and one with a leading space still register.""" + reg = Registry() + with pytest.raises(WiringError, match=rule): + reg.add_reference(ReferenceSpec(name=name, source=FileRef(path="x.csv"))) + assert reg.references == {} + for ok in ("provider npi", " npi"): + reg.add_reference(ReferenceSpec(name=ok, source=FileRef(path="x.csv"))) + assert set(reg.references) == {"provider npi", " npi"} + + def test_dryrun_resolves_file_reference(tmp_path: Path) -> None: # A handler that enriches via reference(...) resolves in a dry-run from the file-backed declaration. csv = _csv(tmp_path / "npi.csv", "key,value\nMED1,9991\n") @@ -1043,6 +1062,39 @@ async def colliding_write(*, name: str, version: str, rows: Any) -> None: await store.close() +async def test_a_nul_key_refusal_is_logged_whole( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + """BACKLOG #6613: every backend refuses a key holding U+0000 before the transaction. The + refusal's text holds the set's name and the key's ordinal, never the key, so it is logged + whole like the collision, and stays a transient failure: last-good kept, retried.""" + from messagefoundry.store.base import ReferenceSnapshotRefused + + csv = _csv(tmp_path / "npi.csv", "key,value\nMED1,9991\n") + store = await MessageStore.open(tmp_path / "nul.db") + text = "reference set 'provider_npi': key #4 contains U+0000 (NUL)" + + async def refused_write(*, name: str, version: str, rows: Any) -> None: + raise ReferenceSnapshotRefused(text) + + store.write_reference_snapshot = refused_write # type: ignore[method-assign] + runner = ReferenceSyncRunner( + store, + lambda: [_spec("provider_npi", csv)], + REF, + alert_sink=_CapturingAlerts(), + egress=EgressSettings(deny_by_default=False), + ) + try: + with caplog.at_level("WARNING"): + result = await runner.sync_all() + assert result.failed == 1 and result.synced == 0 + assert f"{text} (not synced)" in caplog.text + assert "keeping last-good): ReferenceSnapshotRefused" in caplog.text + finally: + await store.close() + + # --- ASVS 14.2.7: purge_reference_snapshots (orphan-scoped) ------------------ # # `reference.value` is PL-2 (PHI.md §2) and until 14.2.7 had NO purge path at all: a set dropped from diff --git a/tests/test_sqlserver_state_key_limits_offline.py b/tests/test_sqlserver_state_key_limits_offline.py index 706f6d6c42..3c7ad97cd2 100644 --- a/tests/test_sqlserver_state_key_limits_offline.py +++ b/tests/test_sqlserver_state_key_limits_offline.py @@ -19,7 +19,7 @@ from messagefoundry.config.wiring import STATE_KEY_MAX_PAIR_UNITS, STATE_KEY_MAX_UNITS from messagefoundry.store import sqlserver as ss from messagefoundry.store.base import ReferenceKeyCollision -from messagefoundry.store.crypto import CipherError +from messagefoundry.store.crypto import CipherError, UnauthenticatedCipherError from messagefoundry.store.sqlserver import SqlServerStore @@ -52,23 +52,37 @@ def test_the_state_ddl_matches_the_setstate_bounds_and_the_collation() -> None: assert 2 * STATE_KEY_MAX_PAIR_UNITS <= 900 < 2 * (STATE_KEY_MAX_PAIR_UNITS + 1) -async def test_a_bin2_state_table_reports_nothing(caplog: pytest.LogCaptureFixture) -> None: - store, seen = _bare_store( - [ - {"name": "namespace", "collation_name": "Latin1_General_100_BIN2"}, - {"name": "key", "collation_name": "Latin1_General_100_BIN2"}, - ] - ) +def _key_columns(state: str, reference: str = "Latin1_General_100_BIN2") -> list[dict[str, Any]]: + """``sys.columns`` rows for the key columns of all three tables: ``state``'s under ``state``, + ``reference``'s and ``reference_version``'s under ``reference`` (BACKLOG #6613).""" + return [ + {"table_name": "state", "name": "namespace", "collation_name": state}, + {"table_name": "state", "name": "key", "collation_name": state}, + *( + {"table_name": table, "name": column, "collation_name": reference} + for table, columns in ( + ("reference", ("name", "version", "key")), + ("reference_version", ("name", "version")), + ) + for column in columns + ), + ] + + +async def test_bin2_key_tables_report_nothing(caplog: pytest.LogCaptureFixture) -> None: + store, seen = _bare_store(_key_columns("Latin1_General_100_BIN2")) with caplog.at_level(logging.WARNING, logger=ss.__name__): - assert await store._report_state_key_collation() is None + assert await store._report_key_collations() is None assert caplog.records == [] - assert len(seen) == 1 and "sys.columns" in seen[0] and "OBJECT_ID('state')" in seen[0] + assert len(seen) == 1 and "sys.columns" in seen[0] + for table in ("state", "reference", "reference_version"): + assert f"OBJECT_ID('{table}')" in seen[0] -async def test_an_absent_state_table_reports_nothing(caplog: pytest.LogCaptureFixture) -> None: +async def test_absent_key_tables_report_nothing(caplog: pytest.LogCaptureFixture) -> None: store, _ = _bare_store([]) with caplog.at_level(logging.WARNING, logger=ss.__name__): - assert await store._report_state_key_collation() is None + assert await store._report_key_collations() is None assert caplog.records == [] @@ -77,23 +91,35 @@ async def test_an_older_state_table_is_reported_and_not_repaired( ) -> None: """A table made before BACKLOG #1588 took the database default. The report names it at WARNING, says nothing is repaired, and issues only the one metadata read: no ALTER, no UPDATE.""" - store, seen = _bare_store( - [ - {"name": "namespace", "collation_name": "SQL_Latin1_General_CP1_CI_AS"}, - {"name": "key", "collation_name": "SQL_Latin1_General_CP1_CI_AS"}, - ] - ) + store, seen = _bare_store(_key_columns("SQL_Latin1_General_CP1_CI_AS")) with caplog.at_level(logging.WARNING, logger=ss.__name__): - found = await store._report_state_key_collation() + found = await store._report_key_collations() assert found == "SQL_Latin1_General_CP1_CI_AS" (record,) = caplog.records assert record.levelno == logging.WARNING text = record.getMessage() assert "SQL_Latin1_General_CP1_CI_AS" in text and ss._STATE_KEY_COLLATION in text - assert "does not repair" in text + assert "state table" in text and "does not repair" in text assert len(seen) == 1 and seen[0].lstrip().upper().startswith("SELECT") +async def test_a_folding_reference_table_is_reported_on_its_own( + caplog: pytest.LogCaptureFixture, +) -> None: + """BACKLOG #6613: the ``reference`` and ``reference_version`` key columns are reported too, in + one WARNING naming those tables and their own remedy. Only ``state``'s collation is returned, + since only it feeds the state-cache note; here that is ``None``.""" + store, _ = _bare_store( + _key_columns("Latin1_General_100_BIN2", reference="Latin1_General_CI_AS") + ) + with caplog.at_level(logging.WARNING, logger=ss.__name__): + assert await store._report_key_collations() is None + (record,) = caplog.records + text = record.getMessage() + assert "reference, reference_version" in text and "Latin1_General_CI_AS" in text + assert "does not repair" in text and "materializes each set from its source" in text + + @pytest.mark.parametrize( "collation", [ @@ -105,51 +131,48 @@ async def test_an_older_state_table_is_reported_and_not_repaired( ) async def test_any_binary_collation_reports_nothing(collation: str) -> None: """A binary collation compares code points, so it cannot merge case variants.""" - rows = [{"name": n, "collation_name": collation} for n in ("namespace", "key")] - store, _ = _bare_store(rows) - assert await store._report_state_key_collation() is None + store, _ = _bare_store(_key_columns(collation, reference=collation)) + assert await store._report_key_collations() is None async def test_one_drifted_column_is_enough_to_report() -> None: - store, _ = _bare_store( - [ - {"name": "namespace", "collation_name": "Latin1_General_100_BIN2"}, - {"name": "key", "collation_name": "Latin1_General_CI_AS"}, - ] - ) - assert await store._report_state_key_collation() == "Latin1_General_CI_AS" + rows = _key_columns("Latin1_General_100_BIN2") + rows[1]["collation_name"] = "Latin1_General_CI_AS" # state.key alone + store, _ = _bare_store(rows) + assert await store._report_key_collations() == "Latin1_General_CI_AS" -async def test_an_undecryptable_row_names_the_drifted_collation( - monkeypatch: pytest.MonkeyPatch, +@pytest.mark.parametrize("folded", ["SQL_Latin1_General_CP1_CI_AS", None]) +@pytest.mark.parametrize("error", [UnauthenticatedCipherError, CipherError]) +async def test_only_an_unauthenticated_row_names_the_drifted_collation( + monkeypatch: pytest.MonkeyPatch, folded: str | None, error: type[CipherError] ) -> None: - """The keyed symptom of a merged row is a CipherError at the cache warm-up. It still fails - closed, and when the report found a folding collation the error carries a note naming it. The - control: with no drift found, the same error carries no such note.""" + """The keyed symptom of a merged row is a failed AEAD tag at the cache warm-up, which the + cipher raises as ``UnauthenticatedCipherError``. It still fails closed, and when the report + found a folding collation the error carries a note naming it. The controls: with no drift + found there is no note, and a plain ``CipherError`` (a corrupt cell, a missing key) carries + none either, since a merged row cannot cause it (BACKLOG #6613).""" def _refuse(*args: Any, **kwargs: Any) -> Any: - raise CipherError("could not decrypt a state row") + raise error("could not decrypt a state row") monkeypatch.setattr(ss, "decrypt_json_cell", _refuse) - row = {"namespace": "ns", "key": "k", "value": "mfenc:x"} - - store, _ = _bare_store([row]) + store, _ = _bare_store([{"namespace": "ns", "key": "k", "value": "mfenc:x"}]) store._cipher = object() # type: ignore[assignment] - with pytest.raises(CipherError) as drifted: - await store._load_state_cache_noting("SQL_Latin1_General_CP1_CI_AS") - notes = getattr(drifted.value, "__notes__", []) - assert any("SQL_Latin1_General_CP1_CI_AS" in n and "may have been" in n for n in notes) - - store2, _ = _bare_store([row]) - store2._cipher = object() # type: ignore[assignment] - with pytest.raises(CipherError) as plain: - await store2._load_state_cache_noting(None) - assert getattr(plain.value, "__notes__", []) == [] + with pytest.raises(error) as raised: + await store._load_state_cache(folded_collation=folded) + assert type(raised.value) is error + notes = getattr(raised.value, "__notes__", []) + if folded is not None and error is UnauthenticatedCipherError: + assert any(folded in n and "may have been" in n for n in notes) + else: + assert notes == [] -def test_reference_keys_differing_only_by_trailing_spaces_are_refused() -> None: +async def test_reference_keys_differing_only_by_trailing_spaces_are_refused() -> None: """``pk_reference`` pads trailing spaces, so these would raise a PK duplicate mid-transaction. - The guard refuses first, naming both keys by ordinal only: no value, and no hash of one.""" + The write refuses first, through the guard every backend shares (BACKLOG #6613), naming both + keys by ordinal only: no value, and no hash of one.""" store = object.__new__(SqlServerStore) for rows, first, later in ( ({"MRN-1": 1, "MRN-1 ": 2}, 0, 1), @@ -157,14 +180,26 @@ def test_reference_keys_differing_only_by_trailing_spaces_are_refused() -> None: ({"MRN-1 ": 1, "other": 2, "MRN-1": 3}, 0, 2), # the bare key comes later ): with pytest.raises(ReferenceKeyCollision, match="only by trailing spaces") as exc: - store._guard_reference_widths("set", rows) + await store.write_reference_snapshot(name="set", version="v1", rows=rows) text = str(exc.value) assert f"keys #{first} and #{later} differ" in text assert "MRN" not in text and "sha256" not in text # nothing of the key (PHI) -def test_reference_keys_that_do_not_collide_pass_the_guard() -> None: +def test_reference_keys_that_do_not_collide_pass_the_width_guard() -> None: """The controls: a lone trailing space, a leading space, a trailing tab, and a case variant are each distinct under BIN2 and pass.""" store = object.__new__(SqlServerStore) store._guard_reference_widths("set", {"a ": 1, " a": 2, "a\t": 3, "A": 4, "b": 5}) + + +def test_the_width_guard_counts_utf16_units_against_the_column_widths() -> None: + """The name is ``NVARCHAR(256)`` and the key ``NVARCHAR(450)``, counted in UTF-16 code units: + each is accepted at its width and refused one unit over, an astral character counting two.""" + store = object.__new__(SqlServerStore) + astral = "\U0001f600" + store._guard_reference_widths("n" * 256, {"k" * 450: 1, astral * 225: 2}) + with pytest.raises(ValueError, match=r"NVARCHAR\(256\) \(257 UTF-16 code units\)"): + store._guard_reference_widths("n" * 255 + astral, {}) + with pytest.raises(ValueError, match=r"key #1 exceeds NVARCHAR\(450\) \(452 UTF-16"): + store._guard_reference_widths("set", {"a": 1, astral * 226: 2}) diff --git a/tests/test_sqlserver_store.py b/tests/test_sqlserver_store.py index b11f41db25..801a4f68ca 100644 --- a/tests/test_sqlserver_store.py +++ b/tests/test_sqlserver_store.py @@ -2045,7 +2045,7 @@ async def test_mark_done_writes_reply_dropped_with_the_delivery(store, verbosity rides the DONE flip beside ``delivered``. Controls: a vanished row writes nothing and returns False, and a plain ``mark_done`` writes no ``reply_dropped``. Events are read through ``events_for``, which decrypts ``detail``. Parametrized over the event verbosity as the - SQLite test is (BACKLOG #4917): ``delivered`` is thinned below ``all`` and ``reply_dropped`` + SQLite test is (BACKLOG #3462): ``delivered`` is thinned below ``all`` and ``reply_dropped`` is not. Set on the fixture's store, since each backend reads it at write time.""" store._message_events = verbosity delivered = [("delivered", "OB1", None)] if verbosity == "all" else [] @@ -4095,7 +4095,7 @@ async def test_reference_keys_differing_by_a_trailing_space_fail_guard( not refusing a case the database would have accepted.""" import pyodbc - from messagefoundry.store.sqlserver import SqlServerStore + from messagefoundry.store import sqlserver await store.write_reference_snapshot(name="padded", version="v1", rows={"ok": "1"}) twins = {"MRN-1": "a", "MRN-1 ": "b"} @@ -4108,7 +4108,8 @@ async def test_reference_keys_differing_by_a_trailing_space_fail_guard( await store.write_reference_snapshot(name="padded", version="v3", rows={"MRN-2 ": "c"}) assert store.reference_view()["padded"] == {"MRN-2 ": "c"} - monkeypatch.setattr(SqlServerStore, "_guard_reference_widths", lambda self, name, rows: None) + # The shared guard every backend runs (BACKLOG #6613), as this module bound it. + monkeypatch.setattr(sqlserver, "refuse_unstorable_reference_keys", lambda name, rows: None) with pytest.raises(pyodbc.IntegrityError): await store.write_reference_snapshot(name="padded", version="v4", rows=twins) assert store.reference_view()["padded"] == {"MRN-2 ": "c"} diff --git a/tests/test_sqlserver_store_open_pool_leak.py b/tests/test_sqlserver_store_open_pool_leak.py index 6ce79a602b..5dd032eeea 100644 --- a/tests/test_sqlserver_store_open_pool_leak.py +++ b/tests/test_sqlserver_store_open_pool_leak.py @@ -224,7 +224,7 @@ async def _checkpoint( settles.append(settle) monkeypatch.setattr(SqlServerStore, "_ensure_schema", _noop) - monkeypatch.setattr(SqlServerStore, "_report_state_key_collation", _noop) + monkeypatch.setattr(SqlServerStore, "_report_key_collations", _noop) monkeypatch.setattr(sqlserver_module, "check_open_store_pin", _noop) monkeypatch.setattr(sqlserver_module, "bind_store_salt", _noop) monkeypatch.setattr(SqlServerStore, "checkpoint_cipher_invocations", _checkpoint) diff --git a/tests/test_transform_state.py b/tests/test_transform_state.py index 8e7bc80ca3..f4ce7d8d28 100644 --- a/tests/test_transform_state.py +++ b/tests/test_transform_state.py @@ -157,10 +157,14 @@ def test_setstate_bounds_each_field_and_the_pair_in_utf16_units() -> None: # A lone surrogate is refused as a key fault, not raised as a bare UnicodeEncodeError, and at # construction rather than inside the handoff, where the backend's bind of the key would raise # it as a store error. cell_aad binds a lone surrogate via surrogatepass (BACKLOG #5962). - for lone in (chr(0xD800), chr(0xDFFF), "MRN-" + chr(0xDC80)): - with pytest.raises(StateKeyError, match="lone surrogate") as exc: - SetState("ns", lone, 1) - assert "MRN" not in str(exc.value) + # BACKLOG #6613: a valid pair held as two code points (U+D83D U+DE00, not U+1F600) is refused + # too, since no backend stores it as two code points either, and the message no longer calls + # it a lone surrogate. + pair = chr(0xD83D) + chr(0xDE00) + for surrogate in (chr(0xD800), chr(0xDFFF), "MRN-" + chr(0xDC80), "MRN-" + pair): + with pytest.raises(StateKeyError, match=r"surrogate code point \(U\+D800") as exc: + SetState("ns", surrogate, 1) + assert "MRN" not in str(exc.value) and "lone" not in str(exc.value) # Nothing chained: the encode error's `.object` is the whole key. assert exc.value.__cause__ is None and exc.value.__context__ is None # A non-ASCII key already over the limit in code points is refused without an encode. From 20b3e3d51ecbad7de4fa21ff5d608772a0b5dd88 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:46:32 -0600 Subject: [PATCH 31/49] docs: reference-set key rules on every backend, and the SetState surrogate wording (BACKLOG #6613) CONFIGURATION.md's Reference sets section states the key and set-name refusals every backend now applies, what the ordinals count, and that SQL Server reports the reference tables' collation. The SetState keys paragraph names any surrogate code point, and says only a failed metadata read stops the open. ADR 0006 gains a dated amendment. A changelog fragment corrects the 0.5.3 entry that said each SetState refusal names a length. BACKLOG #6613 Proposed PR title: Reference keys some backend cannot hold are refused on every backend (BACKLOG #6613) Proposed vault banner: SHIPPED. Every backend refuses padded and NUL reference keys before the transaction (ReferenceSnapshotRefused), a padded or NUL set name at load; SQL Server reports the reference tables' collation; the state note rides only UnauthenticatedCipherError; items 5 to 9 fixed. Item 3's refusal at open not built: it would refuse a pre-#1588 store that opens today. Verified-by: none --- .../6613-setstate-entry-correction.fixed.md | 3 +++ docs/CONFIGURATION.md | 19 ++++++++++++++++--- docs/adr/0006-external-data-lookups.md | 4 ++++ 3 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 changelog.d/6613-setstate-entry-correction.fixed.md diff --git a/changelog.d/6613-setstate-entry-correction.fixed.md b/changelog.d/6613-setstate-entry-correction.fixed.md new file mode 100644 index 0000000000..3b58c21dfb --- /dev/null +++ b/changelog.d/6613-setstate-entry-correction.fixed.md @@ -0,0 +1,3 @@ +- **Correction to the 0.5.3 entry on `SetState` key refusals.** It said each refusal names the + field and its length. Each names the field and the rule, never the value; only a refusal for + length also gives the length in UTF-16 code units. (`BACKLOG #6613`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5ca2f96196..4310c8e9b9 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -708,19 +708,21 @@ def anonymize(msg): is an **upsert by `(namespace, key)`** the engine applies **inside the routed→outbound handoff transaction**. `Send`-only Handlers are unchanged — fully **backward compatible**. - **Keys are exact, and bounded.** `namespace` and `key` must be non-empty strings that do not end - in a space (U+0020) and contain no NUL (U+0000) and no lone surrogate (U+D800 to U+DFFF). Each is + in a space (U+0020) and contain no NUL (U+0000) and no surrogate code point (U+D800 to U+DFFF), + whether lone or half of a pair held as two code points. Each is at most 256 UTF-16 code units, and the two together at most 450. `SetState(...)` raises `StateKeyError` (a `WiringError`) at construction otherwise, on every store backend, and the error names the field, never its value. Why: SQL Server ignores trailing spaces when it compares keys, so `k` and `k ` would otherwise be one stored row there and two everywhere else; Postgres text - cannot hold NUL; no backend stores a lone surrogate; and SQL Server's `state` columns are + cannot hold NUL; no backend stores a surrogate code point; and SQL Server's `state` columns are `NVARCHAR(256)` under a clustered primary key capped at 900 bytes. A field read from a fixed-width sender can carry padding: strip it before keying on it, for example `(msg["PID-3.1"] or "").rstrip(" ")`. Case and accents are compared exactly on SQLite, on Postgres, and on a SQL Server database whose `state` table this release or a later one created. A SQL Server `state` table created earlier keeps the database's default collation, which may fold case (BACKLOG #1588); the engine logs a WARNING at every open of a table whose key columns are not - binary, naming the collation and the remedy, and repairs nothing (BACKLOG #4917). + binary, naming the collation and the remedy, and repairs nothing (BACKLOG #4917). The open + goes on after the warning; only a failure of the metadata read itself stops it. - **Exactly-once / re-run safety.** Because the write commits in the **same transaction** as the outbound rows, a crash before commit leaves **no** state (atomic with the handoff) and the attempt that commits applies the write **exactly once per message** — this preserves the staged pipeline's @@ -811,6 +813,17 @@ crash-re-run — the same accepted caveat as a code-set hot-reload). seconds, default `30`, `0` = no limit) bounds each call, the execute and each fetch, and a result that does not fit its columns, at least a missing or doubled column, a NULL key or a duplicate key, fails the sync rather than replacing the last-good snapshot; see [`CONNECTIONS.md`](CONNECTIONS.md) §*A `DatabaseRef` statement passes the same gate, and a row ceiling*. +- **Keys and set names are exact.** Every store backend refuses a snapshot holding two keys that + differ only by trailing spaces (U+0020), which SQL Server compares as equal, or a key holding + NUL (U+0000), which Postgres text cannot store, before the snapshot's transaction (BACKLOG + #4917, #6613). The sync then fails and alerts every interval until the source changes, and the + last-good snapshot stays active. The log line names the set and the keys by 0-based ordinal, + their position among the keys the source yielded, never a key; an ordinal is not a file line + number. A lone key with a trailing space is not refused. A `Reference(...)` name that ends in a + space or holds NUL is refused at load, on every backend, since SQL Server would read `npi` and + `npi ` as one set. SQL Server also bounds a key at 450 UTF-16 code units and a set name at + 256, and reports a non-binary collation on the `reference` and `reference_version` key + columns at open, at WARNING, repairing nothing. - **Sync.** The engine's `ReferenceSyncRunner` materializes each set once at startup (before listeners serve, so `reference(...)` resolves on the first message) and every `refresh_seconds`. A source failure is **isolated**: it's logged + alerted and the **last-good snapshot is kept** (the write diff --git a/docs/adr/0006-external-data-lookups.md b/docs/adr/0006-external-data-lookups.md index 450bb44539..ec3f6a4b67 100644 --- a/docs/adr/0006-external-data-lookups.md +++ b/docs/adr/0006-external-data-lookups.md @@ -296,6 +296,10 @@ first-ever reference-row key-rotation tests on all three backends. Server `write_reference_snapshot` now refuses such a snapshot before its transaction with `ReferenceKeyCollision`, naming the two keys by ordinal only. The sync still fails and alerts every interval, and the last-good snapshot stays active, as it did when the INSERT failed. + **AMENDED 2026-12-01 (BACKLOG #6613):** the refusal moved to + `store/reference_keys.py`, which SQLite and Postgres call too, so a set behaves the same on + every backend; it also refuses a key holding U+0000, which Postgres text cannot store, as a + `ReferenceSnapshotRefused`, the collision's base class. - **Encryption at rest.** Values are `cipher.encrypt(json.dumps(v))` (`mfenc`), covered by **both** `reencrypt_to_active` (key rotation) **and** `_encrypt_existing_rows` (the no-key→key migration pass). The migration pass is required because "born encrypted" is false: under a no-key deployment From 64e91a908d48789d9c6d2a456a73dbff70a8108c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:14:37 -0600 Subject: [PATCH 32/49] reference keys: review round 1 fixes, preview and rename keep the rules (BACKLOG #6613) The dry-run reference preview runs the shared key guard, so check no longer passes a Handler against a set every backend refuses. A rename to a set name ending in a space is refused at plan time. The guard also refuses a surrogate code point in a key, which surfaced as a bare UnicodeEncodeError. A non-string set name reaches the registry as before. SQL Server: the reference collation warning names the tables that fold and says what that does to names and keys; the state-cache note's docstring says a key not supplied fails the tag too; the width constant's comment gives the real byte sum, and a test pins both constants to the DDL; an ASCII key skips the UTF-16 encode. The vacuous width-guard control is gone, and the trailing-space twin test expects the name rule's refusal, which now fires first. Claims now name the rules the guard applies rather than every backend limit. BACKLOG #6613 Verified-by: tests --- messagefoundry/config/impact.py | 6 +++ messagefoundry/config/wiring.py | 14 ++++--- messagefoundry/pipeline/dryrun.py | 16 +++++++- messagefoundry/store/postgres.py | 4 +- messagefoundry/store/reference_keys.py | 18 +++++--- messagefoundry/store/sqlserver.py | 35 ++++++++-------- messagefoundry/store/store.py | 4 +- tests/test_connection_name_rule.py | 17 ++++++-- tests/test_reference_key_guard.py | 11 +++++ tests/test_reference_sets.py | 41 +++++++++++++++++++ ...test_sqlserver_state_key_limits_offline.py | 39 ++++++++---------- 11 files changed, 147 insertions(+), 58 deletions(-) diff --git a/messagefoundry/config/impact.py b/messagefoundry/config/impact.py index 2c7e6bc69d..e82a84d9e1 100644 --- a/messagefoundry/config/impact.py +++ b/messagefoundry/config/impact.py @@ -3334,6 +3334,12 @@ def _validate_new_name(config_dir: Path, target_kind: str, new: str) -> None: f"the new name {new!r} is not a valid connection name: it must match " f"{CONNECTION_NAME_PATTERN}" ) + # A renamed reference set must still load: Registry.add_reference refuses a set name ending in a + # space (BACKLOG #6613). U+0000 is a control character, refused above. + if target_kind == "reference" and new.endswith(" "): + raise WiringError( + f"the new name {new!r} is not a valid set name: it must not end with a space" + ) if target_kind in _FILE_BACKED_KINDS: # Reuse the exact traversal/drive/containment rules the codeset writer enforces on a file stem. from messagefoundry.config.code_sets import CODESETS_DIR_NAME diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index d9c09bec21..42a3ca31a2 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -7575,13 +7575,15 @@ def add_handler(self, name: str, fn: HandlerFn, accepts: HandlerAccepts | None = self.handler_accepts[name] = accepts def add_reference(self, spec: ReferenceSpec) -> None: - # BACKLOG #6613: SQL Server pads a trailing space when it compares reference_version.name - # (the `state` comment in store/sqlserver.py's _SCHEMA says why), so `npi` and `npi ` would - # be one set there, each sync overwriting the other's; Postgres text cannot hold U+0000. - # Refused on every backend, as SetState refuses such a key. - if spec.name.endswith(" "): + # BACKLOG #6613: SQL Server pads a trailing space when it compares a set name (the `state` + # comment in store/sqlserver.py's _SCHEMA says why). case_twins already refuses `npi` beside + # `npi ` in one graph, but not across reloads: a set renamed from one to the other would + # share the stored rows of the old one there, where SQLite and Postgres keep them apart. + # Postgres text cannot hold U+0000. Refused on every backend, as SetState refuses such a + # key. A name that is not a string is left to graph_problems, as before. + if isinstance(spec.name, str) and spec.name.endswith(" "): raise WiringError(f"reference set {spec.name!r}: a set name must not end with a space") - if "\x00" in spec.name: + if isinstance(spec.name, str) and "\x00" in spec.name: raise WiringError( f"reference set {spec.name!r}: a set name must not contain U+0000 (NUL)" ) diff --git a/messagefoundry/pipeline/dryrun.py b/messagefoundry/pipeline/dryrun.py index ee9f3ad3de..a8af9ae49f 100644 --- a/messagefoundry/pipeline/dryrun.py +++ b/messagefoundry/pipeline/dryrun.py @@ -74,6 +74,10 @@ from messagefoundry.pipeline.sandbox import SandboxMode, SandboxSession, run_sandboxed from messagefoundry.store import MessageStatus from messagefoundry.store.metadata import encode_reference_value +from messagefoundry.store.reference_keys import ( + ReferenceSnapshotRefused, + refuse_unstorable_reference_keys, +) __all__ = [ "DeliveryPreview", @@ -715,7 +719,8 @@ def dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: engine's reference cache returns (BACKLOG #1174): a TOML date is an ISO string in both. Each read decodes its own copy, as the engine's does (:class:`_PreviewReferenceSet`). A set the store would refuse to encode is omitted, as the live sync would refuse to commit it. So is - a set whose file did not load (vault BACKLOG #3340); both log a warning naming it, the second once + a set whose keys break a rule every store backend refuses (BACKLOG #6613), and a set whose file + did not load (vault BACKLOG #3340); both log a warning naming it, the second once per set per process. Every call reads every file again. A caller previewing many messages against one graph, as @@ -729,9 +734,16 @@ def dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: if not isinstance(path, str): # an env() ref — unresolved in a pure dry-run continue try: + rows = load_code_set(path) + refuse_unstorable_reference_keys(spec.name, rows) view[spec.name] = _PreviewReferenceSet( - {k: encode_reference_value(v) for k, v in load_code_set(path).items()} + {k: encode_reference_value(v) for k, v in rows.items()} ) + except ReferenceSnapshotRefused as exc: + # BACKLOG #6613: every backend's write refuses this set, so the live sync never commits + # it. Its text names the set, the rule and key ordinals, never a key, as the sync logs it. + log.warning("dry-run: reference set skipped: %s", exc) + continue except CodeSetError: # A missing, malformed or unreadable file. Say so, or a later read of the set reports it # missing with nothing to say why. The set name only, never the loader's text: that can diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 031ac83095..0822670a54 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -5508,8 +5508,8 @@ async def write_reference_snapshot( """Materialize a new reference snapshot and atomically make it active (ADR 0006). In one transaction: drop the set's prior rows, insert the new snapshot (each value JSON-encoded then encrypted), and upsert the ``reference_version`` pointer. The read cache swaps only after - commit, so a failed sync leaves the last-good snapshot live. Ported, not stubbed. A key some - backend could not hold exactly, a NUL among them, is refused first (BACKLOG #6613).""" + commit, so a failed sync leaves the last-good snapshot live. Ported, not stubbed. The key rules + every backend shares, a NUL key among them, are applied first (BACKLOG #6613).""" refuse_unstorable_reference_keys(name, rows) encoded = [(k, encode_reference_value(v)) for k, v in rows.items()] encrypted = [ diff --git a/messagefoundry/store/reference_keys.py b/messagefoundry/store/reference_keys.py index e99a2a4e09..755d0a4fc9 100644 --- a/messagefoundry/store/reference_keys.py +++ b/messagefoundry/store/reference_keys.py @@ -3,10 +3,11 @@ """The reference-snapshot key rules every store backend applies before its transaction (BACKLOG #4917, #6613). -A key some backend could not hold exactly is refused on every backend, as ``SetState`` refuses -such a state key, so a set behaves the same wherever it runs. A leaf module, so each backend's +The rules here are refused on every backend, as ``SetState`` refuses such a state key, so a set +that breaks one fails the same way wherever it runs. Not every backend limit is here: SQL Server's +column widths stay its own ``_guard_reference_widths``. A leaf module, so each backend's ``write_reference_snapshot`` imports it at module level; ``store.base`` re-exports the two error -classes. +classes, and ``pipeline/dryrun.py`` runs the same rules in a preview. """ from __future__ import annotations @@ -39,10 +40,11 @@ class ReferenceKeyCollision(ReferenceSnapshotRefused): def refuse_unstorable_reference_keys(name: str, rows: Mapping[str, Any]) -> None: """Raise :class:`ReferenceSnapshotRefused` for a key holding U+0000, which Postgres text cannot - store, and :class:`ReferenceKeyCollision` for two keys equal once trailing U+0020 is stripped. + store, or a surrogate code point (U+D800..U+DFFF), which no backend stores, and + :class:`ReferenceKeyCollision` for two keys equal once trailing U+0020 is stripped. One pass. Only a key ending in a space can pad onto another, so only those are stripped and - held: usually none, so a large set costs a containment test and an ``endswith`` per key.""" + held: usually none. An ASCII key, the usual MRN-style one, skips the surrogate scan.""" padded: dict[str, int] = {} # stripped form of a space-ending key -> its ordinal for ordinal, key in enumerate(rows): if "\x00" in key: @@ -51,6 +53,12 @@ def refuse_unstorable_reference_keys(name: str, rows: Mapping[str, Any]) -> None " text cannot store; refusing the snapshot (key value withheld: reference keys" " may be PHI)" ) + if not key.isascii() and any("\ud800" <= ch <= "\udfff" for ch in key): + raise ReferenceSnapshotRefused( + f"reference set {name!r}: key #{ordinal} contains a surrogate code point" + " (U+D800..U+DFFF), which no backend stores; refusing the snapshot (key value" + " withheld: reference keys may be PHI)" + ) if not key.endswith(" "): continue stripped = key.rstrip(" ") diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index 98696296b9..8e0df1f3ab 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -801,8 +801,8 @@ def _utf16_units(text: str) -> int: #: ``reference.name``'s width in ``_SCHEMA``, in UTF-16 code units. _REFERENCE_NAME_MAX_UNITS: Final = 256 -#: ``reference.[key]``'s width in ``_SCHEMA``, in UTF-16 code units: the widest that keeps -#: ``pk_reference`` under SQL Server's 1700-byte nonclustered key cap. +#: ``reference.[key]``'s width in ``_SCHEMA``, in UTF-16 code units. ``pk_reference`` is then +#: 2*(256+64+450) = 1540 bytes, under SQL Server's 1700-byte nonclustered key cap. _REFERENCE_KEY_MAX_UNITS: Final = 450 @@ -10543,14 +10543,13 @@ async def _report_key_collations(self) -> str | None: " AND name IN ('namespace', 'key', 'name', 'version')" ) # Any binary collation compares code points, as the caches do; only a linguistic one folds. - found: dict[str, set[str]] = {} + found: dict[str, set[str]] = {} # table -> its folding collations for r in rows: collation = str(r["collation_name"]) # A token, not a suffix: Latin1_General_100_BIN2_UTF8 is binary too. if not {"BIN", "BIN2"} & set(collation.upper().split("_")): - group = "state" if r["table_name"] == "state" else "reference" - found.setdefault(group, set()).add(collation) - state = ", ".join(sorted(found["state"])) if "state" in found else None + found.setdefault(str(r["table_name"]), set()).add(collation) + state = ", ".join(sorted(found.pop("state"))) if "state" in found else None if state is not None: log.warning( "sqlserver: the state table's namespace/key columns use collation %s, not a binary" @@ -10562,16 +10561,18 @@ async def _report_key_collations(self) -> str | None: state, _STATE_KEY_COLLATION, ) - if "reference" in found: + if found: log.warning( - "sqlserver: the reference, reference_version tables' key columns use collation %s," - " not a binary one such as the %s the shipped DDL names. Keys this collation" - " compares as equal, such as ones differing only in case under a case-insensitive" - " collation, collide there, so a sync of a set holding both fails; the engine does" - " not repair them. Remedy: drop both tables and delete the schema_meta row, so the" + "sqlserver: the %s table's name/version/key columns use collation %s, not a binary" + " one such as the %s the shipped DDL names. Values this collation compares as" + " equal, such as ones differing only in case under a case-insensitive collation," + " are one value there: at least, two such keys fail a set's sync, and two such set" + " names share one stored set. The engine does not repair them. Remedy: drop the" + " reference and reference_version tables and delete the schema_meta row, so the" " next open (or provision-schema) re-runs the DDL batch and creates them again;" " the next sync then materializes each set from its source", - ", ".join(sorted(found["reference"])), + ", ".join(sorted(found)), + ", ".join(sorted(set().union(*found.values()))), _STATE_KEY_COLLATION, ) return state @@ -10582,8 +10583,9 @@ async def _load_state_cache(self, *, folded_collation: str | None = None) -> Non A failed AEAD tag (:class:`UnauthenticatedCipherError`) is how a row merged across a case or accent variant shows: its value was sealed to the other spelling. When :meth:`_report_key_collations` found a folding ``folded_collation``, that error carries a - note naming it (BACKLOG #4917, #6613). Any other ``CipherError``, a corrupt cell or a key - not supplied, is not such a merge and carries no note.""" + note naming it as a possible cause (BACKLOG #4917, #6613). A key not supplied fails the tag + too, so it carries the note as well. A plain ``CipherError``, such as a malformed cell, + cannot come from a merge and carries none.""" try: self._state_cache = await cipher_bulk_call( self._cipher, @@ -10706,7 +10708,8 @@ def _guard_reference_widths(self, name: str, rows: Mapping[str, Any]) -> None: f"({name_units} UTF-16 code units); refusing the snapshot" ) for ordinal, key in enumerate(rows): - units = _utf16_units(key) + # ASCII is one unit per char, so the usual MRN-style key skips the encode. + units = len(key) if key.isascii() else _utf16_units(key) if units > _REFERENCE_KEY_MAX_UNITS: digest = hashlib.sha256(key.encode()).hexdigest()[:12] raise ValueError( diff --git a/messagefoundry/store/store.py b/messagefoundry/store/store.py index d4a0c73d2d..af7429d044 100644 --- a/messagefoundry/store/store.py +++ b/messagefoundry/store/store.py @@ -15680,8 +15680,8 @@ async def write_reference_snapshot( (served from the in-memory cache) until this commits; a **failed** sync rolls back wholesale, so the last-good snapshot stays active (graceful degradation). The cache is swapped **only after** commit — a rolled-back write never leaks into :meth:`reference_view`. Replaces the whole set - (build-new-then-flip), so it is idempotent on a re-run with the same rows. A key some backend - could not hold exactly is refused first, as on every backend (BACKLOG #6613).""" + (build-new-then-flip), so it is idempotent on a re-run with the same rows. The key rules every + backend shares are applied first (BACKLOG #6613).""" refuse_unstorable_reference_keys(name, rows) encoded = [(k, encode_reference_value(v)) for k, v in rows.items()] encrypted = [ diff --git a/tests/test_connection_name_rule.py b/tests/test_connection_name_rule.py index c9ce9c409e..eb0b14d66f 100644 --- a/tests/test_connection_name_rule.py +++ b/tests/test_connection_name_rule.py @@ -402,12 +402,21 @@ def test_every_twin_table_pairs_a_rename_kind_with_its_own_registry_table() -> N @pytest.mark.parametrize( - ("first", "second"), - [("EPIC", "EPIC "), ("EPIC", "\uff25\uff30\uff29\uff23")], # a trailing space; full width + ("first", "second", "refusal"), + [ + # Since BACKLOG #6613 a set name ending in a space is refused on its own, at registration, + # before the twin check sees the pair. + ("EPIC", "EPIC ", "reference set 'EPIC ': a set name must not end with a space"), + ( + "EPIC", + "\uff25\uff30\uff29\uff23", + "duplicate reference set name: .*differs only in case", + ), + ], ids=["trailing_space", "full_width"], ) def test_a_reference_twin_by_width_or_trailing_space_is_refused( - tmp_path: Path, first: str, second: str + tmp_path: Path, first: str, second: str, refusal: str ) -> None: # A reference set name is not bound by the name rule, and SQL Server's `=` ignores a trailing # space and a _CI_AS collation ignores width, so casefold alone would let these load. @@ -417,7 +426,7 @@ def test_a_reference_twin_by_width_or_trailing_space_is_refused( + "\n", encoding="utf-8", ) - with pytest.raises(WiringError, match="duplicate reference set name: .*differs only in case"): + with pytest.raises(WiringError, match=refusal): load_config(tmp_path, allow_empty=True) diff --git a/tests/test_reference_key_guard.py b/tests/test_reference_key_guard.py index fddaa957b6..a645292643 100644 --- a/tests/test_reference_key_guard.py +++ b/tests/test_reference_key_guard.py @@ -47,6 +47,17 @@ def test_a_nul_in_a_key_is_refused_naming_its_ordinal_and_no_key() -> None: assert not isinstance(exc.value, ReferenceKeyCollision) +def test_a_surrogate_in_a_key_is_refused_naming_its_ordinal_and_no_key() -> None: + """No backend stores a surrogate code point: before this, the bind raised a bare + ``UnicodeEncodeError`` naming no set, rule or row. A lone one and a pair held as two code + points are each refused; the control, the same character as one code point, passes.""" + for key in ("MRN-" + chr(0xD800), "MRN-" + chr(0xD83D) + chr(0xDE00)): + with pytest.raises(ReferenceSnapshotRefused, match="key #1 contains a surrogate") as exc: + refuse_unstorable_reference_keys("set", {"A": 1, key: 2}) + assert "MRN" not in str(exc.value) + refuse_unstorable_reference_keys("set", {"MRN-\U0001f600": 1, "café": 2}) + + def test_keys_that_every_backend_holds_exactly_pass() -> None: """The controls: a lone trailing space, a leading space, a trailing tab, a case variant and another control character are each distinct on every backend and pass.""" diff --git a/tests/test_reference_sets.py b/tests/test_reference_sets.py index 3d7bfc499b..a489cd348e 100644 --- a/tests/test_reference_sets.py +++ b/tests/test_reference_sets.py @@ -672,6 +672,47 @@ def test_a_reference_set_name_some_backend_cannot_hold_is_refused(name: str, rul assert set(reg.references) == {"provider npi", " npi"} +def test_a_non_string_reference_set_name_still_reaches_the_registry() -> None: + """The name rule reads only a string, so a mistyped name keeps the path it had: it registers, + and ``graph_problems`` judges it, rather than an ``AttributeError`` naming no rule.""" + reg = Registry() + reg.add_reference(ReferenceSpec(name=42, source=FileRef(path="x.csv"))) # type: ignore[arg-type] + names: list[object] = list(reg.references) + assert names == [42] + + +def test_a_rename_to_a_padded_reference_set_name_is_refused_at_plan_time(tmp_path: Path) -> None: + """BACKLOG #6613: a renamed set must still load, so the plan refuses the name the registry + would refuse, before any file is rewritten. The control: an inner space is a valid set name.""" + from messagefoundry.config.impact import _validate_new_name + + with pytest.raises(WiringError, match="must not end with a space"): + _validate_new_name(tmp_path, "reference", "npi ") + _validate_new_name(tmp_path, "reference", "provider npi") + _validate_new_name(tmp_path, "router", "route ") # the rule is the reference set's only + + +def test_dryrun_omits_a_reference_set_every_backend_refuses( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + """BACKLOG #6613: a file-backed set holding two keys that differ only by trailing spaces is + refused by every store backend's write, so the live sync never commits it. The preview omits + it too, with a warning naming the set and the ordinals and no key, so ``check`` cannot pass a + Handler against a set the engine will never serve. The control: a clean set is previewed.""" + from messagefoundry.pipeline.dryrun import dry_run_reference_view + + padded = _csv(tmp_path / "padded.csv", "key,value\nMRN-1,9991\nMRN-1 ,9992\n") + clean = _csv(tmp_path / "clean.csv", "key,value\nMRN-1,9991\n") + reg = Registry() + reg.add_reference(ReferenceSpec(name="padded", source=FileRef(path=str(padded)))) + reg.add_reference(ReferenceSpec(name="clean", source=FileRef(path=str(clean)))) + with caplog.at_level("WARNING"): + view = dry_run_reference_view(reg) + assert set(view) == {"clean"} + assert "reference set 'padded': keys #0 and #1 differ only by trailing spaces" in caplog.text + assert "MRN" not in caplog.text + + def test_dryrun_resolves_file_reference(tmp_path: Path) -> None: # A handler that enriches via reference(...) resolves in a dry-run from the file-backed declaration. csv = _csv(tmp_path / "npi.csv", "key,value\nMED1,9991\n") diff --git a/tests/test_sqlserver_state_key_limits_offline.py b/tests/test_sqlserver_state_key_limits_offline.py index 3c7ad97cd2..63eebd403c 100644 --- a/tests/test_sqlserver_state_key_limits_offline.py +++ b/tests/test_sqlserver_state_key_limits_offline.py @@ -150,8 +150,9 @@ async def test_only_an_unauthenticated_row_names_the_drifted_collation( """The keyed symptom of a merged row is a failed AEAD tag at the cache warm-up, which the cipher raises as ``UnauthenticatedCipherError``. It still fails closed, and when the report found a folding collation the error carries a note naming it. The controls: with no drift - found there is no note, and a plain ``CipherError`` (a corrupt cell, a missing key) carries - none either, since a merged row cannot cause it (BACKLOG #6613).""" + found there is no note, and a plain ``CipherError`` (such as a malformed cell) carries none + either, since a merged row cannot cause it (BACKLOG #6613). A key not supplied also raises + ``UnauthenticatedCipherError``, so it carries the note, which names only a possible cause.""" def _refuse(*args: Any, **kwargs: Any) -> Any: raise error("could not decrypt a state row") @@ -172,30 +173,26 @@ def _refuse(*args: Any, **kwargs: Any) -> Any: async def test_reference_keys_differing_only_by_trailing_spaces_are_refused() -> None: """``pk_reference`` pads trailing spaces, so these would raise a PK duplicate mid-transaction. The write refuses first, through the guard every backend shares (BACKLOG #6613), naming both - keys by ordinal only: no value, and no hash of one.""" + keys by ordinal only: no value, and no hash of one. The rule's own cases and controls are in + ``tests/test_reference_key_guard.py``; this shows the SQL Server write reaches it.""" store = object.__new__(SqlServerStore) - for rows, first, later in ( - ({"MRN-1": 1, "MRN-1 ": 2}, 0, 1), - ({"MRN-1 ": 1, "other": 2, "MRN-1 ": 3}, 0, 2), # two padded keys, no bare one - ({"MRN-1 ": 1, "other": 2, "MRN-1": 3}, 0, 2), # the bare key comes later - ): - with pytest.raises(ReferenceKeyCollision, match="only by trailing spaces") as exc: - await store.write_reference_snapshot(name="set", version="v1", rows=rows) - text = str(exc.value) - assert f"keys #{first} and #{later} differ" in text - assert "MRN" not in text and "sha256" not in text # nothing of the key (PHI) - - -def test_reference_keys_that_do_not_collide_pass_the_width_guard() -> None: - """The controls: a lone trailing space, a leading space, a trailing tab, and a case variant are - each distinct under BIN2 and pass.""" - store = object.__new__(SqlServerStore) - store._guard_reference_widths("set", {"a ": 1, " a": 2, "a\t": 3, "A": 4, "b": 5}) + with pytest.raises(ReferenceKeyCollision, match="only by trailing spaces") as exc: + await store.write_reference_snapshot( + name="set", version="v1", rows={"MRN-1": 1, "MRN-1 ": 2} + ) + text = str(exc.value) + assert "keys #0 and #1 differ" in text + assert "MRN" not in text and "sha256" not in text # nothing of the key (PHI) def test_the_width_guard_counts_utf16_units_against_the_column_widths() -> None: """The name is ``NVARCHAR(256)`` and the key ``NVARCHAR(450)``, counted in UTF-16 code units: - each is accepted at its width and refused one unit over, an astral character counting two.""" + each is accepted at its width and refused one unit over, an astral character counting two. The + guard's constants are pinned to the shipped DDL, so a widened column fails here.""" + (ddl,) = [stmt for stmt in ss._SCHEMA if "CREATE TABLE reference (" in stmt] + assert f"name NVARCHAR({ss._REFERENCE_NAME_MAX_UNITS}) COLLATE" in ddl + assert f"[key] NVARCHAR({ss._REFERENCE_KEY_MAX_UNITS}) COLLATE" in ddl + assert (ss._REFERENCE_NAME_MAX_UNITS, ss._REFERENCE_KEY_MAX_UNITS) == (256, 450) store = object.__new__(SqlServerStore) astral = "\U0001f600" store._guard_reference_widths("n" * 256, {"k" * 450: 1, astral * 225: 2}) From f0a7edfc52d199f211eb651dfa9a8a5be2e0d7da Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:16:47 -0600 Subject: [PATCH 33/49] docs: reference-set key rules after review round 1 (BACKLOG #6613) CONFIGURATION.md and the changelog fragment add the surrogate key rule, the dry-run and check skip, and the rename refusal, and give the cross-reload reason for the set-name rule rather than the twin case graph validation already refuses. BACKLOG #6613 Proposed PR title: Reference keys some backend cannot hold are refused on every backend (BACKLOG #6613) Proposed vault banner: SHIPPED. Every backend refuses padded, NUL and surrogate reference keys before the transaction (ReferenceSnapshotRefused), and a padded or NUL set name at load and at rename; the preview skips such a set; SQL Server reports the reference tables' collation; the state note rides only UnauthenticatedCipherError; items 5 to 9 fixed. Item 3's refusal at open not built: it would refuse a pre-#1588 store that opens today. Verified-by: none --- changelog.d/6613.changed.md | 24 +++++++++++++----------- docs/CONFIGURATION.md | 24 ++++++++++++++---------- 2 files changed, 27 insertions(+), 21 deletions(-) diff --git a/changelog.d/6613.changed.md b/changelog.d/6613.changed.md index 88eae6f6b6..c767fccd7f 100644 --- a/changelog.d/6613.changed.md +++ b/changelog.d/6613.changed.md @@ -1,14 +1,16 @@ - **Every store backend refuses a reference snapshot whose keys some backend could not hold exactly, and a set name SQL Server would merge.** SQLite and Postgres now refuse, before the snapshot's transaction, two keys that differ only by trailing spaces, as SQL Server already - did, and every backend refuses a key holding U+0000 (NUL), which Postgres text cannot store. - Both are a `ReferenceSnapshotRefused` (the collision is its subclass `ReferenceKeyCollision`), - naming the set and the keys by 0-based ordinal, never a key, and logged whole; the last-good - snapshot stays active and the sync fails every interval until the source changes. A - `Reference(...)` name that ends in a space or holds U+0000 is refused at load on every backend, - since SQL Server would compare `npi` and `npi ` as one set. A SQL Server open now also reports - a non-binary collation on the `reference` and `reference_version` key columns, at WARNING, and - repairs nothing. The note naming a folding `state` collation now rides only a failed - authentication tag, the one error a merged row can cause. `SetState`'s refusal of a surrogate - code point now says so rather than "lone surrogate", since half of a pair is refused too, and - `StateKeyError` is exported from `messagefoundry`. (`BACKLOG #6613`) + did, and every backend refuses a key holding U+0000 (NUL), which Postgres text cannot store, + or a surrogate code point, which no backend stores. Each refusal is a + `ReferenceSnapshotRefused` (the collision is its subclass `ReferenceKeyCollision`), naming the + set and the keys by 0-based ordinal, never a key, and logged whole; the last-good snapshot + stays active and the sync fails every interval until the source changes. A dry run and + `check` skip such a file-backed set with the same warning. A `Reference(...)` name that ends in + a space or holds U+0000 is refused at load on every backend, and so is a rename to such a + name, since SQL Server compares `npi` and `npi ` as one name. A SQL Server open now also + reports a non-binary collation on the `reference` and `reference_version` key columns, at + WARNING, and repairs nothing. The note naming a folding `state` collation now rides only a + failed authentication tag, the one error a merged row can cause. `SetState`'s refusal of a + surrogate code point now says so rather than "lone surrogate", since half of a pair is refused + too, and `StateKeyError` is exported from `messagefoundry`. (`BACKLOG #6613`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 4310c8e9b9..ffa9f496c1 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -814,16 +814,20 @@ crash-re-run — the same accepted caveat as a code-set hot-reload). that does not fit its columns, at least a missing or doubled column, a NULL key or a duplicate key, fails the sync rather than replacing the last-good snapshot; see [`CONNECTIONS.md`](CONNECTIONS.md) §*A `DatabaseRef` statement passes the same gate, and a row ceiling*. - **Keys and set names are exact.** Every store backend refuses a snapshot holding two keys that - differ only by trailing spaces (U+0020), which SQL Server compares as equal, or a key holding - NUL (U+0000), which Postgres text cannot store, before the snapshot's transaction (BACKLOG - #4917, #6613). The sync then fails and alerts every interval until the source changes, and the - last-good snapshot stays active. The log line names the set and the keys by 0-based ordinal, - their position among the keys the source yielded, never a key; an ordinal is not a file line - number. A lone key with a trailing space is not refused. A `Reference(...)` name that ends in a - space or holds NUL is refused at load, on every backend, since SQL Server would read `npi` and - `npi ` as one set. SQL Server also bounds a key at 450 UTF-16 code units and a set name at - 256, and reports a non-binary collation on the `reference` and `reference_version` key - columns at open, at WARNING, repairing nothing. + differ only by trailing spaces (U+0020), which SQL Server compares as equal, a key holding NUL + (U+0000), which Postgres text cannot store, or a key holding a surrogate code point (U+D800 to + U+DFFF), which no backend stores, before the snapshot's transaction (BACKLOG #4917, #6613). The + sync then fails and alerts every interval until the source changes, and the last-good snapshot + stays active. The log line names the set and the keys by 0-based ordinal, their position among + the keys the source yielded, never a key; an ordinal is not a file line number. A lone key with + a trailing space is not refused. A dry run and `messagefoundry check` skip such a file-backed + set with the same warning, so a Handler is not previewed against a set the engine never serves. + A `Reference(...)` name that ends in a space or holds NUL is refused at load, on every backend, + and so is a rename to such a name. SQL Server compares `npi` and `npi ` as one name, so a set + renamed from one to the other across a reload would share the old set's stored rows there; one + graph declaring both is refused as twins either way. SQL Server also bounds a key at 450 UTF-16 + code units and a set name at 256, and reports a non-binary collation on the `reference` and + `reference_version` key columns at open, at WARNING, repairing nothing. - **Sync.** The engine's `ReferenceSyncRunner` materializes each set once at startup (before listeners serve, so `reference(...)` resolves on the first message) and every `refresh_seconds`. A source failure is **isolated**: it's logged + alerted and the **last-good snapshot is kept** (the write From 77fa5a3075d3d815cfc6c1349c058bb2444cc0de Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:37:10 -0600 Subject: [PATCH 34/49] reference keys: review round 2 fixes (BACKLOG #6613) A set name holding a surrogate code point is refused at load, as the rename path already refused it. The reference guard reuses controlchars.has_lone_surrogate. The dry-run warning for a refused set is logged once per set per process. The SQL Server collation warning names each folding table.column, and a comment at the report call records why it warns rather than refuses. The add_reference comment no longer credits case_twins with the same-graph case, and a database-lookup test keeps the twin check's trailing-space fold covered. BACKLOG #6613 Verified-by: tests --- messagefoundry/config/wiring.py | 37 +++++++++++++------ messagefoundry/pipeline/dryrun.py | 13 +++++-- messagefoundry/store/reference_keys.py | 4 +- messagefoundry/store/sqlserver.py | 12 ++++-- tests/test_connection_name_rule.py | 13 +++++++ tests/test_reference_key_guard.py | 3 +- tests/test_reference_sets.py | 19 ++++++++-- ...test_sqlserver_state_key_limits_offline.py | 3 +- 8 files changed, 77 insertions(+), 27 deletions(-) diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index 42a3ca31a2..c5b954a268 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -145,7 +145,11 @@ def handle(msg): is_connection_name, reference_record_name, ) -from messagefoundry.controlchars import scrub_control_chars, scrub_log_argument +from messagefoundry.controlchars import ( + has_lone_surrogate, + scrub_control_chars, + scrub_log_argument, +) from messagefoundry.credential import QUALIFIED_CERT_NAME, unmatchable_san_reason from messagefoundry.exception_origin import ( exception_chain, @@ -7576,17 +7580,26 @@ def add_handler(self, name: str, fn: HandlerFn, accepts: HandlerAccepts | None = def add_reference(self, spec: ReferenceSpec) -> None: # BACKLOG #6613: SQL Server pads a trailing space when it compares a set name (the `state` - # comment in store/sqlserver.py's _SCHEMA says why). case_twins already refuses `npi` beside - # `npi ` in one graph, but not across reloads: a set renamed from one to the other would - # share the stored rows of the old one there, where SQLite and Postgres keep them apart. - # Postgres text cannot hold U+0000. Refused on every backend, as SetState refuses such a - # key. A name that is not a string is left to graph_problems, as before. - if isinstance(spec.name, str) and spec.name.endswith(" "): - raise WiringError(f"reference set {spec.name!r}: a set name must not end with a space") - if isinstance(spec.name, str) and "\x00" in spec.name: - raise WiringError( - f"reference set {spec.name!r}: a set name must not contain U+0000 (NUL)" - ) + # comment in store/sqlserver.py's _SCHEMA says why), so a set renamed from `npi` to `npi ` + # across a reload would share the old set's stored rows there, where SQLite and Postgres + # keep them apart. This refusal comes first, so case_twins' trailing-space fold no longer + # sees a reference set name. Postgres text cannot hold U+0000, and no backend stores a + # surrogate code point. Refused on every backend, as SetState refuses such a key. A name + # that is not a string is left to graph_problems, as before. + if isinstance(spec.name, str): + if spec.name.endswith(" "): + raise WiringError( + f"reference set {spec.name!r}: a set name must not end with a space" + ) + if "\x00" in spec.name: + raise WiringError( + f"reference set {spec.name!r}: a set name must not contain U+0000 (NUL)" + ) + if has_lone_surrogate(spec.name): + raise WiringError( + f"reference set {spec.name!r}: a set name must not contain a surrogate code" + " point (U+D800..U+DFFF)" + ) self._add(self.references, spec.name, spec, "reference set") def add_lookup(self, spec: DatabaseLookupSpec) -> None: diff --git a/messagefoundry/pipeline/dryrun.py b/messagefoundry/pipeline/dryrun.py index a8af9ae49f..c6d657677a 100644 --- a/messagefoundry/pipeline/dryrun.py +++ b/messagefoundry/pipeline/dryrun.py @@ -684,6 +684,8 @@ def transform_one( #: The ``(set name, file path)`` pairs whose skip :func:`dry_run_reference_view` has already logged #: in this process; the path too, so another config's set of the same name still logs. A test resets it. _skipped_reference_sets_logged: set[tuple[str, str]] = set() +#: The same, for a set whose keys every store backend refuses (BACKLOG #6613). +_refused_reference_sets_logged: set[tuple[str, str]] = set() class _PreviewReferenceSet(Mapping[str, Any]): @@ -720,8 +722,8 @@ def dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: read decodes its own copy, as the engine's does (:class:`_PreviewReferenceSet`). A set the store would refuse to encode is omitted, as the live sync would refuse to commit it. So is a set whose keys break a rule every store backend refuses (BACKLOG #6613), and a set whose file - did not load (vault BACKLOG #3340); both log a warning naming it, the second once - per set per process. + did not load (vault BACKLOG #3340). Each logs a warning naming it; the last two log once per set + per process. Every call reads every file again. A caller previewing many messages against one graph, as ``check`` does, builds the view once and passes it to :func:`dry_run` as ``reference_view`` @@ -741,8 +743,11 @@ def dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: ) except ReferenceSnapshotRefused as exc: # BACKLOG #6613: every backend's write refuses this set, so the live sync never commits - # it. Its text names the set, the rule and key ordinals, never a key, as the sync logs it. - log.warning("dry-run: reference set skipped: %s", exc) + # this content. Its text names the set, the rule and key ordinals, never a key, as the + # sync logs it. Once per set per process, as for a file that did not load below. + if (spec.name, path) not in _refused_reference_sets_logged: + _refused_reference_sets_logged.add((spec.name, path)) + log.warning("dry-run: reference set skipped: %s", exc) continue except CodeSetError: # A missing, malformed or unreadable file. Say so, or a later read of the set reports it diff --git a/messagefoundry/store/reference_keys.py b/messagefoundry/store/reference_keys.py index 755d0a4fc9..133d3b6e0e 100644 --- a/messagefoundry/store/reference_keys.py +++ b/messagefoundry/store/reference_keys.py @@ -15,6 +15,8 @@ from collections.abc import Mapping from typing import Any +from messagefoundry.controlchars import has_lone_surrogate + __all__ = [ "ReferenceKeyCollision", "ReferenceSnapshotRefused", @@ -53,7 +55,7 @@ def refuse_unstorable_reference_keys(name: str, rows: Mapping[str, Any]) -> None " text cannot store; refusing the snapshot (key value withheld: reference keys" " may be PHI)" ) - if not key.isascii() and any("\ud800" <= ch <= "\udfff" for ch in key): + if not key.isascii() and has_lone_surrogate(key): raise ReferenceSnapshotRefused( f"reference set {name!r}: key #{ordinal} contains a surrogate code point" " (U+D800..U+DFFF), which no backend stores; refusing the snapshot (key value" diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index 8e0df1f3ab..d5ebd8e479 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -4606,7 +4606,9 @@ async def open( store._read_only = read_only await store._ensure_schema(create=create, read_only=read_only) # Right after the schema, so a later open step that fails still leaves the report - # logged; read-only included, since it reads metadata only (BACKLOG #4917). + # logged; read-only included, since it reads metadata only (BACKLOG #4917). It warns and + # does not refuse: a refusal would refuse a store whose pre-#1588 state table opens + # today (BACKLOG #6613 item 3, not built). folded = await store._report_key_collations() if store._fifo_claim_proc: # ADR 0114 sub-lever A startup gate (AC-7): verify the deployed procs (existence + @@ -10544,11 +10546,13 @@ async def _report_key_collations(self) -> str | None: ) # Any binary collation compares code points, as the caches do; only a linguistic one folds. found: dict[str, set[str]] = {} # table -> its folding collations + columns: dict[str, list[str]] = {} # table -> its folding columns for r in rows: collation = str(r["collation_name"]) # A token, not a suffix: Latin1_General_100_BIN2_UTF8 is binary too. if not {"BIN", "BIN2"} & set(collation.upper().split("_")): found.setdefault(str(r["table_name"]), set()).add(collation) + columns.setdefault(str(r["table_name"]), []).append(str(r["name"])) state = ", ".join(sorted(found.pop("state"))) if "state" in found else None if state is not None: log.warning( @@ -10563,15 +10567,15 @@ async def _report_key_collations(self) -> str | None: ) if found: log.warning( - "sqlserver: the %s table's name/version/key columns use collation %s, not a binary" - " one such as the %s the shipped DDL names. Values this collation compares as" + "sqlserver: reference set columns %s use collation %s, not a binary one such as" + " the %s the shipped DDL names. Values this collation compares as" " equal, such as ones differing only in case under a case-insensitive collation," " are one value there: at least, two such keys fail a set's sync, and two such set" " names share one stored set. The engine does not repair them. Remedy: drop the" " reference and reference_version tables and delete the schema_meta row, so the" " next open (or provision-schema) re-runs the DDL batch and creates them again;" " the next sync then materializes each set from its source", - ", ".join(sorted(found)), + ", ".join(f"{t}.{c}" for t in sorted(found) for c in sorted(columns[t])), ", ".join(sorted(set().union(*found.values()))), _STATE_KEY_COLLATION, ) diff --git a/tests/test_connection_name_rule.py b/tests/test_connection_name_rule.py index eb0b14d66f..849bf39750 100644 --- a/tests/test_connection_name_rule.py +++ b/tests/test_connection_name_rule.py @@ -430,6 +430,19 @@ def test_a_reference_twin_by_width_or_trailing_space_is_refused( load_config(tmp_path, allow_empty=True) +def test_a_database_lookup_twin_by_a_trailing_space_is_refused(tmp_path: Path) -> None: + # A reference set name ending in a space is now refused on its own (BACKLOG #6613), so the + # trailing-space fold in case_twins is exercised here, by a database lookup name. + (tmp_path / "lookups.py").write_text( + "from messagefoundry import DatabaseLookup\n" + + "\n".join(_LOOKUP_CALL.format(name=name) for name in ("EPIC", "EPIC ")) + + "\n", + encoding="utf-8", + ) + with pytest.raises(WiringError, match="duplicate database lookup name: .*differs only in case"): + load_config(tmp_path, allow_empty=True) + + def test_the_twin_fold_keeps_a_no_break_space_and_a_superscript_apart(tmp_path: Path) -> None: # The fold adds width and trailing U+0020 to casefold, and no more: a no-break space and a # superscript are compared as written. Whether a given SQL Server collation also keeps these diff --git a/tests/test_reference_key_guard.py b/tests/test_reference_key_guard.py index a645292643..df90fc87df 100644 --- a/tests/test_reference_key_guard.py +++ b/tests/test_reference_key_guard.py @@ -4,7 +4,8 @@ hold exactly, before its transaction, as ``SetState`` refuses such a state key on every backend. The rules: two keys that differ only by trailing spaces (SQL Server pads them in ``pk_reference``), -and a key holding U+0000 (Postgres text cannot store it). The SQLite store is opened for real; the +a key holding U+0000 (Postgres text cannot store it), and a key holding a surrogate code point (no +backend stores one). The SQLite store is opened for real; the Postgres and SQL Server stores are built bare with ``object.__new__``, so each test shows the guard runs before the store touches its cipher or its database. Not env-gated. """ diff --git a/tests/test_reference_sets.py b/tests/test_reference_sets.py index a489cd348e..f8c5c5448b 100644 --- a/tests/test_reference_sets.py +++ b/tests/test_reference_sets.py @@ -656,7 +656,11 @@ def test_reference_declaration_registers() -> None: @pytest.mark.parametrize( ("name", "rule"), - [("npi ", "must not end with a space"), ("np\x00i", r"must not contain U\+0000")], + [ + ("npi ", "must not end with a space"), + ("np\x00i", r"must not contain U\+0000"), + ("np\ud800i", "must not contain a surrogate code point"), + ], ) def test_a_reference_set_name_some_backend_cannot_hold_is_refused(name: str, rule: str) -> None: """BACKLOG #6613: SQL Server pads a trailing space when it compares ``reference_version.name``, @@ -693,14 +697,19 @@ def test_a_rename_to_a_padded_reference_set_name_is_refused_at_plan_time(tmp_pat def test_dryrun_omits_a_reference_set_every_backend_refuses( - tmp_path: Path, caplog: pytest.LogCaptureFixture + tmp_path: Path, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: """BACKLOG #6613: a file-backed set holding two keys that differ only by trailing spaces is refused by every store backend's write, so the live sync never commits it. The preview omits it too, with a warning naming the set and the ordinals and no key, so ``check`` cannot pass a - Handler against a set the engine will never serve. The control: a clean set is previewed.""" + Handler against a set the next sync refuses. The warning is logged once per set per process, + since a caller that passes no view rebuilds it for every message. The control: a clean set is + previewed.""" + from messagefoundry.pipeline import dryrun from messagefoundry.pipeline.dryrun import dry_run_reference_view + monkeypatch.setattr(dryrun, "_refused_reference_sets_logged", set()) + padded = _csv(tmp_path / "padded.csv", "key,value\nMRN-1,9991\nMRN-1 ,9992\n") clean = _csv(tmp_path / "clean.csv", "key,value\nMRN-1,9991\n") reg = Registry() @@ -708,8 +717,10 @@ def test_dryrun_omits_a_reference_set_every_backend_refuses( reg.add_reference(ReferenceSpec(name="clean", source=FileRef(path=str(clean)))) with caplog.at_level("WARNING"): view = dry_run_reference_view(reg) + assert set(dry_run_reference_view(reg)) == {"clean"} # a second build, as per message assert set(view) == {"clean"} - assert "reference set 'padded': keys #0 and #1 differ only by trailing spaces" in caplog.text + needle = "reference set 'padded': keys #0 and #1 differ only by trailing spaces" + assert caplog.text.count(needle) == 1 assert "MRN" not in caplog.text diff --git a/tests/test_sqlserver_state_key_limits_offline.py b/tests/test_sqlserver_state_key_limits_offline.py index 63eebd403c..410dd498a2 100644 --- a/tests/test_sqlserver_state_key_limits_offline.py +++ b/tests/test_sqlserver_state_key_limits_offline.py @@ -116,7 +116,8 @@ async def test_a_folding_reference_table_is_reported_on_its_own( assert await store._report_key_collations() is None (record,) = caplog.records text = record.getMessage() - assert "reference, reference_version" in text and "Latin1_General_CI_AS" in text + assert "reference.key" in text and "reference_version.name" in text + assert "reference_version.key" not in text and "Latin1_General_CI_AS" in text assert "does not repair" in text and "materializes each set from its source" in text From 20a74d0fb16e0acbcc5eea45f40db3145251b916 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:38:12 -0600 Subject: [PATCH 35/49] docs: reference-set key rules after review round 2 (BACKLOG #6613) The changelog headline names the three key rules and says SQL Server's widths stay its own. CONFIGURATION.md says the preview warning names the same set, rule and ordinals, and that an engine that synced the set keeps serving its last-good snapshot. ADR 0006's amendment lists every rule the change adds, and the surrogate set-name refusal. BACKLOG #6613 Proposed PR title: Reference keys some backend cannot hold are refused on every backend (BACKLOG #6613) Proposed vault banner: SHIPPED. Every backend refuses padded, NUL and surrogate reference keys before the transaction (ReferenceSnapshotRefused), and such a set name at load and at rename; the preview skips such a set; SQL Server reports the reference tables' collation; the state note rides only UnauthenticatedCipherError; items 5 to 9 fixed. Item 3's refusal at open not built: it would refuse a pre-#1588 store that opens today. Verified-by: none --- changelog.d/6613.changed.md | 29 +++++++++++++------------- docs/CONFIGURATION.md | 15 ++++++------- docs/adr/0006-external-data-lookups.md | 9 +++++--- 3 files changed, 29 insertions(+), 24 deletions(-) diff --git a/changelog.d/6613.changed.md b/changelog.d/6613.changed.md index c767fccd7f..e7010964a6 100644 --- a/changelog.d/6613.changed.md +++ b/changelog.d/6613.changed.md @@ -1,16 +1,17 @@ -- **Every store backend refuses a reference snapshot whose keys some backend could not hold - exactly, and a set name SQL Server would merge.** SQLite and Postgres now refuse, before the - snapshot's transaction, two keys that differ only by trailing spaces, as SQL Server already - did, and every backend refuses a key holding U+0000 (NUL), which Postgres text cannot store, - or a surrogate code point, which no backend stores. Each refusal is a - `ReferenceSnapshotRefused` (the collision is its subclass `ReferenceKeyCollision`), naming the +- **Every store backend refuses a reference snapshot holding padded, NUL or surrogate keys, and a + set name SQL Server would merge.** SQL Server's key and name widths stay its own. SQLite and + Postgres now refuse, before the snapshot's transaction, two keys that differ only by trailing + spaces, as SQL Server already did, and every backend refuses a key holding U+0000 (NUL), which + Postgres text cannot store, or a surrogate code point, which no backend stores. Each refusal is + a `ReferenceSnapshotRefused` (the collision is its subclass `ReferenceKeyCollision`), naming the set and the keys by 0-based ordinal, never a key, and logged whole; the last-good snapshot stays active and the sync fails every interval until the source changes. A dry run and - `check` skip such a file-backed set with the same warning. A `Reference(...)` name that ends in - a space or holds U+0000 is refused at load on every backend, and so is a rename to such a - name, since SQL Server compares `npi` and `npi ` as one name. A SQL Server open now also - reports a non-binary collation on the `reference` and `reference_version` key columns, at - WARNING, and repairs nothing. The note naming a folding `state` collation now rides only a - failed authentication tag, the one error a merged row can cause. `SetState`'s refusal of a - surrogate code point now says so rather than "lone surrogate", since half of a pair is refused - too, and `StateKeyError` is exported from `messagefoundry`. (`BACKLOG #6613`) + `check` skip such a file-backed set with a warning naming the same set, rule and ordinals. A + `Reference(...)` name that ends in a space or holds U+0000 or a surrogate is refused at load on + every backend, and so is a rename to such a name, since SQL Server compares `npi` and `npi ` as + one name. A SQL Server open now also reports a non-binary collation on the `reference` and + `reference_version` key columns, at WARNING, and repairs nothing. The note naming a folding + `state` collation now rides only a failed authentication tag, the one error a merged row can + cause. `SetState`'s refusal of a surrogate code point now says so rather than "lone + surrogate", since half of a pair is refused too, and `StateKeyError` is exported from + `messagefoundry`. (`BACKLOG #6613`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index ffa9f496c1..3bc4d06b06 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -821,13 +821,14 @@ crash-re-run — the same accepted caveat as a code-set hot-reload). stays active. The log line names the set and the keys by 0-based ordinal, their position among the keys the source yielded, never a key; an ordinal is not a file line number. A lone key with a trailing space is not refused. A dry run and `messagefoundry check` skip such a file-backed - set with the same warning, so a Handler is not previewed against a set the engine never serves. - A `Reference(...)` name that ends in a space or holds NUL is refused at load, on every backend, - and so is a rename to such a name. SQL Server compares `npi` and `npi ` as one name, so a set - renamed from one to the other across a reload would share the old set's stored rows there; one - graph declaring both is refused as twins either way. SQL Server also bounds a key at 450 UTF-16 - code units and a set name at 256, and reports a non-binary collation on the `reference` and - `reference_version` key columns at open, at WARNING, repairing nothing. + set, with a warning naming the same set, rule and ordinals, since the next sync refuses it; an + engine that synced the set before keeps serving its last-good snapshot meanwhile. A + `Reference(...)` name that ends in a space or holds NUL or a surrogate code point is refused at + load, on every backend, and so is a rename to such a name. SQL Server compares `npi` and `npi ` + as one name, so a set renamed from one to the other across a reload would share the old set's + stored rows there. SQL Server also bounds a key at 450 UTF-16 code units and a set name at 256, + and reports a non-binary collation on the `reference` and `reference_version` key columns at + open, at WARNING, repairing nothing. - **Sync.** The engine's `ReferenceSyncRunner` materializes each set once at startup (before listeners serve, so `reference(...)` resolves on the first message) and every `refresh_seconds`. A source failure is **isolated**: it's logged + alerted and the **last-good snapshot is kept** (the write diff --git a/docs/adr/0006-external-data-lookups.md b/docs/adr/0006-external-data-lookups.md index ec3f6a4b67..97c79eec74 100644 --- a/docs/adr/0006-external-data-lookups.md +++ b/docs/adr/0006-external-data-lookups.md @@ -297,9 +297,12 @@ first-ever reference-row key-rotation tests on all three backends. `ReferenceKeyCollision`, naming the two keys by ordinal only. The sync still fails and alerts every interval, and the last-good snapshot stays active, as it did when the INSERT failed. **AMENDED 2026-12-01 (BACKLOG #6613):** the refusal moved to - `store/reference_keys.py`, which SQLite and Postgres call too, so a set behaves the same on - every backend; it also refuses a key holding U+0000, which Postgres text cannot store, as a - `ReferenceSnapshotRefused`, the collision's base class. + `store/reference_keys.py`, which SQLite and Postgres call too, so a set breaking that rule + fails the same way on every backend; the column widths above stay SQL Server's own. It also + refuses a key holding U+0000, which Postgres text cannot store, or a surrogate code point, which + no backend stores, as a `ReferenceSnapshotRefused`, the collision's base class. A set name that + ends in a space or holds either is refused at load. A SQL Server open warns, repairing nothing, + when the `reference` or `reference_version` key columns are not binary. - **Encryption at rest.** Values are `cipher.encrypt(json.dumps(v))` (`mfenc`), covered by **both** `reencrypt_to_active` (key rotation) **and** `_encrypt_existing_rows` (the no-key→key migration pass). The migration pass is required because "born encrypted" is false: under a no-key deployment From 156a1f5e7354cffea59f9d7f3f4ab38d77f5cb9d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:02:30 -0600 Subject: [PATCH 36/49] vault: both hops take the unset-token refusal from one builder (BACKLOG #4800) keyprovider_vault and secretprovider_vault each held twin POSIX and Windows copies of the unset-token refusal. Both now call engine_secrets.vault_token_unset, which names the variable and what it is the token of. The text each module gave is unchanged, pinned whole for both platforms by a new test. PARTIAL for #4800. Not built: item 1, the Windows refusal of a Vault token read from the environment. No owner deferral binds: the owner's 2026-10-01 ruling 4 says a secret in a Windows service's NSSM environment is refused always. Built locally, it fails 257 tests on Windows that supply the token through the environment, so it needs the test hop helper and about 18 test files moved to a secrets-directory token on Windows first. The other row items are not started. BACKLOG #4800 Proposed PR title: Vault hops share one unset-token refusal builder (BACKLOG #4800, partial) Proposed vault banner: PARTIAL. The twin _token_unset copies are one builder in engine_secrets, text unchanged. Item 1 is not built: the 2026-10-01 owner ruling requires it, and it waits on moving the Windows test legs' Vault token to a secrets-directory file. Every other item is open. Verified-by: tests --- messagefoundry/config/secretprovider_vault.py | 27 +++++--------- messagefoundry/engine_secrets.py | 25 +++++++++++++ messagefoundry/store/keyprovider_vault.py | 28 +++++---------- tests/test_engine_secrets.py | 35 +++++++++++++++++++ 4 files changed, 76 insertions(+), 39 deletions(-) diff --git a/messagefoundry/config/secretprovider_vault.py b/messagefoundry/config/secretprovider_vault.py index dbe16505cb..6e9392c77d 100644 --- a/messagefoundry/config/secretprovider_vault.py +++ b/messagefoundry/config/secretprovider_vault.py @@ -30,7 +30,6 @@ import logging import os -import sys from collections.abc import Iterable from typing import TYPE_CHECKING, Any @@ -41,7 +40,11 @@ vault_client_verify_kwargs, vault_hop_refusal_text, ) -from messagefoundry.engine_secrets import SecretsDirectoryError, secret_setting +from messagefoundry.engine_secrets import ( + SecretsDirectoryError, + secret_setting, + vault_token_unset, +) if TYPE_CHECKING: from messagefoundry.config.settings import SecretsSettings @@ -83,26 +86,12 @@ f"sends its token only to the address named there, never to VAULT_ADDR. Set it in the " f"service's environment, and run check-privileges with that environment" ) -_TOKEN_UNSET = ( - f"{_ENV_TOKEN} is not set or is empty, in the secrets directory or the environment, so the " - f"connector-secret token is not known. The engine reads only the token named there, never " - f"VAULT_TOKEN or ~/.vault-token. Supply it to the service in one of those two places, and " - f"run check-privileges with the service's environment" -) -#: The Windows twin, as in ``store/keyprovider_vault.py``: on Windows the token goes in the -#: secrets directory only, never in the service's environment (owner ruling 2026-10-01). -_TOKEN_UNSET_WINDOWS = ( - f"{_ENV_TOKEN} is not set or is empty, so the connector-secret token is not known. On " - f"Windows, supply it only as the file named {_ENV_TOKEN} in the secrets directory " - f"MEFOR_SECRETS_DIRECTORY names, never in the service's environment. The engine never reads " - f"VAULT_TOKEN or ~/.vault-token in its place. Run check-privileges with " - f"MEFOR_SECRETS_DIRECTORY set as the service has it" -) def _token_unset(platform: str | None = None) -> str: - """The unset-token refusal for ``platform``, this process's when ``None``. Fixed text.""" - return _TOKEN_UNSET_WINDOWS if (platform or sys.platform) == "win32" else _TOKEN_UNSET + """The unset-token refusal for ``platform``, this process's when ``None``. Fixed text, from + the builder both Vault hops share (BACKLOG #4800).""" + return vault_token_unset(_ENV_TOKEN, "connector-secret token", platform) #: Default field read from a KV secret when a reference omits ``#``. diff --git a/messagefoundry/engine_secrets.py b/messagefoundry/engine_secrets.py index 2e0e2d3d16..91bb0d2a75 100644 --- a/messagefoundry/engine_secrets.py +++ b/messagefoundry/engine_secrets.py @@ -68,6 +68,7 @@ "open_secrets_directory", "secret_setting", "secret_settings", + "vault_token_unset", ] #: The variable that names the secrets directory. A path, not a secret. @@ -406,6 +407,30 @@ def secret_settings( return found +def vault_token_unset(variable: str, subject: str, platform: str | None = None) -> str: + """The refusal for a Vault token ``variable`` that is unset or empty, naming what it is the + token of as ``subject``, for ``platform``, this process's when ``None``. Fixed text, never a + value. The one builder for both Vault hops' refusals (BACKLOG #2851, #4800). + + On Windows the token goes in the secrets directory only, never in the service's environment + (owner ruling 2026-10-01; ``serviceenv`` refuses it in the service's own environment lists), + so that text never points a Windows operator at the environment.""" + if (platform or sys.platform) == "win32": + return ( + f"{variable} is not set or is empty, so the {subject} is not known. On Windows, supply " + f"it only as the file named {variable} in the secrets directory " + f"{SECRETS_DIRECTORY_VARIABLE} names, never in the service's environment. The engine " + f"never reads VAULT_TOKEN or ~/.vault-token in its place. Run check-privileges with " + f"{SECRETS_DIRECTORY_VARIABLE} set as the service has it" + ) + return ( + f"{variable} is not set or is empty, in the secrets directory or the environment, so the " + f"{subject} is not known. The engine reads only the token named there, never VAULT_TOKEN " + f"or ~/.vault-token. Supply it to the service in one of those two places, and run " + f"check-privileges with the service's environment" + ) + + def secret_setting(name: str, *, environ: Mapping[str, str] | None = None) -> str | None: """The value of one secret-class setting, as :func:`secret_settings` reads it.""" return secret_settings((name,), environ=environ)[name] diff --git a/messagefoundry/store/keyprovider_vault.py b/messagefoundry/store/keyprovider_vault.py index cd40a6e150..ddf9018c1f 100644 --- a/messagefoundry/store/keyprovider_vault.py +++ b/messagefoundry/store/keyprovider_vault.py @@ -31,7 +31,6 @@ import logging import os import re -import sys from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING, Any @@ -42,7 +41,11 @@ vault_client_verify_kwargs, vault_hop_refusal_text, ) -from messagefoundry.engine_secrets import SecretsDirectoryError, secret_setting +from messagefoundry.engine_secrets import ( + SecretsDirectoryError, + secret_setting, + vault_token_unset, +) from messagefoundry.redaction import codec_safe_str, safe_exc from messagefoundry.store.keyprovider import KeyProviderError, _split_retired @@ -92,27 +95,12 @@ f"token only to the address named there, never to VAULT_ADDR. Set it in the service's " f"environment, and run check-privileges with that environment" ) -_TOKEN_UNSET = ( - f"{_ENV_TOKEN} is not set or is empty, in the secrets directory or the environment, so the " - f"store token is not known. The engine reads only the token named there, never VAULT_TOKEN " - f"or ~/.vault-token. Supply it to the service in one of those two places, and run " - f"check-privileges with the service's environment" -) -#: The Windows twin. On Windows the token goes in the secrets directory only, never in the -#: service's environment (owner ruling 2026-10-01; ``serviceenv`` refuses it in the service's own -#: environment lists), so the refusal never points a Windows operator there. -_TOKEN_UNSET_WINDOWS = ( - f"{_ENV_TOKEN} is not set or is empty, so the store token is not known. On Windows, supply " - f"it only as the file named {_ENV_TOKEN} in the secrets directory MEFOR_SECRETS_DIRECTORY " - f"names, never in the service's environment. The engine never reads VAULT_TOKEN or " - f"~/.vault-token in its place. Run check-privileges with MEFOR_SECRETS_DIRECTORY set as the " - f"service has it" -) def _token_unset(platform: str | None = None) -> str: - """The unset-token refusal for ``platform``, this process's when ``None``. Fixed text.""" - return _TOKEN_UNSET_WINDOWS if (platform or sys.platform) == "win32" else _TOKEN_UNSET + """The unset-token refusal for ``platform``, this process's when ``None``. Fixed text, from + the builder both Vault hops share (BACKLOG #4800).""" + return vault_token_unset(_ENV_TOKEN, "store token", platform) def _import_hvac() -> Any: diff --git a/tests/test_engine_secrets.py b/tests/test_engine_secrets.py index 00d1f6c93d..a0d18773b8 100644 --- a/tests/test_engine_secrets.py +++ b/tests/test_engine_secrets.py @@ -417,6 +417,41 @@ def test_the_windows_token_refusal_never_points_at_the_environment( assert str(caught.value) == windows +@pytest.mark.parametrize( + ("hop", "variable", "subject"), + [ + ("store", "MEFOR_STORE_VAULT_TOKEN", "store token"), + ("secrets", "MEFOR_SECRETS_VAULT_TOKEN", "connector-secret token"), + ], +) +def test_both_vault_hops_take_the_unset_token_text_from_one_builder( + hop: str, variable: str, subject: str +) -> None: + """BACKLOG #4800: the two Vault modules held twin copies of the unset-token refusal, one per + platform each. Both now come from ``engine_secrets.vault_token_unset``, and the text each + gave before is unchanged, pinned here whole for both platforms.""" + from messagefoundry.config import secretprovider_vault + from messagefoundry.engine_secrets import vault_token_unset + from messagefoundry.store import keyprovider_vault + + module: Any = keyprovider_vault if hop == "store" else secretprovider_vault + for platform in ("win32", "linux"): + assert module._token_unset(platform) == vault_token_unset(variable, subject, platform) + assert module._token_unset("linux") == ( + f"{variable} is not set or is empty, in the secrets directory or the environment, so the " + f"{subject} is not known. The engine reads only the token named there, never VAULT_TOKEN " + f"or ~/.vault-token. Supply it to the service in one of those two places, and run " + f"check-privileges with the service's environment" + ) + assert module._token_unset("win32") == ( + f"{variable} is not set or is empty, so the {subject} is not known. On Windows, supply " + f"it only as the file named {variable} in the secrets directory MEFOR_SECRETS_DIRECTORY " + f"names, never in the service's environment. The engine never reads VAULT_TOKEN or " + f"~/.vault-token in its place. Run check-privileges with MEFOR_SECRETS_DIRECTORY set as the " + f"service has it" + ) + + def test_an_unusable_directory_and_an_unset_address_are_refused_together( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: From 2e79b9292919e70ccf73f79c11b69797dbed34ae Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:09:07 -0600 Subject: [PATCH 37/49] vault: comments name where each unset refusal's text now lives (BACKLOG #4800) Review round 1 fixes, comments and a docstring only. The Vault modules' comments say the address refusal is theirs and the token's comes from engine_secrets.vault_token_unset, and that builder's docstring says it builds the token refusal only, and that the Windows environment refusal (#4800 item 1) is not built. BACKLOG #4800 Proposed PR title: Vault hops share one unset-token refusal builder (BACKLOG #4800, partial) Proposed vault banner: PARTIAL. The twin _token_unset copies are one builder in engine_secrets, text unchanged. Item 1 is not built: the 2026-10-01 owner ruling requires it, and it waits on moving the Windows test legs' Vault token to a secrets-directory file. Every other item is open. Verified-by: tests --- messagefoundry/config/secretprovider_vault.py | 7 ++++--- messagefoundry/engine_secrets.py | 10 ++++++---- messagefoundry/store/keyprovider_vault.py | 7 ++++--- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/messagefoundry/config/secretprovider_vault.py b/messagefoundry/config/secretprovider_vault.py index 6e9392c77d..b742e603a8 100644 --- a/messagefoundry/config/secretprovider_vault.py +++ b/messagefoundry/config/secretprovider_vault.py @@ -65,7 +65,8 @@ # # BACKLOG #2851: both are REQUIRED and always handed to hvac. Given None, hvac reads VAULT_ADDR, # VAULT_TOKEN and then ~/.vault-token, which in an operator's shell are the operator's own Vault and -# token. So an unset or empty variable refuses, with the fixed text below, rather than fall back. +# token. So an unset or empty variable refuses, with fixed text (the address's below, the +# token's from engine_secrets.vault_token_unset), rather than fall back. # The twin of store/keyprovider_vault.py's. _ENV_ADDR = "MEFOR_SECRETS_VAULT_ADDR" _ENV_TOKEN = "MEFOR_SECRETS_VAULT_TOKEN" # nosec B105 — the env-var NAME, not a token value @@ -79,8 +80,8 @@ #: not reach this hop yet.) _ENV_CA_FILE = "MEFOR_SECRETS_VAULT_CA_FILE" -#: The refusals for an unset address or token: fixed text naming the variable, never a value. One -#: text each, for the provider and ``check-privileges`` alike (BACKLOG #2851). +#: The refusal for an unset address: fixed text naming the variable, never a value, for the +#: provider and ``check-privileges`` alike (BACKLOG #2851). The token's is :func:`_token_unset`. _ADDR_UNSET = ( f"{_ENV_ADDR} is not set or is empty, so the connector-secret Vault is not known. The engine " f"sends its token only to the address named there, never to VAULT_ADDR. Set it in the " diff --git a/messagefoundry/engine_secrets.py b/messagefoundry/engine_secrets.py index 91bb0d2a75..17a2024d2b 100644 --- a/messagefoundry/engine_secrets.py +++ b/messagefoundry/engine_secrets.py @@ -410,11 +410,13 @@ def secret_settings( def vault_token_unset(variable: str, subject: str, platform: str | None = None) -> str: """The refusal for a Vault token ``variable`` that is unset or empty, naming what it is the token of as ``subject``, for ``platform``, this process's when ``None``. Fixed text, never a - value. The one builder for both Vault hops' refusals (BACKLOG #2851, #4800). + value. Both Vault hops build their unset-token refusal here (BACKLOG #2851, #4800); each + keeps its own unset-address text. - On Windows the token goes in the secrets directory only, never in the service's environment - (owner ruling 2026-10-01; ``serviceenv`` refuses it in the service's own environment lists), - so that text never points a Windows operator at the environment.""" + On Windows the token is to go in the secrets directory only, never in the service's environment + (owner ruling 2026-10-01), so that text never points a Windows operator at the environment. + ``serviceenv`` refuses it in the service's own environment lists; :func:`secret_settings` still + reads one the process inherits any other way (BACKLOG #4800 item 1, not built).""" if (platform or sys.platform) == "win32": return ( f"{variable} is not set or is empty, so the {subject} is not known. On Windows, supply " diff --git a/messagefoundry/store/keyprovider_vault.py b/messagefoundry/store/keyprovider_vault.py index ddf9018c1f..0b1e2543a4 100644 --- a/messagefoundry/store/keyprovider_vault.py +++ b/messagefoundry/store/keyprovider_vault.py @@ -71,7 +71,8 @@ # None, hvac reads VAULT_ADDR, VAULT_TOKEN and then ~/.vault-token. In an operator's shell those # are the operator's own Vault and token, usually with wider rights than the engine needs, and a # stray VAULT_ADDR on a service account would receive the engine's token. So an unset or empty -# variable refuses, with the fixed text below, rather than fall back. +# variable refuses, with fixed text (the address's below, the token's from +# engine_secrets.vault_token_unset), rather than fall back. _ENV_ADDR = "MEFOR_STORE_VAULT_ADDR" _ENV_TOKEN = "MEFOR_STORE_VAULT_TOKEN" # nosec B105 — this is the env-var NAME, not a token value #: The Transit key name (the KEK) the wrapped DEK was sealed under. @@ -88,8 +89,8 @@ #: ``CURL_CA_BUNDLE``, and only when none is set ``requests``' PUBLIC certifi bundle. _ENV_CA_FILE = "MEFOR_STORE_VAULT_CA_FILE" -#: The refusals for an unset address or token: fixed text naming the variable, never a value. One -#: text each, for the providers and ``check-privileges`` alike (BACKLOG #2851). +#: The refusal for an unset address: fixed text naming the variable, never a value, for the +#: providers and ``check-privileges`` alike (BACKLOG #2851). The token's is :func:`_token_unset`. _ADDR_UNSET = ( f"{_ENV_ADDR} is not set or is empty, so the store Vault is not known. The engine sends its " f"token only to the address named there, never to VAULT_ADDR. Set it in the service's " From 5fe9a6503efae0a98ea5a900109774a81b2b1795 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:49:45 -0600 Subject: [PATCH 38/49] engine_secrets: the token refusal's docstring says when serviceenv refuses (BACKLOG #4800) Review round 2 finding 1, a docstring only. vault_token_unset's docstring said flatly that serviceenv refuses a Vault token in the service's own environment lists. It does that only when it finds its NSSM service and can read those lists. The docstring now says so, points at serviceenv's module docstring for what else it refuses and what it does not cover, at least a host other than NSSM and an ancestor walk that fails, and says secret_settings still reads an inherited token wherever serviceenv refuses nothing and the secrets directory has no file for it. The stale "not built" status note is dropped; the item reference stays. BACKLOG #4800 Proposed PR title: Vault hops share one unset-token refusal builder (BACKLOG #4800, partial) Proposed vault banner: PARTIAL. The twin _token_unset copies are one builder in engine_secrets, text unchanged, and its docstring states when serviceenv refuses an environment token. Item 1, the Windows refusal of an environment-sourced Vault token, is not built and stays owed. Every other item is open. Verified-by: tests --- messagefoundry/engine_secrets.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/messagefoundry/engine_secrets.py b/messagefoundry/engine_secrets.py index 17a2024d2b..d5030c2e7a 100644 --- a/messagefoundry/engine_secrets.py +++ b/messagefoundry/engine_secrets.py @@ -415,8 +415,12 @@ def vault_token_unset(variable: str, subject: str, platform: str | None = None) On Windows the token is to go in the secrets directory only, never in the service's environment (owner ruling 2026-10-01), so that text never points a Windows operator at the environment. - ``serviceenv`` refuses it in the service's own environment lists; :func:`secret_settings` still - reads one the process inherits any other way (BACKLOG #4800 item 1, not built).""" + ``serviceenv`` refuses it in the service's own environment lists when it finds its NSSM service + and can read those lists. Its module docstring says what else it refuses and what it does not + cover, at least a service host other than NSSM and an ancestor walk that fails. Wherever + ``serviceenv`` refuses nothing, :func:`secret_settings` still reads a token the process + inherits from its environment when the secrets directory has no file for it (BACKLOG #4800 + item 1).""" if (platform or sys.platform) == "win32": return ( f"{variable} is not set or is empty, so the {subject} is not known. On Windows, supply " From 4bc7b07c605fd23c4a5d776fe2d12f0c38b324d1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:57:28 -0600 Subject: [PATCH 39/49] engine_secrets: name the wrapper gap and the unset directory (BACKLOG #4800) Review round 3, repair round 1, docstrings only. The previous commit's message said serviceenv refuses "only when" it finds its service and reads its lists; that was false, since it also refuses a token in this process's environment when a known service's lists cannot be read. The docstring itself now: - names the cmd.exe or PowerShell wrapper between NSSM and Python as a case serviceenv refuses nothing, and points at serviceenv by :mod: for the rest, instead of a partial copy of its list; - says the environment read also happens with MEFOR_SECRETS_DIRECTORY unset; - restores that item 1, the Windows refusal, is not built. The module docstring's copy of the serviceenv fact gets the same condition. BACKLOG #4800 Proposed PR title: Vault hops share one unset-token refusal builder (BACKLOG #4800, partial) Proposed vault banner: PARTIAL. The twin _token_unset copies are one builder in engine_secrets, text unchanged, and its docstring states when serviceenv refuses an environment token. Item 1, the Windows refusal of an environment-sourced Vault token, is not built and stays owed. Every other item is open. Verified-by: tests --- messagefoundry/engine_secrets.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/messagefoundry/engine_secrets.py b/messagefoundry/engine_secrets.py index d5030c2e7a..ee20c17731 100644 --- a/messagefoundry/engine_secrets.py +++ b/messagefoundry/engine_secrets.py @@ -31,7 +31,7 @@ **What this slice does not do**, at least: refuse a secret found in the environment (slice B later made the NSSM reading in :mod:`messagefoundry.serviceenv` refuse one in the service's own -lists, where it could read them); +lists, where it can find that service and read them; that module says what it misses); create the directory (the Windows service installer does, slice C, and names it to the service); wrap a file with DPAPI (a plain file restricted by its access list is the control, and whether a Windows file is also wrapped waits on a spike); and @@ -415,12 +415,13 @@ def vault_token_unset(variable: str, subject: str, platform: str | None = None) On Windows the token is to go in the secrets directory only, never in the service's environment (owner ruling 2026-10-01), so that text never points a Windows operator at the environment. - ``serviceenv`` refuses it in the service's own environment lists when it finds its NSSM service - and can read those lists. Its module docstring says what else it refuses and what it does not - cover, at least a service host other than NSSM and an ancestor walk that fails. Wherever - ``serviceenv`` refuses nothing, :func:`secret_settings` still reads a token the process - inherits from its environment when the secrets directory has no file for it (BACKLOG #4800 - item 1).""" + :mod:`messagefoundry.serviceenv` refuses it in the service's own environment lists when it can + tell which NSSM service started the engine and can read those lists, and not, for one, under a + ``cmd.exe`` or PowerShell wrapper between NSSM and Python; that module says what else it + refuses and what it misses. Wherever it refuses nothing, :func:`secret_settings` still reads a + token from the environment when no secrets directory file supplies it, an unset + :data:`SECRETS_DIRECTORY_VARIABLE` included. The Windows refusal of such a token is BACKLOG + #4800 item 1, not built.""" if (platform or sys.platform) == "win32": return ( f"{variable} is not set or is empty, so the {subject} is not known. On Windows, supply " From 56c9fb8b1fd0291aadb98c053dd2c0436931212b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:05:19 -0600 Subject: [PATCH 40/49] engine_secrets: point at serviceenv instead of copying its coverage (BACKLOG #4800) Review round 4, repair round 2, docstrings only. Two rounds of copying serviceenv's coverage into engine_secrets kept going inaccurate, so both copies are replaced by a pointer to serviceenv, which states it once: - vault_token_unset's docstring keeps the owner-ruling sentence, points at serviceenv for where an environment token refuses the start, says secret_settings reads the environment's token when the secrets directory is unset or holds no file for it (not when the directory is set but unusable, which raises), and cites vault BACKLOG #4800 item 1 as one limb, with no status the ledger already holds; - the module docstring's copy becomes the same pointer. The previous commit's banner called item 1 a single refusal; it is a list, and the banner below says one limb. BACKLOG #4800 Proposed PR title: Vault hops share one unset-token refusal builder (BACKLOG #4800, partial) Proposed vault banner: PARTIAL. The twin _token_unset copies in item 1 are one builder in engine_secrets, text unchanged, and its docstring points at serviceenv for when an environment token refuses the start. The item 1 limb for a Windows refusal of an environment-sourced Vault token is not built and stays owed, as are item 1's other limbs and items 2 to 4. Verified-by: tests --- messagefoundry/engine_secrets.py | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/messagefoundry/engine_secrets.py b/messagefoundry/engine_secrets.py index ee20c17731..04010b76b0 100644 --- a/messagefoundry/engine_secrets.py +++ b/messagefoundry/engine_secrets.py @@ -30,8 +30,8 @@ neither file. **What this slice does not do**, at least: refuse a secret found in the environment (slice B -later made the NSSM reading in :mod:`messagefoundry.serviceenv` refuse one in the service's own -lists, where it can find that service and read them; that module says what it misses); +later made the NSSM reading in :mod:`messagefoundry.serviceenv` refuse some, as that module +says); create the directory (the Windows service installer does, slice C, and names it to the service); wrap a file with DPAPI (a plain file restricted by its access list is the control, and whether a Windows file is also wrapped waits on a spike); and @@ -415,13 +415,10 @@ def vault_token_unset(variable: str, subject: str, platform: str | None = None) On Windows the token is to go in the secrets directory only, never in the service's environment (owner ruling 2026-10-01), so that text never points a Windows operator at the environment. - :mod:`messagefoundry.serviceenv` refuses it in the service's own environment lists when it can - tell which NSSM service started the engine and can read those lists, and not, for one, under a - ``cmd.exe`` or PowerShell wrapper between NSSM and Python; that module says what else it - refuses and what it misses. Wherever it refuses nothing, :func:`secret_settings` still reads a - token from the environment when no secrets directory file supplies it, an unset - :data:`SECRETS_DIRECTORY_VARIABLE` included. The Windows refusal of such a token is BACKLOG - #4800 item 1, not built.""" + :mod:`messagefoundry.serviceenv` says where a token in the environment refuses the start and + what it misses. :func:`secret_settings` still reads the environment's token when the secrets + directory is unset or holds no file for it; refusing that on Windows is one limb of vault + BACKLOG #4800 item 1.""" if (platform or sys.platform) == "win32": return ( f"{variable} is not set or is empty, so the {subject} is not known. On Windows, supply " From a7a4338bfa441e5e42a5e626bb387d68ea7ea8e0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:37:00 -0600 Subject: [PATCH 41/49] serviceenv: the docstrings say what a failed walk and a failed machine-wide read do (BACKLOG #4800) Docstrings only, no code change. A walk that fails above a non-Python wrapper such as cmd.exe returns NOT_A_SERVICE in _started_by_something_else, not service_environment_unobservable; the module docstring now says so. The machine-wide refusal fails open: where the machine-wide environment key cannot be read, _located_machine_wide logs a WARNING and locates nothing, so a machine-wide secret is not refused even under enforce. The module docstring and the function's own docstring now say so, with at-least wording for the cases it misses. Proposed PR title: Restack #6613 and #4800 onto the final #6573 branch; serviceenv docstrings name two fail-open readings Verified-by: tests --- messagefoundry/serviceenv.py | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/messagefoundry/serviceenv.py b/messagefoundry/serviceenv.py index 6caba01030..d4f6bbc062 100644 --- a/messagefoundry/serviceenv.py +++ b/messagefoundry/serviceenv.py @@ -44,8 +44,12 @@ carries it and the caller applies the setting. The engine refuses only a name it finds set in that environment's registry key: a secret a ``python.exe`` wrapper between NSSM and the engine exports into the engine's own environment is named and not refused, unless the - machine-wide key also sets that name. Under a wrapper the walk does not pass through, such as - ``cmd.exe``, with ``nssm.exe`` above it, the engine cannot tell whether it runs as that + machine-wide key also sets that name. **This refusal fails open**: where that key cannot be + read, the engine logs a WARNING, finds no name there, and refuses no machine-wide secret, even + under ``enforce`` (:func:`_located_machine_wide`). It misses at least that case, a reading that + is not ``observed``, which never asks the key, and a name set in the service's own lists, which + those lists' refusal covers instead. Under a wrapper the walk does not pass through, such as + ``cmd.exe``, with ``nssm.exe`` found above it, the engine cannot tell whether it runs as that service: it names ``service_environment_unobservable`` and refuses nothing here. A store key from outside the lists stays named and not refused, as the bullet above says. @@ -65,8 +69,12 @@ ``MEFOR_VALUE_*`` name in the service's own lists is covered. **Not a refusal when the read fails, with one exception.** An engine that cannot walk its -ancestors, or cannot read its service's lists, reports ``service_environment_unobservable`` and -starts, and a secret in those lists goes unrefused. The exception: a known service whose lists +ancestors up to the first process that is neither a Python interpreter nor +``messagefoundry.exe``, or cannot read its service's lists, reports +``service_environment_unobservable`` and starts, and a secret in those lists goes unrefused. A +walk that fails above such a process, such as a ``cmd.exe`` wrapper, reports ``not_a_service`` +instead, the reading a shell start gives, so an ``nssm.exe`` further up goes unnoticed and no +``service_environment_unobservable`` is named. The exception: a known service whose lists could not be read refuses a store key or another engine secret in this process's environment, whatever the enforcement setting, since it most likely came from them. """ @@ -1325,7 +1333,11 @@ def _located_machine_wide( ) -> tuple[str, ...]: """The ``names`` ``machine_wide`` says the machine-wide environment sets, in their own order. None located where there is no reader, no name to ask about, or the read fails: the refusal - acts only on a name it found there, and the loosening still names the rest.""" + acts only on a name it found there, and the loosening still names the rest. + + So the refusal fails open on a failed read: an ``OSError`` from ``machine_wide``, such as the + key not opening or a name in it not being readable, logs a WARNING and locates nothing, and a + machine-wide secret is then not refused, even under ``[security].enforcement = "enforce"``.""" if machine_wide is None or not names: return () try: @@ -1464,8 +1476,9 @@ def _started_by_something_else( A shell is the usual case, and then the engine is not a service. But an operator may also register NSSM to start a wrapper, such as ``cmd.exe``, that starts the engine. So the walk goes on: an ``nssm.exe`` further up means the engine cannot tell whether it runs as that service, - and says so. A walk that fails above the wrapper settles nothing either way, and the reading - stays the shell's.""" + and says so. A walk that fails above the wrapper, with an ``OSError``, reads as + ``NOT_A_SERVICE``, the shell's reading, not ``UNOBSERVABLE``: an ``nssm.exe`` it did not reach + goes unnoticed.""" try: nssm = next((pid for pid, above in rest if above.lower() == _NSSM_IMAGE), None) except OSError: From a95af89aeccbf5b0f296d9629a86d5be34baaeb3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:42:28 -0600 Subject: [PATCH 42/49] Rename the NUL-key test's store file off a Windows reserved device name (BACKLOG #6613) test_a_nul_key_refusal_is_logged_whole opened tmp_path / "nul.db". NUL with any extension is a reserved device name on Windows, so MessageStore.open failed with "unable to open database file" on the windows-2022 test shard. The file is now nul_key.db. No other test file this stack added uses a reserved device name. Verified-by: tests --- tests/test_reference_sets.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_reference_sets.py b/tests/test_reference_sets.py index f8c5c5448b..a933b15fa9 100644 --- a/tests/test_reference_sets.py +++ b/tests/test_reference_sets.py @@ -1123,7 +1123,8 @@ async def test_a_nul_key_refusal_is_logged_whole( from messagefoundry.store.base import ReferenceSnapshotRefused csv = _csv(tmp_path / "npi.csv", "key,value\nMED1,9991\n") - store = await MessageStore.open(tmp_path / "nul.db") + # Not "nul.db": NUL with any extension is a reserved device name on Windows. + store = await MessageStore.open(tmp_path / "nul_key.db") text = "reference set 'provider_npi': key #4 contains U+0000 (NUL)" async def refused_write(*, name: str, version: str, rows: Any) -> None: From 746bb5cc9f8674fda43dc59b1e9cfd297ae3626d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:48:44 -0600 Subject: [PATCH 43/49] Name the Windows release that opens NUL. as the device (BACKLOG #6613) The comment added with the rename said NUL with any extension is reserved on Windows. That holds on Windows Server 2022, the windows-2022 runner, and not on Windows 11, where NUL. is a regular file. The comment now says so, matching tests/test_audit_integrity.py. The previous commit's message carries the same overstatement; this one corrects it. Proposed PR title: unchanged (this repairs the existing #6613 branch). Verified-by: tests --- tests/test_reference_sets.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_reference_sets.py b/tests/test_reference_sets.py index a933b15fa9..23b24195d0 100644 --- a/tests/test_reference_sets.py +++ b/tests/test_reference_sets.py @@ -1123,7 +1123,8 @@ async def test_a_nul_key_refusal_is_logged_whole( from messagefoundry.store.base import ReferenceSnapshotRefused csv = _csv(tmp_path / "npi.csv", "key,value\nMED1,9991\n") - # Not "nul.db": NUL with any extension is a reserved device name on Windows. + # Not "nul.db": Windows Server 2022 (the windows-2022 CI runner) opens NUL. as the + # device, so SQLite cannot open it there, though Windows 11 makes it a regular file. store = await MessageStore.open(tmp_path / "nul_key.db") text = "reference set 'provider_npi': key #4 contains U+0000 (NUL)" From 696839a7ddf7982de3d0d638a3ccb731ee6ab8c1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 13:22:00 -0600 Subject: [PATCH 44/49] Config backup: an unreachable share at the first screen fails the backup; the held-dir refusal names its remedy The screen before a config file's confined open read any ENOENT as a file gone, so a share or network path that could not be reached (WinError 53, 67) left the file out unrecorded while docs/CONFIGURATION.md said it fails the backup. It now fails the backup naming the file; a plain absent file is still left out. The refusal for a config dir that cannot be held as itself now gives the remedy before the dir (close what holds it open, or include_config = false), and the include_config row states it. The pinned survivor length for that arm moves from 68 to 15. Repair of the Lander's hold on PR 3535 (BACKLOG #6573). Verified-by: tests --- docs/CONFIGURATION.md | 2 +- messagefoundry/pipeline/dr_backup.py | 29 +++++++++----- tests/test_backup_runner.py | 59 ++++++++++++++++++++++++++-- 3 files changed, 76 insertions(+), 14 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 20bb5f9151..634db74f5f 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and a remedy: if the volume has no drive letter, assign it one, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails, that final-path failure and a hold of the config dir refused with one of the three codes below included, and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these refusals, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir, and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and a remedy: if the volume has no drive letter, assign it one, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails, that final-path failure and a hold of the config dir refused with one of the three codes below included, and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these refusals, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir and the remedy: close the program that holds the config dir open, or set `include_config = false`; and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 28ecce1b27..237f570344 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -3802,9 +3802,11 @@ def _open_config_file( ``base`` itself when the config dir could not be held.""" try: st = path.lstat() - except FileNotFoundError: - return "gone" - except OSError: + except OSError as exc: + if is_absent(exc): + return "gone" + if isinstance(exc, FileNotFoundError): + raise _config_file_error(path, base, exc) from exc return "passed-over" if not stat.S_ISREG(st.st_mode) or _stat_names_another_path(st): return "passed-over" @@ -3825,7 +3827,7 @@ def _open_config_file( except OSError as screen_exc: if is_absent(screen_exc): return "gone" - raise _config_dir_error(base, exc) from exc + raise _config_dir_error(base, exc, remedy=_UNHELD_DIR_REMEDY) from exc # The volume does not do what the hold asked: a step of the open, as below, except that a # refusal names the config dir, whose step it was. failed: OSError = exc @@ -3972,16 +3974,23 @@ def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: return _error_like(exc, what, None) -def _config_dir_error(base: Path, exc: OSError, reason: str | None = None) -> OSError: +_UNHELD_DIR_REMEDY = "close what holds it open, or include_config = false" + + +def _config_dir_error( + base: Path, exc: OSError, reason: str | None = None, *, remedy: str | None = None +) -> OSError: """The error that fails the backup when the config dir ``base`` itself could not be held as itself (vault BACKLOG #6573), naming the dir rather than a file under it, and keeping ``exc``'s codes. It gives ``reason``, else ``exc``'s text less the period Windows ends it - with. The dir comes after that (:func:`_refusal`), so the 200-character cut the ``dr_backup`` - audit row's error makes takes a long path before the cause.""" + with, then ``remedy`` where one is given. The dir comes after those (:func:`_refusal`), so + the 200-character cut the ``dr_backup`` audit row's error makes takes a long path before the + cause and the remedy.""" cause = reason if reason is not None else exc.strerror if exc.strerror is not None else str(exc) - return _refusal( - exc, "config dir not held", cause.rstrip().removesuffix("."), scrub_log_argument(str(base)) - ) + cause = cause.rstrip().removesuffix(".") + if remedy is not None: + cause = f"{cause}; {remedy}" + return _refusal(exc, "config dir not held", cause, scrub_log_argument(str(base))) def _rel_name(path: Path, base: Path) -> str: diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index ada7d61344..832cd9c74f 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1684,6 +1684,55 @@ async def test_a_config_file_on_an_unreachable_share_fails_the_backup( monkeypatch.undo() +def _fault_the_first_screen( + monkeypatch: pytest.MonkeyPatch, checked: Path, screen_exc: OSError +) -> list[Path]: + """Fail every ``Path.lstat`` of ``checked`` with ``screen_exc``, the screen the add makes + before its confined open. Returns the list each faulted screen appends ``checked`` to.""" + real_lstat = Path.lstat + key = os.path.normcase(os.fspath(checked)) + faulted: list[Path] = [] + + def lstat(self: Path) -> os.stat_result: + if os.path.normcase(os.fspath(self)) == key: + faulted.append(self) + raise screen_exc + return real_lstat(self) + + monkeypatch.setattr(Path, "lstat", lstat) + return faulted + + +@pytest.mark.parametrize("winerror", [53, 67], ids=["bad-netpath", "bad-net-name"]) +async def test_a_config_file_whose_first_screen_meets_an_unreachable_share_fails_the_backup( + tmp_path, key_b64, monkeypatch, winerror +) -> None: + """A file the walk listed, whose screen before the confined open fails because its share or + network path cannot be reached (ERROR_BAD_NETPATH or ERROR_BAD_NET_NAME, which Python maps to + ENOENT), fails the backup naming the file, rather than being read as a file gone since the + listing and left out unrecorded (vault BACKLOG #6573). The control is a plain ENOENT at that + screen, which is a file gone and is left out while the backup succeeds.""" + cfg, _host = _config_for_a_swap(tmp_path) + checked = cfg / "swapped.toml" + + (tmp_path / "control").mkdir() + faulted = _fault_the_first_screen( + monkeypatch, checked, _os_error(2, "No such file or directory") + ) + result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) + assert faulted, "the control's fault ran" + assert "config/swapped.toml" not in names # the control: a file gone is left out + assert result.config_skipped_files == () + monkeypatch.undo() + + faulted = _fault_the_first_screen( + monkeypatch, checked, _os_error(2, "The network path was not found", winerror) + ) + with pytest.raises(BackupError, match="swapped.toml"): + await _pass_with_bytes(tmp_path, key_b64, cfg) + assert faulted, "the fault ran" + + @pytest.mark.parametrize( ("code", "winerror"), [(5, None), (22, 64)], ids=["eio", "netname-deleted"] ) @@ -2106,7 +2155,7 @@ def open_by_name(path, flags, *args, **kwargs): "file-unreadable": ("step", 5, "use local NTFS or ReFS or include_config = false", 0), "dir-holds-links": ("root", 0x80, "fix its filter or share, or include_config = false", 1), "dir-unreadable": ("root", 5, "use local NTFS or ReFS or include_config = false", 1), - "dir-held-open": ("held", None, "being used by another process", 1), + "dir-held-open": ("held", None, "close what holds it open, or include_config = false", 1), "final-path": ( "final", None, @@ -2124,7 +2173,7 @@ def open_by_name(path, flags, *args, **kwargs): ("file-unreadable", 59), ("dir-holds-links", 57), ("dir-unreadable", 61), - ("dir-held-open", 68), + ("dir-held-open", 15), ("final-path", 41), ], ) @@ -2273,7 +2322,9 @@ async def test_a_root_hold_that_reports_no_such_path_while_the_dir_is_there_fail with pytest.raises(BackupError) as raised: await _pass_with_bytes(tmp_path, key_b64, cfg) assert failed, "the fault ran" - assert "config dir not held: The system cannot find the path" in str(raised.value) + text = str(raised.value) + assert "config dir not held: The system cannot find the path" in text + assert "close what holds it open, or include_config = false" in text @pytest.mark.skipif(sys.platform != "win32", reason="a Windows sharing violation") @@ -2294,6 +2345,8 @@ async def test_a_config_dir_another_handle_holds_open_for_delete_fails_naming_th _close(handle) text = str(raised.value) assert "config dir not held" in text and "WinError 32" in text + # The BackupError's text is already cut at 200 characters, so the remedy survives the cut. + assert "close what holds it open, or include_config = false" in text assert "feed.py" not in text (tmp_path / "control").mkdir() _result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) From de6f6375e39764791e79a1414f17530e325ec18e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 13:35:54 -0600 Subject: [PATCH 45/49] Config backup: the held-dir remedy is a sharing violation's only, given in short so the dir still survives the cut Review round 1 of the repair: the remedy to close what holds the config dir open was given for every failed hold, path-not-found and access denied included, and its length pushed the dir past the audit row's 200-character cut for any real path. It is now given only for ERROR_SHARING_VIOLATION, with a short cause in place of Windows' text, so a dir of up to 68 characters survives as before. The docs row quotes the text the code emits; the first-screen test pins which screen faulted. Repair of the Lander's hold on PR 3535 (BACKLOG #6573). Verified-by: tests --- docs/CONFIGURATION.md | 2 +- messagefoundry/pipeline/dr_backup.py | 31 +++++++++++++++++----------- tests/test_backup_runner.py | 10 ++++----- 3 files changed, 25 insertions(+), 18 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 634db74f5f..b99a3209d2 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and a remedy: if the volume has no drive letter, assign it one, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails, that final-path failure and a hold of the config dir refused with one of the three codes below included, and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these refusals, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, or that cannot be held for another reason while it is still there, which names the config dir and the remedy: close the program that holds the config dir open, or set `include_config = false`; and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and a remedy: if the volume has no drive letter, assign it one, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails, that final-path failure and a hold of the config dir refused with one of the three codes below included, and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these refusals, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, which names the config dir and the remedy (`in use by another process; close what holds it open, or include_config = false`), or that cannot be held for another reason while it is still there, which names the config dir; and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 237f570344..539392220f 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -3827,7 +3827,11 @@ def _open_config_file( except OSError as screen_exc: if is_absent(screen_exc): return "gone" - raise _config_dir_error(base, exc, remedy=_UNHELD_DIR_REMEDY) from exc + # A sharing violation is given in short with its remedy, so the 200-character cut + # the dr_backup audit row's error makes keeps both and still names the dir. + held_open = getattr(exc, "winerror", None) == _WIN_SHARING_VIOLATION + reason = _HELD_OPEN_REASON if held_open else None + raise _config_dir_error(base, exc, reason) from exc # The volume does not do what the hold asked: a step of the open, as below, except that a # refusal names the config dir, whose step it was. failed: OSError = exc @@ -3974,23 +3978,26 @@ def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: return _error_like(exc, what, None) -_UNHELD_DIR_REMEDY = "close what holds it open, or include_config = false" +#: Windows ERROR_SHARING_VIOLATION: another process holds the config dir open without the sharing +#: the hold asks for. +_WIN_SHARING_VIOLATION = 32 +#: The config dir refusal's cause and remedy for a sharing violation. As ``safe_exc`` renders the +#: error, its class included, the text before the dir is then 143 characters, so a dir of up to +#: 68 characters survives the ``dr_backup`` audit row's 200-character cut whole beside them, as +#: long a dir as Windows' own text left room for (``tests/test_backup_runner.py`` pins it). +_HELD_OPEN_REASON = "in use by another process; close what holds it open, or include_config = false" -def _config_dir_error( - base: Path, exc: OSError, reason: str | None = None, *, remedy: str | None = None -) -> OSError: +def _config_dir_error(base: Path, exc: OSError, reason: str | None = None) -> OSError: """The error that fails the backup when the config dir ``base`` itself could not be held as itself (vault BACKLOG #6573), naming the dir rather than a file under it, and keeping ``exc``'s codes. It gives ``reason``, else ``exc``'s text less the period Windows ends it - with, then ``remedy`` where one is given. The dir comes after those (:func:`_refusal`), so - the 200-character cut the ``dr_backup`` audit row's error makes takes a long path before the - cause and the remedy.""" + with. The dir comes after that (:func:`_refusal`), so the 200-character cut the ``dr_backup`` + audit row's error makes takes a long path before the cause.""" cause = reason if reason is not None else exc.strerror if exc.strerror is not None else str(exc) - cause = cause.rstrip().removesuffix(".") - if remedy is not None: - cause = f"{cause}; {remedy}" - return _refusal(exc, "config dir not held", cause, scrub_log_argument(str(base))) + return _refusal( + exc, "config dir not held", cause.rstrip().removesuffix("."), scrub_log_argument(str(base)) + ) def _rel_name(path: Path, base: Path) -> str: diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index 832cd9c74f..a7a33db68b 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -1720,7 +1720,7 @@ async def test_a_config_file_whose_first_screen_meets_an_unreachable_share_fails monkeypatch, checked, _os_error(2, "No such file or directory") ) result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) - assert faulted, "the control's fault ran" + assert faulted == [checked], "the control's fault ran" assert "config/swapped.toml" not in names # the control: a file gone is left out assert result.config_skipped_files == () monkeypatch.undo() @@ -1730,7 +1730,7 @@ async def test_a_config_file_whose_first_screen_meets_an_unreachable_share_fails ) with pytest.raises(BackupError, match="swapped.toml"): await _pass_with_bytes(tmp_path, key_b64, cfg) - assert faulted, "the fault ran" + assert faulted == [checked], "the fault ran" @pytest.mark.parametrize( @@ -2173,7 +2173,7 @@ def open_by_name(path, flags, *args, **kwargs): ("file-unreadable", 59), ("dir-holds-links", 57), ("dir-unreadable", 61), - ("dir-held-open", 15), + ("dir-held-open", 68), ("final-path", 41), ], ) @@ -2324,7 +2324,7 @@ async def test_a_root_hold_that_reports_no_such_path_while_the_dir_is_there_fail assert failed, "the fault ran" text = str(raised.value) assert "config dir not held: The system cannot find the path" in text - assert "close what holds it open, or include_config = false" in text + assert "close what holds it open" not in text # that remedy is a sharing violation's only @pytest.mark.skipif(sys.platform != "win32", reason="a Windows sharing violation") @@ -2346,7 +2346,7 @@ async def test_a_config_dir_another_handle_holds_open_for_delete_fails_naming_th text = str(raised.value) assert "config dir not held" in text and "WinError 32" in text # The BackupError's text is already cut at 200 characters, so the remedy survives the cut. - assert "close what holds it open, or include_config = false" in text + assert "in use by another process; close what holds it open, or include_config = false" in text assert "feed.py" not in text (tmp_path / "control").mkdir() _result, names, _bytes = await _pass_with_bytes(tmp_path / "control", key_b64, cfg) From 91580d2a3e5ae1016532bdc6173f276b1417bbec Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 13:50:09 -0600 Subject: [PATCH 46/49] Config backup docs: a stat failure on an unreachable share is no longer passed over; the held-dir quote is pinned Review round 2 of the repair: the include_config row still said the walk passes over any file whose stat fails, and that the skipped list names a file it could not stat for any reason but absence. Both now except a share or network path that cannot be reached, which fails the backup. A test pins that the row quotes the held-dir refusal text the code gives, and the constant's comment drops a miscounted length. Repair of the Lander's hold on PR 3535 (BACKLOG #6573). Verified-by: tests --- docs/CONFIGURATION.md | 2 +- messagefoundry/pipeline/dr_backup.py | 6 +++--- tests/test_backup_runner.py | 10 ++++++++++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index b99a3209d2..62d7fa2b2a 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and a remedy: if the volume has no drive letter, assign it one, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails, that final-path failure and a hold of the config dir refused with one of the three codes below included, and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these refusals, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, which names the config dir and the remedy (`in use by another process; close what holds it open, or include_config = false`), or that cannot be held for another reason while it is still there, which names the config dir; and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails for any reason but absence or a share or network path that cannot be reached (below), and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and a remedy: if the volume has no drive letter, assign it one, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails, that final-path failure and a hold of the config dir refused with one of the three codes below included, and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these refusals, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, which names the config dir and the remedy (`in use by another process; close what holds it open, or include_config = false`), or that cannot be held for another reason while it is still there, which names the config dir; and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence or an unreachable share or network path; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 539392220f..af331a8a5f 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -3982,9 +3982,9 @@ def _config_file_error(path: Path, base: Path, exc: OSError) -> OSError: #: the hold asks for. _WIN_SHARING_VIOLATION = 32 #: The config dir refusal's cause and remedy for a sharing violation. As ``safe_exc`` renders the -#: error, its class included, the text before the dir is then 143 characters, so a dir of up to -#: 68 characters survives the ``dr_backup`` audit row's 200-character cut whole beside them, as -#: long a dir as Windows' own text left room for (``tests/test_backup_runner.py`` pins it). +#: error, a dir of up to 68 characters survives the ``dr_backup`` audit row's 200-character cut +#: whole beside them, as long a dir as Windows' own text left room for +#: (``tests/test_backup_runner.py`` pins that length, and that the docs row quotes this text). _HELD_OPEN_REASON = "in use by another process; close what holds it open, or include_config = false" diff --git a/tests/test_backup_runner.py b/tests/test_backup_runner.py index a7a33db68b..db48bf4807 100644 --- a/tests/test_backup_runner.py +++ b/tests/test_backup_runner.py @@ -2353,6 +2353,16 @@ async def test_a_config_dir_another_handle_holds_open_for_delete_fails_naming_th assert "config/feed.py" in names # the control +def test_the_include_config_row_quotes_the_held_config_dir_refusal_as_the_code_gives_it() -> None: + """The ``include_config`` row of ``docs/CONFIGURATION.md`` quotes the cause and remedy the + refusal of a config dir another process holds open gives, so an operator who searches the + docs for the audit row's text finds it (vault BACKLOG #6573).""" + from messagefoundry.pipeline.dr_backup import _HELD_OPEN_REASON + + doc = (Path(__file__).resolve().parents[1] / "docs" / "CONFIGURATION.md").read_text("utf-8") + assert f"`{_HELD_OPEN_REASON}`" in doc + + @pytest.mark.skipif(sys.platform != "win32", reason="the final-path check is Windows-only") async def test_a_tar_failure_closes_the_handle_of_a_file_whose_final_path_cannot_be_read( tmp_path, key_b64, monkeypatch From 3e75f941363152edc378c2983c19eb5173dd5aa0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 14:32:09 -0600 Subject: [PATCH 47/49] docs: include_config row names the two unreachable codes and the unrecorded subfolder The include_config row of docs/CONFIGURATION.md said a share or network path that cannot be reached fails the backup. That holds for a file the walk listed. A subfolder whose listing fails with ERROR_BAD_NETPATH or ERROR_BAD_NET_NAME is dropped by the walk's onerror with no record, and the run succeeds. The row now says so, names the two codes where it said "unreachable", and says a share lost with another code at the first stat, such as ERROR_NETNAME_DELETED, is passed over. Text only; no code or test changes. Repair of the Lander hold on PR 3535 (BACKLOG #6573). Verified-by: tests --- docs/CONFIGURATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 62d7fa2b2a..98f65217bb 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3470,7 +3470,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | `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 | -| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails for any reason but absence or a share or network path that cannot be reached (below), and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and a remedy: if the volume has no drive letter, assign it one, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails, that final-path failure and a hold of the config dir refused with one of the three codes below included, and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these refusals, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. A share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. That failure covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, which names the config dir and the remedy (`in use by another process; close what holds it open, or include_config = false`), or that cannot be held for another reason while it is still there, which names the config dir; and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence or an unreachable share or network path; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | +| `include_config` | bool | `true` | bundle the running config dir (the last applied reload's root, else `--config`) into the archive, so the cold seed can carry the store **plus** the config that interprets it without assuming the DR box can reach the org's git repo. The archive holds every config file the walk listed only when `config_bundled` is true and `config_skipped_files` is empty. The manifest and the `dr_backup` audit row record `config_bundled`, the `config_dir` the pass read, `config_bundle_error`, `config_unreadable_files`, what `config_fingerprint` left out (vault BACKLOG #3765), and `config_skipped_files` with `config_skipped_count`, what the archive walk passed over (vault BACKLOG #5233); the `messagefoundry backup` summary carries `config_bundled`, `config_bundle_error` and, when it is not empty, the skipped list with its count. `config_bundled` is true only when the walk added at least one regular config file. A full pass whose walk adds none, such as over an empty config dir or one holding only links, still succeeds with the store snapshot and records `config_bundled: false` with `config_bundle_error: "no-regular-file"` (vault BACKLOG #5220). That value is a fixed token; every other `config_bundle_error` is an exception class name. What happens to a file the archive walk accepts and then cannot open or read is stated once, below. The walk passes over at least a symlink, on Windows a directory junction or volume mount point, a folder it cannot list and a file whose stat fails for any reason but absence, `ERROR_BAD_NETPATH` or `ERROR_BAD_NET_NAME` (below), so at least a share lost with another code, such as `ERROR_NETNAME_DELETED`, is passed over, and the run succeeds without them, except a config-only pass the walk then adds no regular file to, which fails (see the paragraph above this table). A filesystem mounted below the config dir on POSIX is not a link, and is walked. The walk adds each file from a handle it opened through no link below the config dir, and describes and fills the file's member from that handle, never by its name again, so a folder or a file swapped for a symlink, or on Windows a junction, after the walk checked it adds nothing from behind the link to the archive (vault BACKLOG #6573), outside at least the residuals below. A file swapped so is recorded as passed over; a folder swapped so may leave no record. A swap still reaches at least this, on POSIX and Windows alike: a folder swapped for a link while the walk lists it can put the names behind the link, never their bytes, in `config_skipped_files`, the audit row and the WARNING; the space estimate taken before the walk reads by name, so a swap can inflate it and refuse the backup for space. On POSIX a folder above the config dir, or the config dir itself, swapped for a link after the backup resolved the config dir is not detected, and the walk then reads what the link leads to; on Windows that holds for a folder above the config dir, only for a file added without the final-path check, as below, and for a file opened by name it holds for the config dir itself too. A hard link is not a link here, so a name swapped for a second hard link to another file is carried with that file's bytes. On Windows a file whose reparse point names no path, such as a cloud placeholder, is opened by name more than once, the last time through the placeholder's own filter after the open as itself checked it. That last open can follow a link swapped in since the open as itself, even to a UNC path, and so reach the host it names before the engine refuses what it reached. On Windows the walk also checks that each file's final path, every link resolved, is the config dir joined with the listed names, and passes the file over when the path read names another. When the query for that path fails with `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`, which the walk reads as the volume being unable to report one, the file is added from its handle without that check. That is a reading, not a proof: `ERROR_INVALID_PARAMETER` in particular is a generic code, and the walk trusts it on any volume, NTFS included; any other failure of that query fails the backup, naming the file. For `ERROR_PATH_NOT_FOUND`, which at least a volume with no drive letter gives for every file, the failure also names the query and a remedy: if the volume has no drive letter, assign it one, or set `include_config = false`. One WARNING per pass counts the files added without that check, names at most the first 1000 of them and gives each Windows error code seen. On the backup's walk the config dir itself and each folder below it are held, and refused if they are a link, while the file is opened; once the file is open, each is checked again by its handle before it is released, and the file is refused if any of them now names another path. That re-check sees one instant, so where the final path cannot be read at least these still go undetected: a held folder emptied, made a link in place and made a folder again between the file's open and the re-check, whose link the open followed; and a folder above the config dir, as above. A file the walk accepts and then cannot open or read fails the backup, naming the file, except in at least these cases. When the open fails, that final-path failure and a hold of the config dir refused with one of the three codes below included, and the name is then gone, the file is left out unrecorded, and when the name then reads as no regular file, or as a link, it is passed over. On Windows, when a step of the open, the hold of the config dir included, fails with one of those three codes, which say the volume does not do what the step asked, the backup asks the config dir's volume whether it supports reparse points. Where the volume reports it does not, no link can be there, so the file is opened by name below the config dir as resolved, as before vault BACKLOG #6573, holding nothing, and counted in the same WARNING. Where it reports it does, the backup fails, naming the cause, the remedy and then the file, or the config dir when the step was its hold: fix the local filter driver or the share client that refused the step, or set `include_config = false`. A file whose name became something other than a regular file before that open, or whose open reached something other than a regular file, is passed over. Where the answer cannot be read, it fails the same way with the remedy to keep the config dir on a local NTFS or ReFS volume, or set `include_config = false`. Each of these refusals, and the config dir's own below, gives the cause and any remedy before the file or the config dir it names, so the 200-character cut the `dr_backup` audit row's error makes drops a long name rather than them. A network redirector or file-system driver that reports that support falsely is an unmeasured residual: the open by name follows any link there. For a file the walk listed, a share or network path that cannot be reached (`ERROR_BAD_NETPATH`, `ERROR_BAD_NET_NAME`), which Windows reports as a name not found, is no such case, nor is a second look at the name that fails for any reason but absence, nor a read that fails once the file is open: each fails the backup. A subfolder whose listing fails with either code is at least one exception: it is left out with no record, and the run succeeds. The failure of the backup covers at least a file the service cannot read, on Windows a config folder another process holds open for delete, which names the file, or the config dir itself so held, which names the config dir and the remedy (`in use by another process; close what holds it open, or include_config = false`), or that cannot be held for another reason while it is still there, which names the config dir; and on POSIX a file another process holds a conflicting kernel lease on, which fails rather than waits for the lease to break. A symlinked folder or a junction the walk lists as a folder is named in one WARNING at least where the walk reaches it (vault BACKLOG #5221); one inside a pruned editor candidate or backup staging folder is not. `config_unreadable_files` is what the digest met, fixed before the walk runs, not a census of the archive. With this on it names at least a folder the digest covers (`codesets/`, `environments/`) and could not list, or a file it covers and could not stat for any reason but absence, each of which the archive also lacks if the fault lasts to the walk, and a file locked only while the digest read it, which the archive carries. `config_skipped_files` is what the walk itself passed over, relative to the config dir, with `.` for the dir itself: the first of them by name, at most 1000 and at most 256 KiB of the manifest's JSON, with `config_skipped_count` the total, so this list cannot by itself push the manifest past its 1 MiB read cap. The entries other than a directory link the walk lists as a folder are also named together in one WARNING per pass; such a link is named in the WARNING above, and a dangling one, which the walk lists as a file, in this one. It names at least a file the walk did not add as a regular file, such as a symlinked `connections.toml` the digest read through, and a file it could not stat for any reason but absence, `ERROR_BAD_NETPATH` or `ERROR_BAD_NET_NAME`; a directory link it did not follow, or a folder whose `lstat` failed; and a folder it could not list, the config dir itself included, but not a subfolder whose listing Windows reports as a name not found, `ERROR_BAD_NETPATH` and `ERROR_BAD_NET_NAME` included, whether or not the digest covers it. It does not name at least a second hard link to a file the walk already added, which the archive stores as a link member and a restore writes as a copy of that file, a file gone by the walk's stat, a subfolder gone before the walk lists it, a config editor's lock file, or a candidate or staging folder the walk lists as a plain folder, nor each file below a link or a folder it names. When the config dir itself is gone or cannot be listed, a full backup still succeeds with the store snapshot, logs one WARNING naming the directory and the error class, and records `config_bundled: false` with that class; no alert is raised for it. A config dir lost after that read and before the walk is recorded instead as `config_bundled: false` with `"no-regular-file"` and `config_skipped_files: ["."]`. A config-only backup fails in both cases, as a `snapshot` failure, whether the read or the walk meets the fault. The `messagefoundry backup` CLI bundles its own `--config` argument instead | | `verify_after_backup` | bool | `true` | run the lightweight restore-verify after every backup (open + `integrity_check` + row-count). On by default — a backup nobody has opened is a backup that silently doesn't restore | | `full_restore_verify` | bool | `false` | the heavier verify: restore the snapshot to a throwaway temp DB, open it through the real `open_store` path **under this instance's live `[store]` settings** (only the path and the backend substituted), then decrypt and authenticate its cipher-covered cells and report how many were opened. A snapshot holding sealed cells that these settings resolve no key for is reported `KEY_MISMATCH`, not `FAIL` — the archive is fine, the key configuration is not. On-demand / opt-in extra, deliberately **not** the per-backup default | | `config_only_on_server_db` | bool | `true` | on a Postgres/SQL Server store the DB backup is DBA-delegated (#52), so back up the **config bundle only**. `false` = skip the backup entirely on a server-DB store (not even a config-only archive) | From 2280c03f936d96c33c03f2e3da22feee6c82bb3a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 18:05:43 -0600 Subject: [PATCH 48/49] Reference key refusals name the remedy, and any CipherError names a folding state collation (BACKLOG #6613) The SQL Server state cache note rides any CipherError again, as on main: the Transit cipher raises a plain one for a failed tag whose reason it cannot read. The padding, NUL and surrogate refusals name the remedy at the source. CONFIGURATION.md and the changelog claim only what holds. Verified-by: tests --- changelog.d/6613.changed.md | 18 +++++++++--------- docs/CONFIGURATION.md | 12 +++++++----- messagefoundry/store/reference_keys.py | 13 +++++++------ messagefoundry/store/sqlserver.py | 15 +++++++-------- tests/test_reference_key_guard.py | 4 ++++ .../test_sqlserver_state_key_limits_offline.py | 15 +++++++-------- 6 files changed, 41 insertions(+), 36 deletions(-) diff --git a/changelog.d/6613.changed.md b/changelog.d/6613.changed.md index e7010964a6..947c2040e7 100644 --- a/changelog.d/6613.changed.md +++ b/changelog.d/6613.changed.md @@ -1,17 +1,17 @@ -- **Every store backend refuses a reference snapshot holding padded, NUL or surrogate keys, and a - set name SQL Server would merge.** SQL Server's key and name widths stay its own. SQLite and +- **Every store backend refuses a reference snapshot holding two keys that differ only by trailing + spaces, or a key holding NUL or a surrogate; a set name ending in a space or holding NUL or a + surrogate is refused at load and at rename.** These rules still accept a lone key with a trailing + space and an over-long key; SQL Server's key and name widths stay its own check. SQLite and Postgres now refuse, before the snapshot's transaction, two keys that differ only by trailing spaces, as SQL Server already did, and every backend refuses a key holding U+0000 (NUL), which Postgres text cannot store, or a surrogate code point, which no backend stores. Each refusal is a `ReferenceSnapshotRefused` (the collision is its subclass `ReferenceKeyCollision`), naming the - set and the keys by 0-based ordinal, never a key, and logged whole; the last-good snapshot - stays active and the sync fails every interval until the source changes. A dry run and + set, the keys by 0-based ordinal and the remedy, never a key, and logged whole; the last-good + snapshot stays active and the sync fails every interval until the source changes. A dry run and `check` skip such a file-backed set with a warning naming the same set, rule and ordinals. A `Reference(...)` name that ends in a space or holds U+0000 or a surrogate is refused at load on every backend, and so is a rename to such a name, since SQL Server compares `npi` and `npi ` as one name. A SQL Server open now also reports a non-binary collation on the `reference` and - `reference_version` key columns, at WARNING, and repairs nothing. The note naming a folding - `state` collation now rides only a failed authentication tag, the one error a merged row can - cause. `SetState`'s refusal of a surrogate code point now says so rather than "lone - surrogate", since half of a pair is refused too, and `StateKeyError` is exported from - `messagefoundry`. (`BACKLOG #6613`) + `reference_version` key columns, at WARNING, and repairs nothing. + `SetState`'s refusal of a surrogate code point now says so rather than "lone surrogate", since + half of a pair is refused too, and `StateKeyError` is exported from `messagefoundry`. (`BACKLOG #6613`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 9baf769d99..5c8ec3df54 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -721,8 +721,8 @@ def anonymize(msg): Postgres, and on a SQL Server database whose `state` table this release or a later one created. A SQL Server `state` table created earlier keeps the database's default collation, which may fold case (BACKLOG #1588); the engine logs a WARNING at every open of a table whose key columns are not - binary, naming the collation and the remedy, and repairs nothing (BACKLOG #4917). The open - goes on after the warning; only a failure of the metadata read itself stops it. + binary, naming the collation and the remedy, and repairs nothing (BACKLOG #4917). The + warning itself does not stop the open. - **Exactly-once / re-run safety.** Because the write commits in the **same transaction** as the outbound rows, a crash before commit leaves **no** state (atomic with the handoff) and the attempt that commits applies the write **exactly once per message** — this preserves the staged pipeline's @@ -819,9 +819,11 @@ crash-re-run — the same accepted caveat as a code-set hot-reload). U+DFFF), which no backend stores, before the snapshot's transaction (BACKLOG #4917, #6613). The sync then fails and alerts every interval until the source changes, and the last-good snapshot stays active. The log line names the set and the keys by 0-based ordinal, their position among - the keys the source yielded, never a key; an ordinal is not a file line number. A lone key with - a trailing space is not refused. A dry run and `messagefoundry check` skip such a file-backed - set, with a warning naming the same set, rule and ordinals, since the next sync refuses it; an + the keys the source yielded, never a key; an ordinal is not a file line number. The line also + names the remedy, at the source: for two keys that differ only by trailing spaces, remove one of + the two, since stripping the spaces alone leaves a duplicate key; for NUL or a surrogate, strip it + or remove that key. A lone key with a trailing space is not refused. A dry run and + `messagefoundry check` skip such a file-backed set, with a warning naming the same set, rule and ordinals, since the next sync refuses it; an engine that synced the set before keeps serving its last-good snapshot meanwhile. A `Reference(...)` name that ends in a space or holds NUL or a surrogate code point is refused at load, on every backend, and so is a rename to such a name. SQL Server compares `npi` and `npi ` diff --git a/messagefoundry/store/reference_keys.py b/messagefoundry/store/reference_keys.py index 133d3b6e0e..1d89624cb8 100644 --- a/messagefoundry/store/reference_keys.py +++ b/messagefoundry/store/reference_keys.py @@ -52,14 +52,14 @@ def refuse_unstorable_reference_keys(name: str, rows: Mapping[str, Any]) -> None if "\x00" in key: raise ReferenceSnapshotRefused( f"reference set {name!r}: key #{ordinal} contains U+0000 (NUL), which Postgres" - " text cannot store; refusing the snapshot (key value withheld: reference keys" - " may be PHI)" + " text cannot store; refusing the snapshot; strip it or remove that key at the" + " source (key value withheld: reference keys may be PHI)" ) if not key.isascii() and has_lone_surrogate(key): raise ReferenceSnapshotRefused( f"reference set {name!r}: key #{ordinal} contains a surrogate code point" - " (U+D800..U+DFFF), which no backend stores; refusing the snapshot (key value" - " withheld: reference keys may be PHI)" + " (U+D800..U+DFFF), which no backend stores; refusing the snapshot; strip it or" + " remove that key at the source (key value withheld: reference keys may be PHI)" ) if not key.endswith(" "): continue @@ -72,7 +72,8 @@ def refuse_unstorable_reference_keys(name: str, rows: Mapping[str, Any]) -> None # No digest: an MRN-shaped key is guessable from a short unsalted hash. raise ReferenceKeyCollision( f"reference set {name!r}: keys #{first} and #{later} differ only by trailing" - " spaces, which SQL Server compares as equal; refusing the snapshot (key values" - " withheld: reference keys may be PHI)" + " spaces, which SQL Server compares as equal; refusing the snapshot; remove one of" + " the two at the source, since stripping the spaces alone leaves a duplicate key" + " (key values withheld: reference keys may be PHI)" ) padded[stripped] = ordinal diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index 0e518cad2a..b47a1b15e5 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -143,7 +143,6 @@ CipherInfo, IdentityCipher, StoreKeylessError, - UnauthenticatedCipherError, allows_unmarked, cell_aad, cipher_info, @@ -10585,19 +10584,19 @@ async def _report_key_collations(self) -> str | None: async def _load_state_cache(self, *, folded_collation: str | None = None) -> None: """Warm the transform-state read-through cache from the ``state`` table at open (ADR 0005). - A failed AEAD tag (:class:`UnauthenticatedCipherError`) is how a row merged across a case - or accent variant shows: its value was sealed to the other spelling. When - :meth:`_report_key_collations` found a folding ``folded_collation``, that error carries a - note naming it as a possible cause (BACKLOG #4917, #6613). A key not supplied fails the tag - too, so it carries the note as well. A plain ``CipherError``, such as a malformed cell, - cannot come from a merge and carries none.""" + A row merged across a case or accent variant fails to decrypt here, since its value was + sealed to the other spelling. When :meth:`_report_key_collations` found a folding + ``folded_collation``, any ``CipherError`` carries a note naming it as a possible cause + (BACKLOG #4917). The class does not tell a merge apart: the Transit cipher raises a plain + ``CipherError`` for a failed tag where it cannot read Vault's reason as one, and a key not + supplied or a malformed cell carries the note too.""" try: self._state_cache = await cipher_bulk_call( self._cipher, self._decode_state_rows, await self._fetchall("SELECT namespace, [key], value FROM state"), ) - except UnauthenticatedCipherError as exc: + except CipherError as exc: if folded_collation is not None: exc.add_note( f"the state table's key columns use collation {folded_collation}, not a" diff --git a/tests/test_reference_key_guard.py b/tests/test_reference_key_guard.py index df90fc87df..40ec7861e2 100644 --- a/tests/test_reference_key_guard.py +++ b/tests/test_reference_key_guard.py @@ -37,6 +37,8 @@ def test_padded_keys_are_refused_naming_both_ordinals_and_no_key() -> None: refuse_unstorable_reference_keys("set", rows) text = str(exc.value) assert f"keys #{first} and #{later} differ" in text + # The remedy: stripping alone would make two equal keys, which the loaders refuse. + assert "remove one of the two at the source" in text assert "MRN" not in text and "sha256" not in text # nothing of the key (PHI) assert isinstance(exc.value, ReferenceSnapshotRefused) @@ -45,6 +47,7 @@ def test_a_nul_in_a_key_is_refused_naming_its_ordinal_and_no_key() -> None: with pytest.raises(ReferenceSnapshotRefused, match=r"key #1 contains U\+0000") as exc: refuse_unstorable_reference_keys("set", {"A": 1, "MRN\x00-2": 2}) assert "MRN" not in str(exc.value) + assert "strip it or remove that key at the source" in str(exc.value) assert not isinstance(exc.value, ReferenceKeyCollision) @@ -56,6 +59,7 @@ def test_a_surrogate_in_a_key_is_refused_naming_its_ordinal_and_no_key() -> None with pytest.raises(ReferenceSnapshotRefused, match="key #1 contains a surrogate") as exc: refuse_unstorable_reference_keys("set", {"A": 1, key: 2}) assert "MRN" not in str(exc.value) + assert "strip it or remove that key at the source" in str(exc.value) refuse_unstorable_reference_keys("set", {"MRN-\U0001f600": 1, "café": 2}) diff --git a/tests/test_sqlserver_state_key_limits_offline.py b/tests/test_sqlserver_state_key_limits_offline.py index 410dd498a2..9a7f8c07da 100644 --- a/tests/test_sqlserver_state_key_limits_offline.py +++ b/tests/test_sqlserver_state_key_limits_offline.py @@ -145,15 +145,14 @@ async def test_one_drifted_column_is_enough_to_report() -> None: @pytest.mark.parametrize("folded", ["SQL_Latin1_General_CP1_CI_AS", None]) @pytest.mark.parametrize("error", [UnauthenticatedCipherError, CipherError]) -async def test_only_an_unauthenticated_row_names_the_drifted_collation( +async def test_an_undecryptable_row_names_the_drifted_collation( monkeypatch: pytest.MonkeyPatch, folded: str | None, error: type[CipherError] ) -> None: - """The keyed symptom of a merged row is a failed AEAD tag at the cache warm-up, which the - cipher raises as ``UnauthenticatedCipherError``. It still fails closed, and when the report - found a folding collation the error carries a note naming it. The controls: with no drift - found there is no note, and a plain ``CipherError`` (such as a malformed cell) carries none - either, since a merged row cannot cause it (BACKLOG #6613). A key not supplied also raises - ``UnauthenticatedCipherError``, so it carries the note, which names only a possible cause.""" + """The keyed symptom of a merged row is a ``CipherError`` at the cache warm-up: usually + ``UnauthenticatedCipherError``, but a plain one where the Transit cipher cannot read Vault's + reason as a failed tag. Either still fails closed, and when the report found a folding + collation it carries a note naming that as a possible cause (BACKLOG #4917, #6613). The + control: with no drift found there is no note.""" def _refuse(*args: Any, **kwargs: Any) -> Any: raise error("could not decrypt a state row") @@ -165,7 +164,7 @@ def _refuse(*args: Any, **kwargs: Any) -> Any: await store._load_state_cache(folded_collation=folded) assert type(raised.value) is error notes = getattr(raised.value, "__notes__", []) - if folded is not None and error is UnauthenticatedCipherError: + if folded is not None: assert any(folded in n and "may have been" in n for n in notes) else: assert notes == [] From fc69c72ca58449ee5f235c8403aa1657d8e1584a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 18:11:05 -0600 Subject: [PATCH 49/49] Reference key remedies keep lookups working, and the state cache docstring hedges (BACKLOG #6613) Review repair: the collision remedy keeps one unpadded key, the surrogate remedy writes a pair as its one character, and a merged row may, not must, fail to decrypt. Verified-by: tests --- changelog.d/6613.changed.md | 6 +++--- docs/CONFIGURATION.md | 9 +++++---- messagefoundry/store/reference_keys.py | 25 ++++++++++++++----------- messagefoundry/store/sqlserver.py | 2 +- tests/test_reference_key_guard.py | 9 +++++---- 5 files changed, 28 insertions(+), 23 deletions(-) diff --git a/changelog.d/6613.changed.md b/changelog.d/6613.changed.md index 947c2040e7..9c9288ed27 100644 --- a/changelog.d/6613.changed.md +++ b/changelog.d/6613.changed.md @@ -4,9 +4,9 @@ space and an over-long key; SQL Server's key and name widths stay its own check. SQLite and Postgres now refuse, before the snapshot's transaction, two keys that differ only by trailing spaces, as SQL Server already did, and every backend refuses a key holding U+0000 (NUL), which - Postgres text cannot store, or a surrogate code point, which no backend stores. Each refusal is - a `ReferenceSnapshotRefused` (the collision is its subclass `ReferenceKeyCollision`), naming the - set, the keys by 0-based ordinal and the remedy, never a key, and logged whole; the last-good + Postgres text cannot store, or a surrogate code point, which no backend stores. Each of + these key refusals is a `ReferenceSnapshotRefused` (the collision is its subclass + `ReferenceKeyCollision`), naming the set, the keys by 0-based ordinal and the remedy, never a key, and logged whole; the last-good snapshot stays active and the sync fails every interval until the source changes. A dry run and `check` skip such a file-backed set with a warning naming the same set, rule and ordinals. A `Reference(...)` name that ends in a space or holds U+0000 or a surrogate is refused at load on diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5c8ec3df54..31b963e5ea 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -821,10 +821,11 @@ crash-re-run — the same accepted caveat as a code-set hot-reload). stays active. The log line names the set and the keys by 0-based ordinal, their position among the keys the source yielded, never a key; an ordinal is not a file line number. The line also names the remedy, at the source: for two keys that differ only by trailing spaces, remove one of - the two, since stripping the spaces alone leaves a duplicate key; for NUL or a surrogate, strip it - or remove that key. A lone key with a trailing space is not refused. A dry run and - `messagefoundry check` skip such a file-backed set, with a warning naming the same set, rule and ordinals, since the next sync refuses it; an - engine that synced the set before keeps serving its last-good snapshot meanwhile. A + the two and strip the spaces from the one kept; for NUL or a lone surrogate, strip it or remove + that key; for a surrogate pair, write it as its one character or remove that key. Keep only one of + any two keys that leaves equal. A lone key with a trailing space is not refused. A dry run and + `messagefoundry check` skip such a file-backed set, with a warning naming the same + set, rule and ordinals, since the next sync refuses it; an engine that synced the set before keeps serving its last-good snapshot meanwhile. A `Reference(...)` name that ends in a space or holds NUL or a surrogate code point is refused at load, on every backend, and so is a rename to such a name. SQL Server compares `npi` and `npi ` as one name, so a set renamed from one to the other across a reload would share the old set's diff --git a/messagefoundry/store/reference_keys.py b/messagefoundry/store/reference_keys.py index 1d89624cb8..cea8040ea5 100644 --- a/messagefoundry/store/reference_keys.py +++ b/messagefoundry/store/reference_keys.py @@ -28,10 +28,10 @@ class ReferenceSnapshotRefused(ValueError): """A reference snapshot refused before its transaction, because some store backend could not hold one of its keys exactly (BACKLOG #6613). The last-good snapshot stays active. - The message holds the set name, the rule and key ordinals, never a key or a hash of one, so - ``reference_sync`` logs it whole where it logs any other source error by class name only. An - ordinal is the key's 0-based position in the snapshot as the source yielded it, not a file line - number.""" + The message holds the set name, the rule, key ordinals and a fixed remedy, never a key or a hash + of one, so ``reference_sync`` logs it whole where it logs any other source error by class name + only. An ordinal is the key's 0-based position in the snapshot as the source yielded it, not a + file line number.""" class ReferenceKeyCollision(ReferenceSnapshotRefused): @@ -52,14 +52,17 @@ def refuse_unstorable_reference_keys(name: str, rows: Mapping[str, Any]) -> None if "\x00" in key: raise ReferenceSnapshotRefused( f"reference set {name!r}: key #{ordinal} contains U+0000 (NUL), which Postgres" - " text cannot store; refusing the snapshot; strip it or remove that key at the" - " source (key value withheld: reference keys may be PHI)" + " text cannot store; refusing the snapshot; at the source, strip the NUL from that" + " key or remove the key, and keep only one of any two keys left equal (key value" + " withheld: reference keys may be PHI)" ) if not key.isascii() and has_lone_surrogate(key): raise ReferenceSnapshotRefused( f"reference set {name!r}: key #{ordinal} contains a surrogate code point" - " (U+D800..U+DFFF), which no backend stores; refusing the snapshot; strip it or" - " remove that key at the source (key value withheld: reference keys may be PHI)" + " (U+D800..U+DFFF), which no backend stores; refusing the snapshot; at the" + " source, write a surrogate pair as its one character, strip a lone surrogate from" + " that key or remove the key, and keep only one of any two keys left equal (key" + " value withheld: reference keys may be PHI)" ) if not key.endswith(" "): continue @@ -72,8 +75,8 @@ def refuse_unstorable_reference_keys(name: str, rows: Mapping[str, Any]) -> None # No digest: an MRN-shaped key is guessable from a short unsalted hash. raise ReferenceKeyCollision( f"reference set {name!r}: keys #{first} and #{later} differ only by trailing" - " spaces, which SQL Server compares as equal; refusing the snapshot; remove one of" - " the two at the source, since stripping the spaces alone leaves a duplicate key" - " (key values withheld: reference keys may be PHI)" + " spaces, which SQL Server compares as equal; refusing the snapshot; at the source," + " remove one of the two and strip the trailing spaces from the one kept (key values" + " withheld: reference keys may be PHI)" ) padded[stripped] = ordinal diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index b47a1b15e5..8ba4b3fb34 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -10584,7 +10584,7 @@ async def _report_key_collations(self) -> str | None: async def _load_state_cache(self, *, folded_collation: str | None = None) -> None: """Warm the transform-state read-through cache from the ``state`` table at open (ADR 0005). - A row merged across a case or accent variant fails to decrypt here, since its value was + A row merged across a case or accent variant may fail to decrypt here, where its value was sealed to the other spelling. When :meth:`_report_key_collations` found a folding ``folded_collation``, any ``CipherError`` carries a note naming it as a possible cause (BACKLOG #4917). The class does not tell a merge apart: the Transit cipher raises a plain diff --git a/tests/test_reference_key_guard.py b/tests/test_reference_key_guard.py index 40ec7861e2..0ab3032ea4 100644 --- a/tests/test_reference_key_guard.py +++ b/tests/test_reference_key_guard.py @@ -37,8 +37,8 @@ def test_padded_keys_are_refused_naming_both_ordinals_and_no_key() -> None: refuse_unstorable_reference_keys("set", rows) text = str(exc.value) assert f"keys #{first} and #{later} differ" in text - # The remedy: stripping alone would make two equal keys, which the loaders refuse. - assert "remove one of the two at the source" in text + # The remedy: a lone padded key is accepted, so keeping it padded would miss every lookup. + assert "remove one of the two and strip the trailing spaces from the one kept" in text assert "MRN" not in text and "sha256" not in text # nothing of the key (PHI) assert isinstance(exc.value, ReferenceSnapshotRefused) @@ -47,7 +47,7 @@ def test_a_nul_in_a_key_is_refused_naming_its_ordinal_and_no_key() -> None: with pytest.raises(ReferenceSnapshotRefused, match=r"key #1 contains U\+0000") as exc: refuse_unstorable_reference_keys("set", {"A": 1, "MRN\x00-2": 2}) assert "MRN" not in str(exc.value) - assert "strip it or remove that key at the source" in str(exc.value) + assert "at the source, strip the NUL from that key or remove the key" in str(exc.value) assert not isinstance(exc.value, ReferenceKeyCollision) @@ -59,7 +59,8 @@ def test_a_surrogate_in_a_key_is_refused_naming_its_ordinal_and_no_key() -> None with pytest.raises(ReferenceSnapshotRefused, match="key #1 contains a surrogate") as exc: refuse_unstorable_reference_keys("set", {"A": 1, key: 2}) assert "MRN" not in str(exc.value) - assert "strip it or remove that key at the source" in str(exc.value) + assert "at the source, write a surrogate pair as its one character" in str(exc.value) + assert "strip a lone surrogate from that key or remove the key" in str(exc.value) refuse_unstorable_reference_keys("set", {"MRN-\U0001f600": 1, "café": 2})