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/changelog.d/6613.changed.md b/changelog.d/6613.changed.md new file mode 100644 index 0000000000..9c9288ed27 --- /dev/null +++ b/changelog.d/6613.changed.md @@ -0,0 +1,17 @@ +- **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 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 + 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. + `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 037d2348cf..31b963e5ea 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 + 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 @@ -811,6 +813,25 @@ 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, 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. The line also + names the remedy, at the source: for two keys that differ only by trailing spaces, remove one of + 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 + 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 450bb44539..97c79eec74 100644 --- a/docs/adr/0006-external-data-lookups.md +++ b/docs/adr/0006-external-data-lookups.md @@ -296,6 +296,13 @@ 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 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 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/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/secretprovider_vault.py b/messagefoundry/config/secretprovider_vault.py index dbe16505cb..b742e603a8 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 @@ -62,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 @@ -76,33 +80,19 @@ #: 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 " 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/config/wiring.py b/messagefoundry/config/wiring.py index 294b5eff8e..f229df051d 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, @@ -6029,8 +6033,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. @@ -6040,16 +6045,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( @@ -7620,6 +7626,27 @@ 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 a set name (the `state` + # 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/engine_secrets.py b/messagefoundry/engine_secrets.py index 36c64be3a7..23220de9ac 100644 --- a/messagefoundry/engine_secrets.py +++ b/messagefoundry/engine_secrets.py @@ -32,8 +32,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 could read them); +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 @@ -72,6 +72,7 @@ "open_secrets_directory", "secret_setting", "secret_settings", + "vault_token_unset", ] #: The variable that names the secrets directory. A path, not a secret. @@ -631,6 +632,34 @@ 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. Both Vault hops build their unset-token refusal here (BACKLOG #2851, #4800); each + keeps its own unset-address text. + + 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` 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 " + 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/pipeline/dryrun.py b/messagefoundry/pipeline/dryrun.py index ee9f3ad3de..c6d657677a 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", @@ -680,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]): @@ -715,8 +721,9 @@ 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 - per set per process. + a set whose keys break a rule every store backend refuses (BACKLOG #6613), and a set whose file + 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`` @@ -729,9 +736,19 @@ 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 + # 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 # missing with nothing to say why. The set name only, never the loader's text: that can 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/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: 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/keyprovider_vault.py b/messagefoundry/store/keyprovider_vault.py index cd40a6e150..0b1e2543a4 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 @@ -68,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. @@ -85,34 +89,19 @@ #: ``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 " 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/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 8b3e18db40..9a3abc250e 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -214,6 +214,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, @@ -5530,7 +5531,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. 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 new file mode 100644 index 0000000000..cea8040ea5 --- /dev/null +++ b/messagefoundry/store/reference_keys.py @@ -0,0 +1,82 @@ +# 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). + +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, and ``pipeline/dryrun.py`` runs the same rules in a preview. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from messagefoundry.controlchars import has_lone_surrogate + +__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, 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): + """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, 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. 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: + raise ReferenceSnapshotRefused( + f"reference set {name!r}: key #{ordinal} contains U+0000 (NUL), which Postgres" + " 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; 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 + 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; 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 ac31138059..8ba4b3fb34 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, @@ -209,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, @@ -799,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. ``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 + + def _keep_matchable_lanes(lanes: Sequence[str]) -> list[str]: """Drop requested lane names that exceed the NVARCHAR(256) lane column (AC-11). @@ -2657,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, @@ -2677,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,8 +4606,10 @@ 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). - folded = await store._report_state_key_collation() + # 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 + # body hash + compat) — a miss degrades LOUDLY to the shipped batch, never a failed @@ -4636,7 +4646,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 @@ -10521,45 +10531,79 @@ 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]] = {} # 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( + "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 found: + log.warning( + "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(f"{t}.{c}" for t in sorted(found) for c in sorted(columns[t])), + ", ".join(sorted(set().union(*found.values()))), + _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 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 + ``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 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 def _decode_state_rows( self, rows: Sequence[Mapping[str, Any]] @@ -10581,20 +10625,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). @@ -10673,53 +10703,33 @@ 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: + # 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( - 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`` @@ -10728,6 +10738,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 98e338836b..bfae12022e 100644 --- a/messagefoundry/store/store.py +++ b/messagefoundry/store/store.py @@ -210,6 +210,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, @@ -15684,7 +15685,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. 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..849bf39750 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,20 @@ 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) + + +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) diff --git a/tests/test_engine_secrets.py b/tests/test_engine_secrets.py index 2e3c713270..e6602c5915 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: diff --git a/tests/test_postgres_store.py b/tests/test_postgres_store.py index cb10fe8dc3..a4c7409ed9 100644 --- a/tests/test_postgres_store.py +++ b/tests/test_postgres_store.py @@ -2057,7 +2057,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..0ab3032ea4 --- /dev/null +++ b/tests/test_reference_key_guard.py @@ -0,0 +1,113 @@ +# 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``), +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. +""" + +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 + # 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) + + +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 "at the source, strip the NUL from that key or remove the key" in str(exc.value) + 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) + 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}) + + +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..23b24195d0 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,76 @@ 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"), + ("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``, + 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_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, 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 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() + 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(dry_run_reference_view(reg)) == {"clean"} # a second build, as per message + assert set(view) == {"clean"} + 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 + + 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 +1114,41 @@ 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") + # 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)" + + 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..9a7f8c07da 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,36 @@ 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.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 + + @pytest.mark.parametrize( "collation", [ @@ -105,66 +132,71 @@ 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" +@pytest.mark.parametrize("folded", ["SQL_Latin1_General_CP1_CI_AS", None]) +@pytest.mark.parametrize("error", [UnauthenticatedCipherError, CipherError]) async def test_an_undecryptable_row_names_the_drifted_collation( - monkeypatch: pytest.MonkeyPatch, + 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 ``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 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: + 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. 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: - store._guard_reference_widths("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) - - -def test_reference_keys_that_do_not_collide_pass_the_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.""" + 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. 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) - store._guard_reference_widths("set", {"a ": 1, " a": 2, "a\t": 3, "A": 4, "b": 5}) + 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 55e4a4b770..7b7caaa04d 100644 --- a/tests/test_transform_state.py +++ b/tests/test_transform_state.py @@ -158,10 +158,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.