From 6ff0a963ee49a1d35f4f8896d5424a3752e11bbe Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:09:56 -0600 Subject: [PATCH 01/12] Admin role, scope and password-reset writes answer 423 for a record that fails its seal PUT /users/{id}/roles, PUT /users/{id}/channel-scope and POST /users/{id}/reset-password now read the account through the checked read (_checked_user), so a record that fails its integrity seal answers the 423 the admin reads answer, reported, rather than a 409 from the write's own seal check (roles) or a 404 from the service loader (scope, reset). The role write's Administrator-grant alert now decides on the checked record's roles, not a raw read. docs/SECURITY.md names the three routes in its route rows and in "What an admin user read reports", with the reset's grant cost. BACKLOG #5520 items 2 and 13. --- docs/SECURITY.md | 14 ++++-- messagefoundry/api/auth_routes.py | 16 ++++--- .../tests/test_ui_user_seal.py | 32 +++++++++++-- tests/test_console_seam_inventory.py | 4 ++ tests/test_unreadable_user_raw_callers.py | 5 +- tests/test_user_seal_routes.py | 48 ++++++++++++++++++- 6 files changed, 100 insertions(+), 19 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index aeb68ca102..17f58590af 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1673,8 +1673,8 @@ tuple: they act only on the caller's own account. | `DELETE` | `/users/{user_id}` | `users:manage` | `require_step_up` | | `DELETE` | `/users/{user_id}/sessions` | `users:manage` | `require_step_up`; **refuses (400) when `user_id` is the caller's own** (BACKLOG #1149) -- end your own from `DELETE /me/sessions` and sign-out instead | | `DELETE` | `/sessions` | `users:manage` | `require_step_up_action` (action `revoke_all_sessions`). Ends the sessions it finds and keeps the caller's current session, except at least when that session's seal fails, when it is ended too, and when the revoke declines to re-stamp it, because an earlier revoke's sweep missed it or its account's record fails its seal, when the revoke ends it in the same transaction (BACKLOG #4975 and its follow-up). Whether it kept that session, in the reply and in the audit row's scope, is the store's answer from the revoke's own transaction, not a read made after it (BACKLOG #4975). Writes one `auth.session_revoked` row with the count, even a zero (BACKLOG #2614); the count includes the caller's own session wherever the call ended it. What it may miss: *Limits of the session sweep* under [Federated sign-in](#federated-sign-in-oidc-browser-only--adr-0142). `messagefoundry admin-revoke-sessions` is the same act from the host, for when the API is not trusted | -| `PUT` | `/users/{user_id}/roles` | `users:manage` | `require_step_up`; **refuses (400) when `user_id` is the caller's own** (BACKLOG #1149) | -| `POST` | `/users/{user_id}/reset-password` | `users:manage` | `require_step_up_action` (action `admin_reset_password`) | +| `PUT` | `/users/{user_id}/roles` | `users:manage` | `require_step_up`; **refuses (400) when `user_id` is the caller's own** (BACKLOG #1149). The account is read with its record checked against its integrity seal (BACKLOG #5520): 423 when the record fails it, with nothing of the row answered. What the 423 reports, and when a row read mid-write is not refused: *What an admin user read reports* below this table; 404 for an unknown user | +| `POST` | `/users/{user_id}/reset-password` | `users:manage` | `require_step_up_action` (action `admin_reset_password`). The account is read with its record checked against its integrity seal (BACKLOG #5520): 423 when the record fails it, with nothing of the row answered. What the 423 reports, and when a row read mid-write is not refused: *What an admin user read reports* below this table; 404 for an unknown user | | `GET` | `/users/{user_id}/federated-identity` | `users:manage` | `require` (a read on the `users:manage` tier, like `GET /users/{user_id}/channel-scope`). The account's stored `issuer`/`subject`, the issuer a bind would use, and whether the account carries its directory id: the pair the console's federated-identity screen shows, for a JSON caller to send back as `expected_issuer`/`expected_subject` (BACKLOG #2331). No step-up, so it spends no grant. Audited as every satisfied route is, by its `auth.permission_granted` row, as the channel-scope read is. The console page of the same pair asks for the step-up window, because it also offers the link and unlink forms. 404 for an unknown user. The account is read with its record checked against its integrity seal (BACKLOG #5520): 423 when the record fails it, with nothing of the row answered. What the 423 reports, and when a row read mid-write is not refused: *What an admin user read reports* below this table | | `PUT` | `/users/{user_id}/federated-identity` | `users:manage` | `require_step_up_action` (action `admin_federated_identity`). Binds the account to an IdP `sub` under the configured `[auth].oidc_issuer`, or rebinds it; either one revokes every live session of the account, in the same transaction as the write (vault BACKLOG #2609). **The only path that creates a federated binding** (ADR 0184, BACKLOG #1143): a federated login never binds, and an unbound one is refused. Directory (AD) accounts only, and only one that carries its immutable directory id (`users.directory_object_id`, the `objectGUID`): 400 `directory_object_id_missing` otherwise, audited as `auth.federated_bind_refused` (BACKLOG #1143 slice C). A local account is refused 400 too, audited with reason `not_a_directory_account` (BACKLOG #3174). 409 when another account holds the identity, audited with reason `federated_subject_held` (BACKLOG #3174), and 409 `federated_binding_changed` when the account no longer holds the body's required `expected_issuer`/`expected_subject`, the pair the caller saw (BACKLOG #2026), also audited as `auth.federated_bind_refused`, with reason `federated_binding_changed`, the expected pair (BACKLOG #2331), and the pair the row held as `held_issuer`/`held_subject` wherever the refusal read it (BACKLOG #3174). 404 for an unknown user, including one deleted while the bind ran (BACKLOG #2331). A rebind is still a clear then a separate set: if another bind lands between them the rebind is refused 409 without that code, and its clear has already removed the old binding, audited as `auth.federated_subject_unbound`. The refusal itself is audited as `auth.federated_bind_refused` with reason `account_bound_concurrently`; that row and the `federated_subject_held` one carry `previous_binding_removed`, which says whether this request's clear had removed a binding first (BACKLOG #3174). **A bound account is refused Windows SSO from then on**, whether or not `oidc_enabled` is on (vault BACKLOG #2609; [Federated sign-in](#federated-sign-in-oidc-browser-only--adr-0142) has the limits) | | `DELETE` | `/users/{user_id}/federated-identity` | `users:manage` | `require_step_up_action` (action `admin_federated_identity`). Removes the binding and revokes the account's sessions (BACKLOG #1474's service method); its next federated login is refused until it is bound again. The body's required `expected_issuer`/`expected_subject` is the pair the caller saw: a stored pair that differs is refused 409 `federated_binding_changed` with nothing changed, compared under the clear's row lock (BACKLOG #2026). That refusal writes an `auth.federated_unbind_refused` audit row naming the actor, with reason `federated_binding_changed` and the expected pair (BACKLOG #2331) | @@ -1682,7 +1682,7 @@ tuple: they act only on the caller's own account. | `POST` | `/users/{user_id}/enrolment-code` | `users:manage` | `require_step_up_action` (action `admin_enrolment_code_issue`). Issues a directory account's single-use enrolment code, returned once and `no-store` ([Directory-account enrolment codes](#directory-account-enrolment-codes-adr-0207), ADR 0207). **Refuses (400) the caller's own account**, a local account, an account holding a factor and a disabled account; 404 for an unknown one | | `DELETE` | `/users/{user_id}/enrolment-code` | `users:manage` | `require_step_up_action` (action `admin_enrolment_code_revoke`). Clears an outstanding code; `revoked` says whether one was. Refuses (400) the caller's own account; 404 for an unknown one | | `GET` | `/users/{user_id}/channel-scope` | `users:manage` | `require` (a read on the `users:manage` tier, not `users:read`). The account is read with its record checked against its integrity seal (BACKLOG #5520): 423 when the record fails it, with nothing of the row answered. What the 423 reports, and when a row read mid-write is not refused: *What an admin user read reports* below this table; 404 for an unknown user | -| `PUT` | `/users/{user_id}/channel-scope` | `users:manage` | `require_step_up`; **refuses (400) when `user_id` is the caller's own** (BACKLOG #1149) | +| `PUT` | `/users/{user_id}/channel-scope` | `users:manage` | `require_step_up`; **refuses (400) when `user_id` is the caller's own** (BACKLOG #1149). The account is read with its record checked against its integrity seal (BACKLOG #5520): 423 when the record fails it, with nothing of the row answered. What the 423 reports, and when a row read mid-write is not refused: *What an admin user read reports* below this table; 404 for an unknown user | | `GET` | `/ad-group-map` | `users:manage` | `require` | | `PUT` | `/ad-group-map` | `users:manage` | `require_step_up_action` (action `save_ends_own_sessions`) **only when the save would end the caller's own sessions**, else the session window (BACKLOG #3401) | | `GET` | `/ad-group-scope-map` | `users:manage` | `require` | @@ -1690,7 +1690,9 @@ tuple: they act only on the caller's own account. **What an admin user read reports (BACKLOG #5520).** At least these read each account with its whole record checked against its integrity seal: `GET /users`, `GET /users/{user_id}/permissions`, -`PATCH /users/{user_id}`, `GET /users/{user_id}/federated-identity` and `GET /users/{user_id}/channel-scope`; +`PATCH /users/{user_id}`, `PUT /users/{user_id}/roles`, `POST /users/{user_id}/reset-password`, +`GET /users/{user_id}/federated-identity`, `GET /users/{user_id}/channel-scope` and +`PUT /users/{user_id}/channel-scope`; and in the web console (BACKLOG #5559) at least these. `GET /ui/users` answers 200 and lists a failing account by its id alone; to a caller holding `users:manage` it links that account's delete to `GET /ui/users/{user_id}/delete-confirm`, which, for a record its checked read refuses @@ -1735,7 +1737,9 @@ tampering, because the role rows are read apart from the account's row. Where after its gate has spent the single-use `admin_user_update` grant, so its 423 and its 404 cost that proof, as the console's `POST /ui/users/{user_id}/update` does after its own gate. So does its 422 for a changed display name the name rule refuses (BACKLOG #5784), which the route checks against -the stored name after that read. Where it is +the stored name after that read. `POST /users/{user_id}/reset-password` reads the account after +its gate has spent the single-use `admin_reset_password` grant, so its 423 and its 404 cost that +proof too. Where it is off, the gate checks the step-up session window instead and spends nothing, so none of these answers costs a proof. On a `vault_transit` store (ADR 0217), a record Vault transit cannot verify is answered the same way as a failing record, but reported under diff --git a/messagefoundry/api/auth_routes.py b/messagefoundry/api/auth_routes.py index eaf29244b2..9d380e2780 100644 --- a/messagefoundry/api/auth_routes.py +++ b/messagefoundry/api/auth_routes.py @@ -1807,19 +1807,18 @@ async def set_user_roles( # the body model. A body that fails ``RolesUpdateRequest`` is answered first, with no audit # row: FastAPI answers 422 on the JSON plane, and the console route that builds the model # renders "invalid input" with a 400. - user = await service.store.get_user(user_id) await _refuse_if_self( request, service, identity, user_id, - user, op="set_roles", detail="another administrator must change your own roles", ) await _validate_roles(service, body.roles) - if user is None: - raise HTTPException(status.HTTP_404_NOT_FOUND, "no such user") + # BACKLOG #5520 items 2 and 13: the route decides on the record, so it reads it checked: a + # record that fails its seal answers the reads' 423, not the write's own 409. + user = await _checked_user(service, user_id) if _externally_managed(user.auth_provider): raise HTTPException( status.HTTP_400_BAD_REQUEST, "AD users get roles from the AD-group map" @@ -1827,8 +1826,7 @@ async def set_user_roles( # BACKLOG #315: promotion mints an approver exactly as creation does, so it pages too. Only a # GRANT pages: re-saving an existing Administrator's roles changes nothing. granted = ( - Role.ADMINISTRATOR.value in body.roles - and Role.ADMINISTRATOR.value not in await service.store.get_user_role_ids(user_id) + Role.ADMINISTRATOR.value in body.roles and Role.ADMINISTRATOR.value not in user.role_ids ) try: # The last-administrator guard is inside, in one store transaction with the role write @@ -1877,6 +1875,9 @@ async def reset_user_password( op="password_reset", detail="use change-password for your own account", ) + # BACKLOG #5520 items 2 and 13: a record that fails its seal answers the reads' 423, not + # the service loader's 404. The service reads the account again before it writes. + await _checked_user(service, user_id) try: issued = await service.admin_reset_password(user_id, actor=identity.username) except ValueError as exc: @@ -2222,6 +2223,9 @@ async def set_channel_scope( ``ChannelScope`` is answered 422 by FastAPI before the guard runs, with no audit row; the console route runs the guard before its own checks (BACKLOG #3393).""" await _refuse_own_channel_scope(request, service, identity, user_id) + # BACKLOG #5520 items 2 and 13: as on the role write, a record that fails its seal answers + # the reads' 423, not the service loader's 404. The service reads it again to decide. + await _checked_user(service, user_id) try: await service.set_channel_scope( user_id, diff --git a/packaging/messagefoundry-webconsole/tests/test_ui_user_seal.py b/packaging/messagefoundry-webconsole/tests/test_ui_user_seal.py index e161a839d2..2c879246fa 100644 --- a/packaging/messagefoundry-webconsole/tests/test_ui_user_seal.py +++ b/packaging/messagefoundry-webconsole/tests/test_ui_user_seal.py @@ -21,7 +21,7 @@ import logging import sqlite3 -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Awaitable, Callable from pathlib import Path import pytest @@ -39,7 +39,7 @@ from messagefoundry.config.settings import AuthSettings, EgressSettings from messagefoundry.pipeline import Engine from messagefoundry.store.crypto import generate_key, make_cipher -from messagefoundry.store.store import MessageStore +from messagefoundry.store.store import MessageStore, VerifiedUser #: What the tampering writes. None of it may appear in an answer. _PLANTED = "planted-outside-the-store" @@ -92,6 +92,28 @@ async def _setup(engine: Engine) -> tuple[AuthService, list[str], str, str]: return service, alerts, intact, victim +def _fail_after_the_route_check( + service: AuthService, + monkeypatch: pytest.MonkeyPatch, + failing: Callable[[str], Awaitable[None]], +) -> None: + """Stand ``failing`` in for the service's checked reader after its first call, which is the + reset route's own checked read of the account (BACKLOG #5520 items 2 and 13), so the stand-in + fails only the name read of the page the landed reset renders.""" + real = service.checked_user + calls = 0 + + async def checked_user(user_id: str) -> VerifiedUser | None: + nonlocal calls + calls += 1 + if calls == 1: + return await real(user_id) + await failing(user_id) + return None + + monkeypatch.setattr(service, "checked_user", checked_user) + + async def _seal_failures(engine: Engine, user_id: str) -> int: rows = await engine.store.list_audit(action=AUTHORITY_SEAL_FAILED_ACTION, limit=10_000) return sum(1 for row in rows if user_id in str(row["detail"])) @@ -278,7 +300,7 @@ async def test_a_page_after_a_landed_action_names_the_account_only_from_a_checke one-time credential names the account. That name is read through the checked read; on a refusal ``_shown_name`` takes (its docstring states which), the page names the id and the credential is still shown, since it was issued. The failure is stood in for at the service's - checked reader, after the reset's own read.""" + checked reader, after the reset's own reads.""" engine, _path = keyed caplog.set_level(logging.DEBUG, logger="messagefoundry_webconsole.routes.admin") service, _alerts, intact, victim = await _setup(engine) @@ -292,7 +314,7 @@ async def test_a_page_after_a_landed_action_names_the_account_only_from_a_checke async def failing(user_id: str) -> None: raise failure - monkeypatch.setattr(service, "checked_user", failing) + _fail_after_the_route_check(service, monkeypatch, failing) path = f"/ui/users/{victim}/reset-password" await mint_bound_proof(c, path) r = await c.post(path, headers=SAME_ORIGIN) @@ -349,7 +371,7 @@ async def failing(user_id: str) -> None: async with _client(engine, service) as c: await cookie_login(c, "root") - monkeypatch.setattr(service, "checked_user", failing) + _fail_after_the_route_check(service, monkeypatch, failing) path = f"/ui/users/{victim}/reset-password" await mint_bound_proof(c, path) r = await c.post(path, headers=SAME_ORIGIN) diff --git a/tests/test_console_seam_inventory.py b/tests/test_console_seam_inventory.py index 1698d24162..193190087a 100644 --- a/tests/test_console_seam_inventory.py +++ b/tests/test_console_seam_inventory.py @@ -513,6 +513,10 @@ def _core(*ops: str) -> Field: "GET /users/{user_id}/channel-scope", "GET /users/{user_id}/permissions", "PATCH /users/{user_id}", + # BACKLOG #5520 items 2 and 13: the writes that decide on the record read it checked. + "PUT /users/{user_id}/roles", + "PUT /users/{user_id}/channel-scope", + "POST /users/{user_id}/reset-password", ), ), "admin.list_custom_roles": _endpoint("GET /roles/custom"), diff --git a/tests/test_unreadable_user_raw_callers.py b/tests/test_unreadable_user_raw_callers.py index 0aa7975943..62b439265b 100644 --- a/tests/test_unreadable_user_raw_callers.py +++ b/tests/test_unreadable_user_raw_callers.py @@ -102,7 +102,8 @@ async def test_a_role_change_on_an_unreadable_account_is_refused_before_any_writ engine_at: tuple[Engine, Path], monkeypatch: pytest.MonkeyPatch, provider: str ) -> None: """The stand-in's ``auth_provider`` is invented, so a corrupt directory account must not be - read as local: the route refuses on the read, before the AD check or the role write runs.""" + read as local: the route refuses on the read, before the AD check or the role write runs. The + read is the checked one (BACKLOG #5520 items 2 and 13), so the refusal is its 423.""" engine, path = engine_at service = await _auth_service(engine) await _auth_add(service, "root", Role.ADMINISTRATOR) @@ -118,7 +119,7 @@ async def test_a_role_change_on_an_unreadable_account_is_refused_before_any_writ async with _auth_client(engine, service) as c: h = _auth((await _login(c, "root")).json()["token"]) r = await c.put(f"/users/{_TARGET}/roles", headers=h, json={"roles": ["operator"]}) - assert r.status_code == 409, r.text + assert r.status_code == 423, r.text assert "integrity" in r.json()["detail"] assert calls == [] diff --git a/tests/test_user_seal_routes.py b/tests/test_user_seal_routes.py index ccee7b6f1b..4bb34dce78 100644 --- a/tests/test_user_seal_routes.py +++ b/tests/test_user_seal_routes.py @@ -180,6 +180,51 @@ async def test_patch_answers_423_for_a_failing_record(keyed: tuple[Engine, Path] assert await _seal_failures(engine, victim) >= 1 +#: The admin writes that decide on the account's record before they write (#5520 items 2 and 13): +#: (method, path suffix, JSON body, step-up action or None for the session window). +_CHECKED_WRITES = { + "roles": ("PUT", "roles", {"roles": [Role.VIEWER.value]}, None), + "channel-scope": ("PUT", "channel-scope", {"channels": ["*"]}, None), + "reset-password": ("POST", "reset-password", None, "admin_reset_password"), +} + + +@pytest.mark.parametrize("name", sorted(_CHECKED_WRITES)) +async def test_an_admin_write_answers_423_for_a_failing_record( + keyed: tuple[Engine, Path], name: str +) -> None: + """#5520 items 2 and 13: ``PUT /users/{id}/roles``, ``PUT /users/{id}/channel-scope`` and + ``POST /users/{id}/reset-password`` read the account through the checked read, so a record + that fails its seal answers the 423 the reads answer, reported, rather than a 409 from the + write's own seal check or a 404 from the service's loader. Controls: an unknown id is still a + 404, and an intact account is written.""" + method, suffix, body, action = _CHECKED_WRITES[name] + engine, path = keyed + service, alerts, intact, victim = await _setup(engine) + await _tamper(path, victim) + + async with _client(engine, service) as c: + token = (await _login(c, "root")).json()["token"] + + async def send(user_id: str) -> httpx.Response: + nonlocal token + _, token = await _reauth(c, token, purpose=action) + return await c.request( + method, f"/users/{user_id}/{suffix}", json=body, headers=_auth(token) + ) + + refused = await send(victim) + absent = await send(ABSENT_USER_ID) + served = await send(intact) + assert refused.status_code == 423, refused.text + assert refused.json()["detail"] == USER_SEAL_REFUSED + assert _PLANTED not in refused.text + assert await _seal_failures(engine, victim) >= 1 + assert any(victim in alert for alert in alerts) + assert absent.status_code == 404, absent.text + assert served.status_code == 200, served.text + + async def test_checked_user_tells_a_failing_record_from_a_missing_one( keyed: tuple[Engine, Path], ) -> None: @@ -479,11 +524,12 @@ def test_the_security_doc_states_what_a_423_reports_and_costs() -> None: "Each engine process sharing the store keeps its own interval", "Where `[auth].require_action_step_up` is on, the default", "the single-use `admin_user_update` grant, so its 423 and its 404 cost that proof", + "the single-use `admin_reset_password` grant, so its 423 and its 404 cost that proof", "Where it is off, the gate checks the step-up session window instead and spends nothing", ): assert fact in body, fact rows = [line for line in text.splitlines() if line.startswith("|") and "#5520" in line] - assert len(rows) == 5, rows + assert len(rows) == 8, rows for row in rows: assert "*What an admin user read reports* below this table" in row, row assert "audit row and alert" not in row and "audited and alerted" not in row, row From 8b66888200dd5ccbc398596ceab88f0145234b5b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:18:09 -0600 Subject: [PATCH 02/12] Username rule refuses a reserved form spelled with a lookalike colon or angle bracket username_refusal now matches RESERVED_ACTOR_FORMS after NFKC with the delimiter lookalikes _DELIMITER_LOOKALIKES lists (RATIO, modifier colons, angle quotation marks, CJK and mathematical angle brackets, modifier arrowheads and others from Unicode's confusables data) taken to ASCII, so "cli" + RATIO + "root" and "" in angle quotation marks are refused as their ASCII forms are. Cross-script letter lookalikes still pass, as the module states. Tests: the lookalike forms are refused by the rule and the request model, with controls; a pin that "" (DIRECTORY_GRANTED_BY) is refused and the bare word is not; and a census that every literal audit actor in the engine package is a reserved form. Prose: usernames.py names at least the paths that skip the rule, the directory rename refresh among them, and says "" is reserved; the DIRECTORY_GRANTED_BY comment names the reconciler's alert and points at usernames.py rather than restating which routes apply the rule; the POST /users row of docs/SECURITY.md points there too. BACKLOG #5520 items 3, 14, 34, 35, 36, 37, 40, 41 and 42. --- docs/SECURITY.md | 2 +- messagefoundry/api/security.py | 12 ++-- messagefoundry/auth/usernames.py | 42 ++++++++++++-- tests/test_username_rule.py | 99 +++++++++++++++++++++++++++++++- 4 files changed, 142 insertions(+), 13 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 17f58590af..f2b249d01d 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1667,7 +1667,7 @@ tuple: they act only on the caller's own account. | `DELETE` | `/roles/custom/{role_id}` | `users:manage` | `require_step_up_action` (action `save_ends_own_sessions`) **only when the save would end the caller's own sessions**, else the session window (BACKLOG #3401) | | `GET` | `/users` | `users:read` | `require`. Each account's record is checked against its integrity seal (BACKLOG #5520); one that fails is listed by its `id` alone, with `integrity_failed: true` (`IntegrityFailedUser`). What that reports: *What an admin user read reports* below this table | | `GET` | `/users/{user_id}/permissions` | `users:read` | `require` — the effective-permission inspector. The account is read with its record checked against its integrity seal (BACKLOG #5520): 423 when the record fails it, with nothing of the row answered. What the 423 reports, and when a row read mid-write is not refused: *What an admin user read reports* below this table; 404 for an unknown user | -| `POST` | `/users` | `users:manage` | `require_step_up`. Refuses (422) a `username` the new-username rule refuses, before anything is generated or written (BACKLOG #5521). The rule, and what it admits, is stated once, in the docstring of `messagefoundry/auth/usernames.py`; the service refuses the same name 400 for a caller that skips the request model. `provision-admin`, `POST /users/directory` and an AD sign-in that creates its account do not apply this rule | +| `POST` | `/users` | `users:manage` | `require_step_up`. Refuses (422) a `username` the new-username rule refuses, before anything is generated or written (BACKLOG #5521). The rule, and what it admits, is stated once, in the docstring of `messagefoundry/auth/usernames.py`; the service refuses the same name 400 for a caller that skips the request model. Which other paths write a username without this rule is stated there too (BACKLOG #5520 item 34) | | `POST` | `/users/directory` | `users:manage` | `require_step_up`. Creates a directory (AD) account's mirror row by name, without a sign-in (BACKLOG #2021). The row's `objectGUID`, display name and `mail` come from a service-account directory lookup, never from the request: the body carries `username` and an optional `notify_email`, and an unknown key is refused 422. The row is never born without a notification address: the directory's `mail` is it when BACKLOG #2014's rule adopts it, and `notify_email` is then refused; otherwise `notify_email` is required and checked as `POST /users` checks `email` (400). 404 when the directory has no enabled account by that name, 400 when it returns no readable `objectGUID`, 409 when a row already holds the name or id, 503 when the directory cannot be reached. No roles: they come from the AD-group map at sign-in | | `PATCH` | `/users/{user_id}` | `users:manage` | `require_step_up_action` (action `admin_user_update`). The account is read with its record checked against its integrity seal (BACKLOG #5520): 423 when the record fails it, with nothing of the row answered. What the 423 reports, and when a row read mid-write is not refused: *What an admin user read reports* below this table; 404 for an unknown user | | `DELETE` | `/users/{user_id}` | `users:manage` | `require_step_up` | diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 45d12d14d6..6879b83415 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -77,11 +77,13 @@ def alert_sink_for(state: Any) -> AlertSink: return sink if sink is not None else _FALLBACK_ALERT_SINK -#: ``granted_by`` on the ``administrator_granted`` alert a directory sign-in raises (vault BACKLOG -#: #2610): no administrator acted, the directory's group membership did. It is a fixed marker, styled -#: like the ```` audit actor. ``POST /users`` refuses the name (``auth/usernames.py``), but -#: provision-admin and the directory create paths do not, so an account literally named -#: ```` could read the same in this field; the alert's ``via`` names the route either way. +#: ``granted_by`` on the ``administrator_granted`` alert raised when the directory, not an +#: administrator, grants Administrator: a directory sign-in (vault BACKLOG #2610) and the directory +#: reconciler (``via=directory_reconcile``). It is a fixed marker, styled like the ```` +#: audit actor. The new-username rule's ``<...>`` form covers it; which paths apply that rule, and +#: what the rule still admits, ``auth/usernames.py`` states. An account named so by a path that skips +#: the rule, or spelled to render the same, could read the same in this field; the alert's ``via`` +#: names the route either way. DIRECTORY_GRANTED_BY = "" diff --git a/messagefoundry/auth/usernames.py b/messagefoundry/auth/usernames.py index 97ee288dab..f3a72fa747 100644 --- a/messagefoundry/auth/usernames.py +++ b/messagefoundry/auth/usernames.py @@ -5,8 +5,11 @@ It imports only the standard library and the engine-free ``controlchars`` leaf, so the request model ``api.auth_models.UserCreateRequest`` can apply the same rule the service does without importing the service. ``AuthService.create_local_user`` checks it before anything is generated or -written, and the model mirrors it. It is not applied by ``provision-admin`` or by the directory -create paths. +written, and the model mirrors it, so at least ``POST /users`` and the console's ``POST +/ui/users`` refuse a name it refuses. Paths that write a username without it include at least +``provision-admin``, the directory create paths (``POST /users/directory`` and an AD sign-in that +creates its account) and the directory rename refresh (``AuthService._refresh_cached_username``), +so an account one of them writes can hold a name this rule refuses. A name is refused when it is blank or white space alone, when it starts or ends with white space (refused rather than trimmed, so the duplicate check and the stored value are the same string), @@ -20,12 +23,16 @@ and in an audit export. The NUL case is pinned by ``tests/test_username_rule.py::test_the_rule_refuses``. -The ``directory`` name is NOT reserved: nothing at HEAD writes it as an audit actor. +The bare word ``directory`` is NOT reserved: nothing at HEAD writes it as an audit actor. The +directory sign-in's marker ```` (``api.security.DIRECTORY_GRANTED_BY``) is, by the +``<...>`` form. What it admits, at least: a space separator inside the name (U+00A0, U+3000), a blank glyph :data:`_BLANK_GLYPHS` does not list, and a lookalike letter from another script, so a Cyrillic -spelling that reads as ``system`` passes. It matches the reserved forms after NFKC and case -folding; it does not fold confusable letters across scripts. +spelling that reads as ``system`` passes, as does a reserved form spelled with a delimiter +lookalike :data:`_DELIMITER_LOOKALIKES` does not list. It matches the reserved forms after NFKC, +with the delimiter lookalikes that table lists taken to ASCII, and case folding; it does not fold +confusable letters across scripts. This docstring is the one statement of the rule; the request model, the service and docs/SECURITY.md point here rather than restate it. @@ -48,6 +55,29 @@ #: new synthetic actor form must be added here too. RESERVED_ACTOR_FORMS: Final = re.compile(r"(?s)system(:.*)?|cli:.*|<.*>") +#: Lookalikes of the delimiters :data:`RESERVED_ACTOR_FORMS` reads that NFKC leaves as they are, +#: each taken to the ASCII character it renders as before the reserved-form match (BACKLOG #5520 +#: items 3, 14 and 35), so ``cli`` + RATIO + ``root`` or ```` in angle quotation marks is +#: refused as ``cli:root`` and ```` are. Code points taken from Unicode's confusables data +#: for ``:``, ``<`` and ``>``, and not every lookalike of them. Applied after NFKC, which takes +#: U+2329 and U+232A to U+3008 and U+3009. +_DELIMITER_LOOKALIKES: Final = str.maketrans( + dict.fromkeys( + (0x02D0, 0x02F8, 0x0589, 0x05C3, 0x0703, 0x0704, 0x16EC, 0x1803, 0x1809, 0x205A) + + (0x2236, 0xA4FD, 0xA789), + ":", + ) + | dict.fromkeys((0x02C2, 0x1438, 0x16B2, 0x2039, 0x276C, 0x276E, 0x27E8, 0x3008), "<") + | dict.fromkeys((0x02C3, 0x1433, 0x203A, 0x276D, 0x276F, 0x27E9, 0x3009), ">") +) + + +def _reserved_form_key(username: str) -> str: + """What :data:`RESERVED_ACTOR_FORMS` is matched against: the name's NFKC form, its + :data:`_DELIMITER_LOOKALIKES` taken to ASCII, case folded.""" + return unicodedata.normalize("NFKC", username).translate(_DELIMITER_LOOKALIKES).casefold() + + #: Unicode's Default_Ignorable_Code_Point ranges (DerivedCoreProperties.txt), inclusive. Most are #: format characters :data:`CONTROL_CATEGORIES` already refuses; the rest render as nothing from #: other categories, at least the combining grapheme joiner U+034F, the variation selectors and the @@ -123,7 +153,7 @@ def username_refusal(username: str) -> str | None: ) if username != stripped: return "a username must not start or end with white space" - if RESERVED_ACTOR_FORMS.fullmatch(unicodedata.normalize("NFKC", username).casefold()): + if RESERVED_ACTOR_FORMS.fullmatch(_reserved_form_key(username)): return ( "that username is reserved for the audit trail's own actors " '("system", "system:...", "cli:..." and "<...>")' diff --git a/tests/test_username_rule.py b/tests/test_username_rule.py index a36d986337..6315156636 100644 --- a/tests/test_username_rule.py +++ b/tests/test_username_rule.py @@ -11,6 +11,7 @@ from __future__ import annotations +import ast from collections.abc import AsyncIterator from pathlib import Path from types import SimpleNamespace @@ -23,9 +24,10 @@ from messagefoundry.api import create_app from messagefoundry.api.auth_models import UserCreateRequest +from messagefoundry.api.security import DIRECTORY_GRANTED_BY from messagefoundry.auth import Role from messagefoundry.auth.service import InvalidUsername -from messagefoundry.auth.usernames import username_refusal +from messagefoundry.auth.usernames import RESERVED_ACTOR_FORMS, username_refusal from messagefoundry.config.settings import EgressSettings from messagefoundry.pipeline import Engine from tests.test_api_auth import _add, _auth, _login, _reauth, _service @@ -78,6 +80,24 @@ "\u2800bob", "\U0001d159", "bob\U00016fe4", + # BACKLOG #5520 item 37: the directory sign-in's synthetic granted_by marker, + # api.security.DIRECTORY_GRANTED_BY, which the "<...>" form refuses. + "", +] + +#: BACKLOG #5520 items 3, 14 and 35: reserved forms spelled with a lookalike of their colon or +#: angle brackets that NFKC leaves as it is. Each renders as a reserved form, so each is refused. +LOOKALIKE_DELIMITERS = [ + "cli\u2236root", # RATIO + "cli\ua789root", # MODIFIER LETTER COLON + "system\u02f8rotate-key", # MODIFIER LETTER RAISED COLON + "SYSTEM\u2236x", + "\u2039oidc\u203a", # SINGLE LEFT/RIGHT-POINTING ANGLE QUOTATION MARK + "\u3008kerberos\u3009", # LEFT/RIGHT ANGLE BRACKET (CJK) + "\u2329reconciler\u232a", # LEFT/RIGHT-POINTING ANGLE BRACKET, which NFKC takes to U+3008/9 + "\u02c2directory\u02c3", # MODIFIER LETTER LEFT/RIGHT ARROWHEAD + "\u27e8oidc\u27e9", # MATHEMATICAL LEFT/RIGHT ANGLE BRACKET + "\u2039oidc>", ] #: The controls: names beside each refused form that the rule must leave alone. @@ -98,6 +118,10 @@ "sysadmin", # What the module docstring says the rule admits: a space separator inside the name. "a\u3000b", + # Controls for LOOKALIKE_DELIMITERS: a lookalike delimiter outside a reserved form. + "sys\u2236tem", + "\u2039bob", + "bob\u203a", ] @@ -111,6 +135,79 @@ def test_the_rule_accepts(name: str) -> None: assert username_refusal(name) is None +@pytest.mark.parametrize("name", LOOKALIKE_DELIMITERS) +def test_the_rule_refuses_a_reserved_form_with_a_lookalike_delimiter(name: str) -> None: + """BACKLOG #5520 items 3, 14 and 35. The controls are ACCEPTED's lookalikes outside a form.""" + assert username_refusal(name) is not None + with pytest.raises(ValidationError): + UserCreateRequest(username=name, email="x@example.test", roles=[]) + + +def test_the_directory_marker_is_a_reserved_form() -> None: + """BACKLOG #5520 item 37: the comment on DIRECTORY_GRANTED_BY says the rule refuses it.""" + assert DIRECTORY_GRANTED_BY in REFUSED + assert username_refusal(DIRECTORY_GRANTED_BY) is not None + # Control: the bare word is not reserved, as the module docstring says. + assert username_refusal("directory") is None + + +def _literal_actors() -> list[tuple[str, str]]: + """Every synthetic audit actor the engine package spells as a literal: a constant, or the + constant head of an f-string, passed as an ``actor=`` keyword or as an ``actor`` parameter's + default, and the module constants named ``*_ACTOR`` or ``*_GRANTED_BY``.""" + root = Path(__file__).resolve().parents[1] / "messagefoundry" + found: list[tuple[str, str]] = [] + + def text(node: ast.expr | None) -> str | None: + if isinstance(node, ast.Constant) and isinstance(node.value, str): + return node.value + if isinstance(node, ast.JoinedStr) and node.values: + return text(node.values[0]) + return None + + for path in sorted(root.rglob("*.py")): + where = path.relative_to(root.parent).as_posix() + for node in ast.walk(ast.parse(path.read_text("utf-8"))): + values: list[ast.expr | None] = [] + if isinstance(node, ast.Call): + values += [kw.value for kw in node.keywords if kw.arg == "actor"] + elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef): + positional = node.args.posonlyargs + node.args.args + with_default = positional[len(positional) - len(node.args.defaults) :] + pairs: list[tuple[ast.arg, ast.expr | None]] = list( + zip(with_default, node.args.defaults, strict=True) + ) + pairs += zip(node.args.kwonlyargs, node.args.kw_defaults, strict=True) + values += [default for arg, default in pairs if arg.arg == "actor"] + elif isinstance(node, ast.Assign | ast.AnnAssign): + targets = node.targets if isinstance(node, ast.Assign) else [node.target] + if any( + isinstance(t, ast.Name) and t.id.endswith(("_ACTOR", "_GRANTED_BY")) + for t in targets + ): + values.append(node.value) + for value in values: + literal = text(value) + if literal is not None: + found.append((where, literal)) + return found + + +def test_every_literal_audit_actor_is_a_reserved_form() -> None: + """BACKLOG #5520 item 3: a census for RESERVED_ACTOR_FORMS. Each synthetic actor the engine + package spells as a literal where ``_literal_actors`` looks must be a form the rule refuses, so + a new literal actor form there fails here until it is added to the rule. An actor built at run + time, or passed under another name, is not seen. The positive control: the census finds the + forms the rule's comment names.""" + actors = _literal_actors() + literals = {literal for _, literal in actors} + for expected in ("system", "system:rotate-key", "", "", "", "cli:"): + assert expected in literals, (expected, sorted(literals)) + assert DIRECTORY_GRANTED_BY in literals + unreserved = [(where, lit) for where, lit in actors if not RESERVED_ACTOR_FORMS.fullmatch(lit)] + assert not unreserved, unreserved + + @pytest.mark.parametrize("name", REFUSED) def test_the_request_model_mirrors_the_rule(name: str) -> None: with pytest.raises(ValidationError): From e42da356136e804ec46968f66677b762be59a1a0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:24:35 -0600 Subject: [PATCH 03/12] Console create form shows the username rule's reason; two over-long docstring lines wrapped POST /ui/users now shows the new-username rule's own fixed reason (username_refusal) when the request model refuses the name, rather than "invalid input" for every refusal; a refusal of another field keeps "invalid input". The reason never echoes the value. The UserSealRefused and checked_user docstrings are wrapped to the 100-column line length. BACKLOG #5520 items 7, 16 and 18 (item 7's strip-before-validation limb is not changed). --- messagefoundry/auth/service.py | 20 ++++++++------- messagefoundry_webconsole/routes/admin.py | 5 ++++ .../tests/test_webui_users.py | 25 +++++++++++++++++++ 3 files changed, 41 insertions(+), 9 deletions(-) diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index b64c55f394..2c7d33a038 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -2285,13 +2285,14 @@ class UserSealRefused(RuntimeError): seal (BACKLOG #5520). :meth:`AuthService.change_password` raises it too, from that read or from the store write's own seal refusal, each reported the same way, and ``POST /me/password`` answers it 423 (BACKLOG #5902). The failure was handed to the seal-failure report, which - writes the audit row and raises the alert only for the first failure of the account in each report interval - (:data:`~messagefoundry.store.row_seal.SEAL_FAILURE_REPORT_INTERVAL_SECONDS`) of this - service's process, so a refusal inside that interval adds no row. Not "no such user": the row is there, and an administrator - may still delete it. ``auth_routes._checked_user``, and so the JSON admin routes that read an - account through it, answer it 423; docs/SECURITY.md, *What an admin user read reports*, states - what at least some web console pages answer. A record Vault transit cannot verify is - refused the same way, reported under ``integrity.authority_seal_unverifiable`` (ADR 0217).""" + writes the audit row and raises the alert only for the first failure of the account in each + report interval (:data:`~messagefoundry.store.row_seal.SEAL_FAILURE_REPORT_INTERVAL_SECONDS`) + of this service's process, so a refusal inside that interval adds no row. Not "no such user": + the row is there, and an administrator may still delete it. ``auth_routes._checked_user``, and + so the JSON admin routes that read an account through it, answer it 423; docs/SECURITY.md, + *What an admin user read reports*, states what at least some web console pages answer. A + record Vault transit cannot verify is refused the same way, reported under + ``integrity.authority_seal_unverifiable`` (ADR 0217).""" async def read_user_or_unreadable(read: Awaitable[UserRecord | None]) -> UserRecord | None: @@ -13467,8 +13468,9 @@ async def _load_users(self) -> list[VerifiedUser]: async def checked_user(self, user_id: str) -> VerifiedUser | None: """The account ``user_id`` names, its whole record checked against its seal, for a caller outside this service that SHOWS it (BACKLOG #5520), and for :meth:`change_password`, which - decides on it (BACKLOG #5902), so its raise-or-``None`` contract binds that control too. ``None`` when no row is there. Raises - :class:`UserSealRefused` only when :meth:`_verified` established that the record fails, + decides on it (BACKLOG #5902), so its raise-or-``None`` contract binds that control too. + ``None`` when no row is there. Raises :class:`UserSealRefused` only when + :meth:`_verified` established that the record fails, or :meth:`_checked_by_id` failed closed, and handed that to the seal-failure report, so the caller can say so rather than answer "no such user". A record Vault transit cannot verify raises it too, reported under its own cause (ADR 0217 (a)). A Vault transit Outage diff --git a/messagefoundry_webconsole/routes/admin.py b/messagefoundry_webconsole/routes/admin.py index 5a5d6a83c1..d37afd6d37 100644 --- a/messagefoundry_webconsole/routes/admin.py +++ b/messagefoundry_webconsole/routes/admin.py @@ -53,6 +53,7 @@ STEP_UP_ACTION_SAVE_ENDS_OWN_SESSIONS, AuthService, ) +from messagefoundry.auth.usernames import username_refusal from messagefoundry.controlchars import scrub_log_argument from .. import pages @@ -450,6 +451,10 @@ async def ui_user_create( ) except (ValidationError, HTTPException) as exc: detail = "invalid input" if isinstance(exc, ValidationError) else str(exc.detail) + if isinstance(exc, ValidationError): + # BACKLOG #5520 items 7 and 16: the username rule's reason is fixed text that never + # echoes the value, so the form can say why; any other field keeps "invalid input". + detail = username_refusal(form.get("username", "").strip()) or detail all_roles = await admin.list_roles(service=service, _=identity) return HTMLResponse( pages.user_new_page( diff --git a/packaging/messagefoundry-webconsole/tests/test_webui_users.py b/packaging/messagefoundry-webconsole/tests/test_webui_users.py index 9e50f451a4..2b26422a7b 100644 --- a/packaging/messagefoundry-webconsole/tests/test_webui_users.py +++ b/packaging/messagefoundry-webconsole/tests/test_webui_users.py @@ -284,6 +284,31 @@ async def test_the_console_create_refuses_a_reserved_or_control_username(engine: assert ok.status_code == 200 and "Account created" in ok.text +async def test_the_console_create_shows_why_the_username_rule_refused(engine: Engine) -> None: + """BACKLOG #5520 items 7 and 16: the form shows the rule's own fixed reason rather than + "invalid input" for every refused name. A refusal of another field keeps "invalid input" + (control), since only the username rule's reasons are known to carry no input.""" + service = await _service(engine) + async with _boss_client(engine, service) as c: + reserved = await _post_pairs( + c, "/ui/users", [("username", "system"), ("email", "x@example.test")] + ) + control = await _post_pairs( + c, "/ui/users", [("username", "a\x07b"), ("email", "x@example.test")] + ) + other = await _post_pairs( + c, + "/ui/users", + [("username", "fine"), ("email", "x@example.test"), ("display_name", "x" * 10_000)], + ) + assert reserved.status_code == 400 + assert "reserved for the audit trail" in html.unescape(reserved.text) + assert "invalid input" not in reserved.text + assert control.status_code == 400 + assert "control, format, invisible or line separator" in html.unescape(control.text) + assert other.status_code == 400 and "invalid input" in other.text + + async def test_create_user_duplicate_rerenders_without_password(engine: Engine) -> None: service = await _service(engine) await _add(service, "op", Role.OPERATOR) From 702619dd3bc4b4dbfec3a1e3cef843724484cc12 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:30:17 -0600 Subject: [PATCH 04/12] Upload gate skips leading white space and a BOM without copying the body _lstrip_bom_ws used bytes.lstrip, which copies the rest of the body when anything is stripped, so an upload that began with one space or a BOM cost nontext_upload_reason a second copy of the whole body. It now finds the first byte past the noise with a regex search and returns only a 16-byte head; every caller compares a signature at its start, so what the container gate and the content sniffs admit is unchanged (pinned by the new tests' controls). BACKLOG #5520, filing review finding 3 (the whole-body lstrip limb; the shared-executor limb is not built). --- messagefoundry/parsing/sniff.py | 23 ++++++++-- tests/test_sniff_head_copy.py | 76 +++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 4 deletions(-) create mode 100644 tests/test_sniff_head_copy.py diff --git a/messagefoundry/parsing/sniff.py b/messagefoundry/parsing/sniff.py index dcdeddcf99..4a60fbcec4 100644 --- a/messagefoundry/parsing/sniff.py +++ b/messagefoundry/parsing/sniff.py @@ -34,6 +34,7 @@ import base64 import binascii import ntpath +import re from messagefoundry.content_type import ContentType from messagefoundry.controlchars import has_control_char @@ -65,11 +66,25 @@ def _looks_like_hl7(raw: bytes) -> bool: _LEADING_WS = b" \t\r\n\x0b\x0c" +#: The first byte that is not :data:`_LEADING_WS`, found in C without copying the body. +_PAST_LEADING_WS = re.compile(b"[^" + re.escape(_LEADING_WS) + b"]") + +#: How much of the body past the leading noise :func:`_lstrip_bom_ws` returns: more than the +#: longest signature any caller compares (the 8-byte PNG magic). +_SNIFF_HEAD_BYTES = 16 + + def _lstrip_bom_ws(raw: bytes) -> bytes: - head = raw.lstrip(_LEADING_WS) - if head.startswith(b"\xef\xbb\xbf"): # UTF-8 BOM - head = head[3:].lstrip(_LEADING_WS) - return head + """The first :data:`_SNIFF_HEAD_BYTES` of ``raw`` past leading :data:`_LEADING_WS` and one + UTF-8 BOM (with white space either side of it). Only that head is copied, so a large body with + leading noise is not copied whole (BACKLOG #5520, filing review finding 3); every caller compares + a signature at its start.""" + found = _PAST_LEADING_WS.search(raw) + at = len(raw) if found is None else found.start() + if raw.startswith(b"\xef\xbb\xbf", at): # UTF-8 BOM + found = _PAST_LEADING_WS.search(raw, at + 3) + at = len(raw) if found is None else found.start() + return raw[at : at + _SNIFF_HEAD_BYTES] #: The str-domain twin of :data:`_LEADING_WS`, plus U+FEFF (what a UTF-8/UTF-16 BOM decodes to). Derived diff --git a/tests/test_sniff_head_copy.py b/tests/test_sniff_head_copy.py new file mode 100644 index 0000000000..8efcd450ef --- /dev/null +++ b/tests/test_sniff_head_copy.py @@ -0,0 +1,76 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""BACKLOG #5520, filing review finding 3: the upload gate's leading-noise skip copies a bounded +head, not the body. + +``nontext_upload_reason`` reads past leading white space and a UTF-8 BOM before it compares a +container's magic bytes. It did that with ``bytes.lstrip``, which copies the rest of the body when +anything is stripped, so a body that starts with one space cost a second copy of itself. The skip +now finds the first byte past the noise in place and copies only a short head. Each test has a +control: the same body with no leading noise, which never copied, and the refusals the skip feeds. +""" + +from __future__ import annotations + +import tracemalloc + +import pytest + +from messagefoundry.content_type import ContentType +from messagefoundry.parsing.sniff import _content_matches_declared, nontext_upload_reason + +_SIZE = 4 * 1024 * 1024 + + +def _peak(body: bytes) -> int: + tracemalloc.start() + try: + tracemalloc.reset_peak() + assert nontext_upload_reason(body) is None + return tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + + +@pytest.mark.parametrize("noise", [b" ", b"\r\n", b"\xef\xbb\xbf", b" \xef\xbb\xbf\t"]) +def test_leading_noise_does_not_copy_the_body(noise: bytes) -> None: + body = noise + b"MSH|" + b"a" * _SIZE + clean = b"MSH|" + b"a" * _SIZE + # Control: a body with nothing to skip. + assert _peak(clean) < _SIZE // 8 + assert _peak(body) < _SIZE // 8 + + +@pytest.mark.parametrize( + "body", + [ + b"%PDF-1.7 rest", + b" \r\n%PDF-1.7 rest", + b"\xef\xbb\xbf%PDF-1.7", + b" \xef\xbb\xbf \x89PNG\r\n\x1a\n...", + b"\n" * 100_000 + b"PK\x03\x04", + ], +) +def test_a_container_behind_leading_noise_is_still_refused(body: bytes) -> None: + reason = nontext_upload_reason(body) + assert reason is not None and "container" in reason + + +@pytest.mark.parametrize( + ("content_type", "body", "agrees"), + [ + (ContentType.XML, b"\n\n ", True), + (ContentType.XML, b"\xef\xbb\xbf ", True), + (ContentType.XML, b" x", False), + (ContentType.JSON, b"\t\r\n{}", True), + (ContentType.JSON, b" \xef\xbb\xbf[1]", True), + (ContentType.JSON, b" ", False), + (ContentType.X12, b"\x0b\x0cISA*00", True), + (ContentType.X12, b"ISX", False), + ], +) +def test_the_content_sniffs_read_the_same_head( + content_type: ContentType, body: bytes, agrees: bool +) -> None: + """The format sniffs share the skip: what they admit is unchanged.""" + assert _content_matches_declared(content_type, body) is agrees From 1fdfdd5336102d08b319138712e11df93e76fc98 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:33:22 -0600 Subject: [PATCH 05/12] apiclient: pin list_users decoding both shapes of the GET /users union A test-only pin: a GET /users reply mixing a UserSummary row and an IntegrityFailedUser row decodes each to its own shape, the failed row to its id and flag alone. BACKLOG #5520 item 10 (the apiclient union-test limb). --- tests/test_apiclient.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/test_apiclient.py b/tests/test_apiclient.py index 375c972b01..c84a7d9738 100644 --- a/tests/test_apiclient.py +++ b/tests/test_apiclient.py @@ -178,6 +178,30 @@ def test_list_readers_still_decode_a_well_formed_reply( assert result.total == 0 +def test_list_users_decodes_both_shapes_of_the_union() -> None: + """BACKLOG #5520 item 10: ``GET /users`` answers a list mixing full summaries and accounts + listed by id alone (``IntegrityFailedUser``); the client decodes each row to its own shape and + keeps nothing of a failed row but its id.""" + from messagefoundry.api.auth_models import IntegrityFailedUser, UserSummary + + rows = [ + { + "id": "a" * 32, + "username": "intact", + "auth_provider": "local", + "disabled": False, + "roles": ["viewer"], + "channel_scope_withheld": True, + }, + {"id": "b" * 32, "integrity_failed": True}, + ] + with _client_answering(json.dumps(rows).encode()) as client: + listed = client.list_users() + assert isinstance(listed[0], UserSummary) and listed[0].username == "intact" + assert isinstance(listed[1], IntegrityFailedUser) + assert listed[1].model_dump() == {"id": "b" * 32, "integrity_failed": True} + + @pytest.mark.parametrize( "content", [ From 44c33df89004dfac9c892dca7c7cfca5f7a914cc Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:37:35 -0600 Subject: [PATCH 06/12] test_user_seal: drop set_user_roles from the raw-read list; name reads without walk order set_user_roles now reads the account checked (BACKLOG #5520 items 2 and 13), so the route scan's allowed raw reads no longer list it, and the scan's liveness check would otherwise fail. _reader_calls now carries the innermost function down the tree instead of relying on ast.walk's breadth-first order to overwrite an outer function's name. BACKLOG #5520 items 2 and 13, and its filing review finding 1 (the _reader_calls limb). --- tests/test_user_seal.py | 46 ++++++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/tests/test_user_seal.py b/tests/test_user_seal.py index 028cee1b32..a7becbac24 100644 --- a/tests/test_user_seal.py +++ b/tests/test_user_seal.py @@ -411,35 +411,39 @@ def counted(*args: Any, _name: str = name, _original: Any = original, **kw: Any) "create_user": frozenset({"get_user_by_username", "get_user"}), "create_directory_user": frozenset({"get_user"}), # The write routes the row left alone, each acting by id; the store's own write refuses a row - # that fails its seal. Their replies carry no field of the row, but ``set_user_roles`` decides - # its AD refusal on the unchecked ``auth_provider`` and names the unchecked ``username`` in its - # administrator-granted alert. Left for a later item, not covered by this row. + # that fails its seal. Their replies carry no field of the row. ``set_user_roles`` decided its + # AD refusal and its administrator-granted alert on a raw row until BACKLOG #5520 items 2 and + # 13, and now reads the account checked, so it is not listed. # The scan sees only ``.store.`` chains in this one file: an alias, a ``getattr`` or # a read in another module is not seen. "delete_user": frozenset({"get_user"}), "admin_revoke_user_sessions": frozenset({"get_user"}), - "set_user_roles": frozenset({"get_user", "get_user_role_ids"}), } def _reader_calls(source: str, receiver: str) -> list[tuple[str, str]]: - """Every ``..`` in ``source``, named by the innermost function holding it.""" - tree = ast.parse(source) - found: dict[int, tuple[str, str]] = {} - # ast.walk is breadth-first, so an inner function is reached after the one holding it, and - # its name overwrites the outer one for the reads inside it. - for func in ast.walk(tree): - if not isinstance(func, ast.FunctionDef | ast.AsyncFunctionDef): - continue - for node in ast.walk(func): - if ( - isinstance(node, ast.Attribute) - and node.attr in _USER_READERS - and isinstance(node.value, ast.Attribute) - and node.value.attr == receiver - ): - found[id(node)] = (func.name, node.attr) - return list(found.values()) + """Every ``..`` in ``source``, named by the innermost function holding it. + A read outside every function is not collected.""" + found: list[tuple[str, str]] = [] + + # The owner is carried down the tree, so the innermost function names each read whatever order + # a walk visits nodes in (BACKLOG #5520, filing review finding 1). + def visit(node: ast.AST, owner: str | None) -> None: + if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef): + owner = node.name + elif ( + owner is not None + and isinstance(node, ast.Attribute) + and node.attr in _USER_READERS + and isinstance(node.value, ast.Attribute) + and node.value.attr == receiver + ): + found.append((owner, node.attr)) + for child in ast.iter_child_nodes(node): + visit(child, owner) + + visit(ast.parse(source), None) + return found def _assert_reads_only_where_listed( From 7f3d398235e4a5daeeb8d37b4868f504bdbfe752 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 17:44:28 -0600 Subject: [PATCH 07/12] Review round 1: bound every leading-noise sniff, refund a reset's grant on a 503, fix rule prose From review round-8fd5daecbc: - docs/SECURITY.md: the POST /users row no longer cites #5520, which broke the route-row count. - sniff: _looks_like_hl7 (the .hl7 upload and file sniff) and text_sniff_head (the network listeners) skip leading noise with a search too, so none of the three copies the body; _lstrip_bom_ws is renamed _sniff_head, since it returns a 16-byte head. The test adds a positive control and the upload gate's .hl7/.txt/.xml entry point. - reset-password: a Vault transit 503 from the new checked read gives back the grant its gate spent, as the route's other no-change 503 does; pinned by a test that fails without it (403). - usernames.py: the console's POST /ui/users strips before the rule, said as such; the lookalike table drops letters (Canadian syllabics PA/PO, a runic and a Lisu letter) that refused names in those scripts, and adds the Devanagari and Gujarati visarga. - checked_user's docstring names the admin write routes that now decide on it. Proposed PR title: Admin user writes read the record checked, username lookalike delimiters refused, upload sniffs copy no body (BACKLOG #5520) Proposed ledger banner, #5520: PARTIAL -- items 2, 13 (role, scope and reset writes answer 423), 3/14/35 delimiter limb, 3 census limb, 16, 7 reason limb, 18, 34, 36, 37, 40, 41, 42, 10 apiclient limb, filing finding 3 lstrip limb and filing finding 1 _reader_calls limb built; multipart items 20-23, 26-33 met by PR 3053. Left: items 1, 11, 17 (#5559), 4/12, 5, 6/15, 8, 9/24/25 remaining limbs, 10 doc-restating limbs, 19, cross-script lookalikes, 7 strip limb, 38/39 (process), filing findings 1 (other limbs), 2, 3 (shared executor), 4. BACKLOG #5520. --- docs/SECURITY.md | 2 +- messagefoundry/api/auth_routes.py | 9 +++- messagefoundry/auth/service.py | 5 ++- messagefoundry/auth/usernames.py | 21 +++++---- messagefoundry/parsing/sniff.py | 48 +++++++++++--------- messagefoundry/transports/file.py | 2 +- messagefoundry/uploads.py | 4 +- tests/test_sniff_head_copy.py | 73 +++++++++++++++++++++++-------- tests/test_user_seal_routes.py | 33 ++++++++++++++ tests/test_username_rule.py | 5 +++ 10 files changed, 150 insertions(+), 52 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index f2b249d01d..75e2fecf87 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1667,7 +1667,7 @@ tuple: they act only on the caller's own account. | `DELETE` | `/roles/custom/{role_id}` | `users:manage` | `require_step_up_action` (action `save_ends_own_sessions`) **only when the save would end the caller's own sessions**, else the session window (BACKLOG #3401) | | `GET` | `/users` | `users:read` | `require`. Each account's record is checked against its integrity seal (BACKLOG #5520); one that fails is listed by its `id` alone, with `integrity_failed: true` (`IntegrityFailedUser`). What that reports: *What an admin user read reports* below this table | | `GET` | `/users/{user_id}/permissions` | `users:read` | `require` — the effective-permission inspector. The account is read with its record checked against its integrity seal (BACKLOG #5520): 423 when the record fails it, with nothing of the row answered. What the 423 reports, and when a row read mid-write is not refused: *What an admin user read reports* below this table; 404 for an unknown user | -| `POST` | `/users` | `users:manage` | `require_step_up`. Refuses (422) a `username` the new-username rule refuses, before anything is generated or written (BACKLOG #5521). The rule, and what it admits, is stated once, in the docstring of `messagefoundry/auth/usernames.py`; the service refuses the same name 400 for a caller that skips the request model. Which other paths write a username without this rule is stated there too (BACKLOG #5520 item 34) | +| `POST` | `/users` | `users:manage` | `require_step_up`. Refuses (422) a `username` the new-username rule refuses, before anything is generated or written (BACKLOG #5521). The rule, and what it admits, is stated once, in the docstring of `messagefoundry/auth/usernames.py`; the service refuses the same name 400 for a caller that skips the request model. Which other paths write a username without this rule is stated there too | | `POST` | `/users/directory` | `users:manage` | `require_step_up`. Creates a directory (AD) account's mirror row by name, without a sign-in (BACKLOG #2021). The row's `objectGUID`, display name and `mail` come from a service-account directory lookup, never from the request: the body carries `username` and an optional `notify_email`, and an unknown key is refused 422. The row is never born without a notification address: the directory's `mail` is it when BACKLOG #2014's rule adopts it, and `notify_email` is then refused; otherwise `notify_email` is required and checked as `POST /users` checks `email` (400). 404 when the directory has no enabled account by that name, 400 when it returns no readable `objectGUID`, 409 when a row already holds the name or id, 503 when the directory cannot be reached. No roles: they come from the AD-group map at sign-in | | `PATCH` | `/users/{user_id}` | `users:manage` | `require_step_up_action` (action `admin_user_update`). The account is read with its record checked against its integrity seal (BACKLOG #5520): 423 when the record fails it, with nothing of the row answered. What the 423 reports, and when a row read mid-write is not refused: *What an admin user read reports* below this table; 404 for an unknown user | | `DELETE` | `/users/{user_id}` | `users:manage` | `require_step_up` | diff --git a/messagefoundry/api/auth_routes.py b/messagefoundry/api/auth_routes.py index 9d380e2780..85186d05d6 100644 --- a/messagefoundry/api/auth_routes.py +++ b/messagefoundry/api/auth_routes.py @@ -1877,7 +1877,14 @@ async def reset_user_password( ) # BACKLOG #5520 items 2 and 13: a record that fails its seal answers the reads' 423, not # the service loader's 404. The service reads the account again before it writes. - await _checked_user(service, user_id) + try: + await _checked_user(service, user_id) + except HTTPException as exc: + if exc.status_code == status.HTTP_503_SERVICE_UNAVAILABLE: + # A Vault transit outage: nothing was read or changed, so, as for the 503 below, + # the grant this request's gate spent is given back for the retry the 503 asks for. + service.refund_action_step_up(STEP_UP_ACTION_ADMIN_RESET_PASSWORD) + raise try: issued = await service.admin_reset_password(user_id, actor=identity.username) except ValueError as exc: diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 2c7d33a038..62045b630a 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -13468,7 +13468,10 @@ async def _load_users(self) -> list[VerifiedUser]: async def checked_user(self, user_id: str) -> VerifiedUser | None: """The account ``user_id`` names, its whole record checked against its seal, for a caller outside this service that SHOWS it (BACKLOG #5520), and for :meth:`change_password`, which - decides on it (BACKLOG #5902), so its raise-or-``None`` contract binds that control too. + decides on it (BACKLOG #5902), so its raise-or-``None`` contract binds that control too, as + it binds at least the admin role, channel-scope and password-reset routes, which answer + 404 or 423 on it and, for the role write, decide the directory refusal and the + administrator-granted alert on what it returns (BACKLOG #5520 items 2 and 13). ``None`` when no row is there. Raises :class:`UserSealRefused` only when :meth:`_verified` established that the record fails, or :meth:`_checked_by_id` failed closed, and handed that to the seal-failure report, so diff --git a/messagefoundry/auth/usernames.py b/messagefoundry/auth/usernames.py index f3a72fa747..e3f3a5fe83 100644 --- a/messagefoundry/auth/usernames.py +++ b/messagefoundry/auth/usernames.py @@ -5,8 +5,11 @@ It imports only the standard library and the engine-free ``controlchars`` leaf, so the request model ``api.auth_models.UserCreateRequest`` can apply the same rule the service does without importing the service. ``AuthService.create_local_user`` checks it before anything is generated or -written, and the model mirrors it, so at least ``POST /users`` and the console's ``POST -/ui/users`` refuse a name it refuses. Paths that write a username without it include at least +written, and the model mirrors it, so ``POST /users`` refuses a name it refuses. The console's +``POST /ui/users`` applies it to the name after ``str.strip``, which also takes control and +separator characters at the ends, so a name refused only for what sits at its ends is created +there trimmed, and the trimmed name passes the rule. Paths that write a username without it include +at least ``provision-admin``, the directory create paths (``POST /users/directory`` and an AD sign-in that creates its account) and the directory rename refresh (``AuthService._refresh_cached_username``), so an account one of them writes can hold a name this rule refuses. @@ -59,16 +62,18 @@ #: each taken to the ASCII character it renders as before the reserved-form match (BACKLOG #5520 #: items 3, 14 and 35), so ``cli`` + RATIO + ``root`` or ```` in angle quotation marks is #: refused as ``cli:root`` and ```` are. Code points taken from Unicode's confusables data -#: for ``:``, ``<`` and ``>``, and not every lookalike of them. Applied after NFKC, which takes -#: U+2329 and U+232A to U+3008 and U+3009. +#: for ``:``, ``<`` and ``>``, and not every lookalike of them: the letters it lists for them (at +#: least Canadian syllabics PA and PO, a runic letter and a Lisu tone letter) are left out, so a +#: name in those scripts is not refused as a ``<...>`` form. Applied after NFKC, which takes U+2329 +#: and U+232A to U+3008 and U+3009. _DELIMITER_LOOKALIKES: Final = str.maketrans( dict.fromkeys( - (0x02D0, 0x02F8, 0x0589, 0x05C3, 0x0703, 0x0704, 0x16EC, 0x1803, 0x1809, 0x205A) - + (0x2236, 0xA4FD, 0xA789), + (0x02D0, 0x02F8, 0x0589, 0x05C3, 0x0703, 0x0704, 0x0903, 0x0A83, 0x16EC, 0x1803, 0x1809) + + (0x205A, 0x2236, 0xA789), ":", ) - | dict.fromkeys((0x02C2, 0x1438, 0x16B2, 0x2039, 0x276C, 0x276E, 0x27E8, 0x3008), "<") - | dict.fromkeys((0x02C3, 0x1433, 0x203A, 0x276D, 0x276F, 0x27E9, 0x3009), ">") + | dict.fromkeys((0x02C2, 0x2039, 0x276C, 0x276E, 0x27E8, 0x3008), "<") + | dict.fromkeys((0x02C3, 0x203A, 0x276D, 0x276F, 0x27E9, 0x3009), ">") ) diff --git a/messagefoundry/parsing/sniff.py b/messagefoundry/parsing/sniff.py index 4a60fbcec4..bd7302a7e2 100644 --- a/messagefoundry/parsing/sniff.py +++ b/messagefoundry/parsing/sniff.py @@ -42,6 +42,10 @@ # Segment ids a valid HL7 v2 payload (single message or batch file) may start with. _HL7_LEADING_SEGMENTS = (b"MSH", b"FHS", b"BHS") +#: The first byte past the leading noise :func:`_looks_like_hl7` tolerates (the MLLP start byte, +#: CR, LF, space and tab), found in C without copying the body. +_PAST_HL7_LEADING_WS = re.compile(rb"[^\x0b\r\n \t]") + def _looks_like_hl7(raw: bytes) -> bool: """Cheap content sniff: does ``raw`` start with an HL7 v2 header segment (ASVS 5.2.2)? @@ -51,10 +55,7 @@ def _looks_like_hl7(raw: bytes) -> bool: (file) or BHS (batch). This rejects a binary or non-HL7 file that merely carries the ``.hl7`` extension before its bytes enter the pipeline, without rejecting a structurally-odd-but-textual HL7 message (which still flows through and is recorded as ``ERROR`` by the parser).""" - head = raw.lstrip(b"\x0b\r\n \t") - if head.startswith(b"\xef\xbb\xbf"): # UTF-8 BOM - head = head[3:].lstrip(b"\x0b\r\n \t") - return head[:3] in _HL7_LEADING_SEGMENTS + return _sniff_head(raw, _PAST_HL7_LEADING_WS)[:3] in _HL7_LEADING_SEGMENTS # Leading noise tolerated before a JSON/XML/X12 magic byte: ASCII whitespace incl. the MLLP start byte @@ -69,20 +70,20 @@ def _looks_like_hl7(raw: bytes) -> bool: #: The first byte that is not :data:`_LEADING_WS`, found in C without copying the body. _PAST_LEADING_WS = re.compile(b"[^" + re.escape(_LEADING_WS) + b"]") -#: How much of the body past the leading noise :func:`_lstrip_bom_ws` returns: more than the -#: longest signature any caller compares (the 8-byte PNG magic). +#: How much of the body past the leading noise :func:`_sniff_head` returns: more than the longest +#: signature any caller compares (the 8-byte PNG magic). _SNIFF_HEAD_BYTES = 16 -def _lstrip_bom_ws(raw: bytes) -> bytes: - """The first :data:`_SNIFF_HEAD_BYTES` of ``raw`` past leading :data:`_LEADING_WS` and one - UTF-8 BOM (with white space either side of it). Only that head is copied, so a large body with - leading noise is not copied whole (BACKLOG #5520, filing review finding 3); every caller compares - a signature at its start.""" - found = _PAST_LEADING_WS.search(raw) +def _sniff_head(raw: bytes, past_noise: re.Pattern[bytes] = _PAST_LEADING_WS) -> bytes: + """At most the first :data:`_SNIFF_HEAD_BYTES` of ``raw`` past its leading noise (the bytes + ``past_noise`` does not match) and one UTF-8 BOM, with noise either side of it. A head for a + signature check, never the body: only the head is copied, so a large body with leading noise + is not copied whole (BACKLOG #5520, filing review finding 3).""" + found = past_noise.search(raw) at = len(raw) if found is None else found.start() if raw.startswith(b"\xef\xbb\xbf", at): # UTF-8 BOM - found = _PAST_LEADING_WS.search(raw, at + 3) + found = past_noise.search(raw, at + 3) at = len(raw) if found is None else found.start() return raw[at : at + _SNIFF_HEAD_BYTES] @@ -96,6 +97,11 @@ def _lstrip_bom_ws(raw: bytes) -> bytes: #: keeping the work O(1) instead of re-encoding a whole 16 MiB body. _TEXT_SNIFF_HEAD_CHARS = 8 +#: The first character that is not :data:`_LEADING_WS_STR`, found without copying the text, so a +#: large decoded body with leading noise is not copied whole (BACKLOG #5520, filing review +#: finding 3). +_PAST_LEADING_WS_STR = re.compile("[^" + re.escape(_LEADING_WS_STR) + "]") + def text_sniff_head(text: str) -> bytes: """UTF-8 head bytes of an already-DECODED body, to hand to :func:`_content_matches_declared`. @@ -111,7 +117,9 @@ def text_sniff_head(text: str) -> bytes: Leading whitespace/BOM is stripped in str space first, so the head starts at the first significant character however much whitespace preceded it; :func:`_content_matches_declared` strips again in byte space, which is idempotent.""" - return text.lstrip(_LEADING_WS_STR)[:_TEXT_SNIFF_HEAD_CHARS].encode("utf-8") + found = _PAST_LEADING_WS_STR.search(text) + at = len(text) if found is None else found.start() + return text[at : at + _TEXT_SNIFF_HEAD_CHARS].encode("utf-8") def _content_matches_declared(content_type: ContentType | None, raw: bytes) -> bool: @@ -131,7 +139,7 @@ def _content_matches_declared(content_type: ContentType | None, raw: bytes) -> b case ContentType.HL7V2 | None: return _looks_like_hl7(raw) case ContentType.X12: - return _lstrip_bom_ws(raw).startswith(b"ISA") + return _sniff_head(raw).startswith(b"ISA") case ContentType.DICOM: # DICOM Part-10: 128-byte preamble + the "DICM" magic. Every DICOM object the engine produces # (C-STORE SCP save_as enforce_file_format=True, dicom.py) or parses (dcmread force=False, @@ -142,9 +150,9 @@ def _content_matches_declared(content_type: ContentType | None, raw: bytes) -> b # FHIR is HL7 FHIR JSON, so it shares the JSON magic (leading { or [ after BOM/ws). Accepting a # top-level [ for FHIR is superset-permissive by design (a single resource is {…}, a bundle is # too) — the accept-gate can only ADMIT more; parsing/fhir stays the real validator. - return _lstrip_bom_ws(raw)[:1] in (b"{", b"[") + return _sniff_head(raw)[:1] in (b"{", b"[") case ContentType.XML: - return _lstrip_bom_ws(raw).startswith(b"<") + return _sniff_head(raw).startswith(b"<") case _: # BINARY / TEXT — opaque bytes / arbitrary text, no reliable signature → accept unchecked return True @@ -184,9 +192,9 @@ def attachment_mime_agrees(content_type: str | None, head: bytes) -> bool: if exact is not None: return head.startswith(exact) if mime in _XML_MIMES or mime.endswith("+xml"): - return _lstrip_bom_ws(head).startswith(b"<") + return _sniff_head(head).startswith(b"<") if mime == "application/json" or mime.endswith("+json"): - return _lstrip_bom_ws(head)[:1] in (b"{", b"[") + return _sniff_head(head)[:1] in (b"{", b"[") return True # no reliable signature for this MIME → accept the declared label unchecked @@ -232,7 +240,7 @@ def nontext_upload_reason(data: bytes) -> str | None: begins with a container's signature never reaches the store. This is a stricter, binary-shaped gate than the 5.2.2 extension/content sniff (which maps a text-but-mismatched body to 400); a container carrying a permitted text extension is caught here first (415), so the 5.2.2 400 path handles the remaining text-vs-extension mismatches.""" - head = _lstrip_bom_ws(data) + head = _sniff_head(data) for mime, prefixes in _MAGIC_PREFIXES.items(): if head.startswith(prefixes): return f"body is a {mime} container; the uploaded-logs feature accepts only plain-text logs" diff --git a/messagefoundry/transports/file.py b/messagefoundry/transports/file.py index d500520c59..dd50a96db8 100644 --- a/messagefoundry/transports/file.py +++ b/messagefoundry/transports/file.py @@ -2667,7 +2667,7 @@ def _win_delete_aged(path: Path, older_than: float) -> bool: # --- helpers ----------------------------------------------------------------- -# The pure magic-byte sniffers (_looks_like_hl7 / _lstrip_bom_ws / _content_matches_declared) were hoisted +# The pure magic-byte sniffers (_looks_like_hl7 / _sniff_head / _content_matches_declared) were hoisted # to parsing/sniff.py (ASVS 5.2.2) so the leaf uploads.py can reuse them without importing a transport; # they are re-imported at the top of this module and re-exported (see __all__) so remotefile.py and the # existing tests that import them from here are unchanged. diff --git a/messagefoundry/uploads.py b/messagefoundry/uploads.py index dccf8d2898..79327b93c8 100644 --- a/messagefoundry/uploads.py +++ b/messagefoundry/uploads.py @@ -58,7 +58,7 @@ strip_control_chars, ) from messagefoundry.parsing.peek import HL7PeekError, Peek -from messagefoundry.parsing.sniff import _looks_like_hl7, _lstrip_bom_ws, nontext_upload_reason +from messagefoundry.parsing.sniff import _looks_like_hl7, _sniff_head, nontext_upload_reason from messagefoundry.parsing.split import split_batch from messagefoundry.path_reach import is_absent, is_name_absent, is_unreachable from messagefoundry.redaction import codec_safe_str, json_loads_or_refusal @@ -1363,7 +1363,7 @@ def validate_upload_content(display: str, data: bytes) -> None: raise UploadContentError( display, "is not HL7 (no MSH/FHS/BHS header) despite its extension" ) - if ctype == "xml" and not _lstrip_bom_ws(data).startswith(b"<"): + if ctype == "xml" and not _sniff_head(data).startswith(b"<"): raise UploadContentError(display, "is not XML (no leading '<') despite its extension") diff --git a/tests/test_sniff_head_copy.py b/tests/test_sniff_head_copy.py index 8efcd450ef..531d9abd7a 100644 --- a/tests/test_sniff_head_copy.py +++ b/tests/test_sniff_head_copy.py @@ -1,44 +1,76 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""BACKLOG #5520, filing review finding 3: the upload gate's leading-noise skip copies a bounded -head, not the body. - -``nontext_upload_reason`` reads past leading white space and a UTF-8 BOM before it compares a -container's magic bytes. It did that with ``bytes.lstrip``, which copies the rest of the body when -anything is stripped, so a body that starts with one space cost a second copy of itself. The skip -now finds the first byte past the noise in place and copies only a short head. Each test has a -control: the same body with no leading noise, which never copied, and the refusals the skip feeds. +"""BACKLOG #5520, filing review finding 3: the content sniffs skip leading noise by copying a +bounded head, not the body. + +The upload gate (``uploads.validate_upload_content``: ``nontext_upload_reason``, then the +``.hl7``/``.xml`` sniff), the file transports' ``_content_matches_declared`` and the network +listeners' ``text_sniff_head`` read past leading white space and a BOM before they compare a +signature. They did that with ``lstrip``, which copies the rest of the body when anything is +stripped, so a body that starts with one space cost a second copy of itself. Each skip now finds +the first byte past the noise in place and copies only a short head. The positive control shows +the instrument sees a whole-body copy; the clean-body control shows a body with nothing to skip. """ from __future__ import annotations import tracemalloc +from collections.abc import Callable import pytest from messagefoundry.content_type import ContentType -from messagefoundry.parsing.sniff import _content_matches_declared, nontext_upload_reason +from messagefoundry.parsing.sniff import ( + _content_matches_declared, + nontext_upload_reason, + text_sniff_head, +) +from messagefoundry.uploads import validate_upload_content _SIZE = 4 * 1024 * 1024 +_NOISE = [b" ", b"\r\n", b"\xef\xbb\xbf", b" \xef\xbb\xbf\t"] -def _peak(body: bytes) -> int: +def _peak(call: Callable[[], object]) -> int: tracemalloc.start() try: tracemalloc.reset_peak() - assert nontext_upload_reason(body) is None + call() return tracemalloc.get_traced_memory()[1] finally: tracemalloc.stop() -@pytest.mark.parametrize("noise", [b" ", b"\r\n", b"\xef\xbb\xbf", b" \xef\xbb\xbf\t"]) -def test_leading_noise_does_not_copy_the_body(noise: bytes) -> None: - body = noise + b"MSH|" + b"a" * _SIZE - clean = b"MSH|" + b"a" * _SIZE +def test_the_instrument_sees_a_whole_body_copy() -> None: + """Positive control: the copy the old skip made is over the bound the tests below hold.""" + body = b" MSH|" + b"a" * _SIZE + assert _peak(lambda: body.lstrip(b" ")) >= _SIZE + + +@pytest.mark.parametrize("noise", _NOISE) +@pytest.mark.parametrize("name", ["x.hl7", "x.txt", "x.xml"]) +def test_the_upload_gate_does_not_copy_a_body_with_leading_noise(noise: bytes, name: str) -> None: + payload = (b"" if name.endswith(".xml") else b"MSH|") + b"a" * _SIZE + noisy = noise + payload # Control: a body with nothing to skip. - assert _peak(clean) < _SIZE // 8 - assert _peak(body) < _SIZE // 8 + assert _peak(lambda: validate_upload_content(name, payload)) < _SIZE // 8 + assert _peak(lambda: validate_upload_content(name, noisy)) < _SIZE // 8 + + +@pytest.mark.parametrize("noise", _NOISE) +@pytest.mark.parametrize("content_type", [ContentType.HL7V2, ContentType.JSON, ContentType.X12]) +def test_the_file_sniff_does_not_copy_a_body_with_leading_noise( + noise: bytes, content_type: ContentType +) -> None: + body = noise + b"x" * _SIZE + assert _peak(lambda: _content_matches_declared(content_type, body)) < _SIZE // 8 + + +@pytest.mark.parametrize("noise", [" ", "\r\n", chr(0xFEFF), " " + chr(0xFEFF) + "\t"]) +def test_the_listener_sniff_does_not_copy_a_text_with_leading_noise(noise: str) -> None: + text = noise + "MSH|" + "a" * _SIZE + assert text_sniff_head(text) == b"MSH|aaaa" + assert _peak(lambda: text_sniff_head(text)) < _SIZE // 8 @pytest.mark.parametrize( @@ -67,10 +99,15 @@ def test_a_container_behind_leading_noise_is_still_refused(body: bytes) -> None: (ContentType.JSON, b" ", False), (ContentType.X12, b"\x0b\x0cISA*00", True), (ContentType.X12, b"ISX", False), + (ContentType.HL7V2, b"\x0b\r\nMSH|", True), + (ContentType.HL7V2, b" \xef\xbb\xbf\tFHS|", True), + # The HL7 sniff's own noise set has no form feed. + (ContentType.HL7V2, b"\x0cMSH|", False), + (ContentType.HL7V2, b" PID|", False), ], ) def test_the_content_sniffs_read_the_same_head( content_type: ContentType, body: bytes, agrees: bool ) -> None: - """The format sniffs share the skip: what they admit is unchanged.""" + """What the sniffs admit is unchanged.""" assert _content_matches_declared(content_type, body) is agrees diff --git a/tests/test_user_seal_routes.py b/tests/test_user_seal_routes.py index 4bb34dce78..daf422fa47 100644 --- a/tests/test_user_seal_routes.py +++ b/tests/test_user_seal_routes.py @@ -39,6 +39,7 @@ from messagefoundry.config.settings import AuthSettings, EgressSettings from messagefoundry.pipeline import Engine from messagefoundry.store.crypto import generate_key, make_cipher +from messagefoundry.store.row_seal import TransitSealUnavailableError from messagefoundry.store.store import AdminRemoval, MessageStore, UserRecord from tests.test_api_auth import ABSENT_USER_ID, _add, _auth, _login, _reauth from tests.test_user_seal import _raw_for @@ -225,6 +226,38 @@ async def send(user_id: str) -> httpx.Response: assert served.status_code == 200, served.text +async def test_a_reset_refused_for_a_vault_outage_gives_its_grant_back( + keyed: tuple[Engine, Path], monkeypatch: pytest.MonkeyPatch +) -> None: + """The reset's checked read answers a Vault transit outage 503 before anything is changed, so + the ``admin_reset_password`` grant its gate spent is given back, as for the route's other + no-change 503: the retry the 503 asks for is served with no new proof. The control is the 423, + which keeps the cost docs/SECURITY.md states.""" + engine, path = keyed + service, _alerts, intact, victim = await _setup(engine) + await _tamper(path, victim) + real = service.checked_user + + async def outage(user_id: str) -> None: + raise TransitSealUnavailableError() + + async with _client(engine, service) as c: + token = (await _login(c, "root")).json()["token"] + _, token = await _reauth(c, token, purpose="admin_reset_password") + monkeypatch.setattr(service, "checked_user", outage) + refused = await c.post(f"/users/{intact}/reset-password", headers=_auth(token)) + monkeypatch.setattr(service, "checked_user", real) + retried = await c.post(f"/users/{intact}/reset-password", headers=_auth(token)) + # Control: a 423 spends the grant, so the next reset needs a new proof. + _, token = await _reauth(c, token, purpose="admin_reset_password") + locked = await c.post(f"/users/{victim}/reset-password", headers=_auth(token)) + spent = await c.post(f"/users/{intact}/reset-password", headers=_auth(token)) + assert refused.status_code == 503, refused.text + assert retried.status_code == 200, retried.text + assert locked.status_code == 423, locked.text + assert spent.status_code == 403, spent.text + + async def test_checked_user_tells_a_failing_record_from_a_missing_one( keyed: tuple[Engine, Path], ) -> None: diff --git a/tests/test_username_rule.py b/tests/test_username_rule.py index 6315156636..00db741d1d 100644 --- a/tests/test_username_rule.py +++ b/tests/test_username_rule.py @@ -98,6 +98,8 @@ "\u02c2directory\u02c3", # MODIFIER LETTER LEFT/RIGHT ARROWHEAD "\u27e8oidc\u27e9", # MATHEMATICAL LEFT/RIGHT ANGLE BRACKET "\u2039oidc>", + "cli" + chr(0x0903) + "root", # DEVANAGARI SIGN VISARGA + "cli" + chr(0x0A83) + "root", # GUJARATI SIGN VISARGA ] #: The controls: names beside each refused form that the rule must leave alone. @@ -122,6 +124,9 @@ "sys\u2236tem", "\u2039bob", "bob\u203a", + # Letters the confusables data lists for "<" and ">", left out of the table: a Canadian + # syllabics name that starts with PA and ends with PO is not a "<...>" form. + chr(0x1438) + chr(0x140A) + chr(0x1433), ] From 1277b992c2d7a23fa206671eacb1ff005ad4bf1d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 18:17:42 -0600 Subject: [PATCH 08/12] Review round 2: keep the reset refund set as recorded, correct the rule's console and table prose From review round-79c01077ad: - reset-password no longer refunds its grant on the checked read's Vault outage 503: a change to the refund set is an ADR 0197 decision nobody recorded. docs/SECURITY.md now states that 503 costs the proof, as the 423 and the 404 do. - usernames.py: str.strip takes only what str.isspace counts as white space, said as such; the lookalike table names what it leaves out (some letters, U+FE30) and adds U+17D6 and the Greek instrumental notation symbols U+1D236/U+1D237, each pinned in the refused list. - transports/file.py: the hoist comment no longer says _sniff_head is re-exported there. Proposed PR title: Admin user writes read the record checked, username lookalike delimiters refused, upload and ingress sniffs copy no body (BACKLOG #5520) Proposed ledger banner, #5520: PARTIAL -- built: items 2 and 13 (PUT roles, PUT channel-scope and POST reset-password answer 423), 3/14/35 delimiter-lookalike limb, 3 census limb, 7 and 16 reason limb, 18, 34, 36, 37, 40, 41, 42, 10 apiclient-union limb, filing finding 1 _reader_calls limb, filing finding 3 whole-body lstrip limb; met by PR 3053: items 20-23, 26-33. Left: items 1, 11, 17 (on #5559), 4/12, 5, 6/15, 8, 9/24/25 remaining limbs, 10 doc limbs, 13 for reset-mfa and other sibling routes, 19, cross-script lookalikes, 7 strip limb, 38/39 (process), filing findings 1 (other limbs), 2, 3 (shared executor), 4, and this PR's open review findings. BACKLOG #5520. --- docs/SECURITY.md | 4 ++-- messagefoundry/api/auth_routes.py | 9 +------- messagefoundry/auth/usernames.py | 25 ++++++++++++---------- messagefoundry/transports/file.py | 6 +++--- tests/test_user_seal_routes.py | 35 +------------------------------ tests/test_username_rule.py | 2 ++ 6 files changed, 23 insertions(+), 58 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 75e2fecf87..9ff8413379 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1738,8 +1738,8 @@ after its gate has spent the single-use `admin_user_update` grant, so its 423 an proof, as the console's `POST /ui/users/{user_id}/update` does after its own gate. So does its 422 for a changed display name the name rule refuses (BACKLOG #5784), which the route checks against the stored name after that read. `POST /users/{user_id}/reset-password` reads the account after -its gate has spent the single-use `admin_reset_password` grant, so its 423 and its 404 cost that -proof too. Where it is +its gate has spent the single-use `admin_reset_password` grant, so its 423, its 404 and the 503 its +checked read answers for a Vault transit outage cost that proof too. Where it is off, the gate checks the step-up session window instead and spends nothing, so none of these answers costs a proof. On a `vault_transit` store (ADR 0217), a record Vault transit cannot verify is answered the same way as a failing record, but reported under diff --git a/messagefoundry/api/auth_routes.py b/messagefoundry/api/auth_routes.py index 85186d05d6..9d380e2780 100644 --- a/messagefoundry/api/auth_routes.py +++ b/messagefoundry/api/auth_routes.py @@ -1877,14 +1877,7 @@ async def reset_user_password( ) # BACKLOG #5520 items 2 and 13: a record that fails its seal answers the reads' 423, not # the service loader's 404. The service reads the account again before it writes. - try: - await _checked_user(service, user_id) - except HTTPException as exc: - if exc.status_code == status.HTTP_503_SERVICE_UNAVAILABLE: - # A Vault transit outage: nothing was read or changed, so, as for the 503 below, - # the grant this request's gate spent is given back for the retry the 503 asks for. - service.refund_action_step_up(STEP_UP_ACTION_ADMIN_RESET_PASSWORD) - raise + await _checked_user(service, user_id) try: issued = await service.admin_reset_password(user_id, actor=identity.username) except ValueError as exc: diff --git a/messagefoundry/auth/usernames.py b/messagefoundry/auth/usernames.py index e3f3a5fe83..a5d746a58b 100644 --- a/messagefoundry/auth/usernames.py +++ b/messagefoundry/auth/usernames.py @@ -6,9 +6,11 @@ model ``api.auth_models.UserCreateRequest`` can apply the same rule the service does without importing the service. ``AuthService.create_local_user`` checks it before anything is generated or written, and the model mirrors it, so ``POST /users`` refuses a name it refuses. The console's -``POST /ui/users`` applies it to the name after ``str.strip``, which also takes control and -separator characters at the ends, so a name refused only for what sits at its ends is created -there trimmed, and the trimmed name passes the rule. Paths that write a username without it include +``POST /ui/users`` applies it to the name after ``str.strip``, which takes the characters +``str.isspace`` counts as white space from the ends (at least the C0 separators U+001C to U+001F +and the line and paragraph separators among them), so a name refused only for such characters at +its ends is created there trimmed, and the trimmed name passes the rule. A control, format or +blank-glyph character at an end that is not white space is still refused there. Paths that write a username without it include at least ``provision-admin``, the directory create paths (``POST /users/directory`` and an AD sign-in that creates its account) and the directory rename refresh (``AuthService._refresh_cached_username``), @@ -62,18 +64,19 @@ #: each taken to the ASCII character it renders as before the reserved-form match (BACKLOG #5520 #: items 3, 14 and 35), so ``cli`` + RATIO + ``root`` or ```` in angle quotation marks is #: refused as ``cli:root`` and ```` are. Code points taken from Unicode's confusables data -#: for ``:``, ``<`` and ``>``, and not every lookalike of them: the letters it lists for them (at -#: least Canadian syllabics PA and PO, a runic letter and a Lisu tone letter) are left out, so a -#: name in those scripts is not refused as a ``<...>`` form. Applied after NFKC, which takes U+2329 -#: and U+232A to U+3008 and U+3009. +#: for ``:``, ``<`` and ``>``, and not every lookalike of them. At least these are left out: some +#: letters it lists (Canadian syllabics PA and PO, a runic letter and a Lisu tone letter), so a +#: name in those scripts is not refused as a ``<...>`` form, though the modifier letters U+02D0, +#: U+02F8, U+A789, U+02C2 and U+02C3 are kept; and U+FE30, which NFKC turns into a two-dot leader +#: rather than a colon. Applied after NFKC, which takes U+2329 and U+232A to U+3008 and U+3009. _DELIMITER_LOOKALIKES: Final = str.maketrans( dict.fromkeys( - (0x02D0, 0x02F8, 0x0589, 0x05C3, 0x0703, 0x0704, 0x0903, 0x0A83, 0x16EC, 0x1803, 0x1809) - + (0x205A, 0x2236, 0xA789), + (0x02D0, 0x02F8, 0x0589, 0x05C3, 0x0703, 0x0704, 0x0903, 0x0A83, 0x16EC, 0x17D6, 0x1803) + + (0x1809, 0x205A, 0x2236, 0xA789), ":", ) - | dict.fromkeys((0x02C2, 0x2039, 0x276C, 0x276E, 0x27E8, 0x3008), "<") - | dict.fromkeys((0x02C3, 0x203A, 0x276D, 0x276F, 0x27E9, 0x3009), ">") + | dict.fromkeys((0x02C2, 0x2039, 0x276C, 0x276E, 0x27E8, 0x3008, 0x1D236), "<") + | dict.fromkeys((0x02C3, 0x203A, 0x276D, 0x276F, 0x27E9, 0x3009, 0x1D237), ">") ) diff --git a/messagefoundry/transports/file.py b/messagefoundry/transports/file.py index dd50a96db8..e656b1bee3 100644 --- a/messagefoundry/transports/file.py +++ b/messagefoundry/transports/file.py @@ -2667,9 +2667,9 @@ def _win_delete_aged(path: Path, older_than: float) -> bool: # --- helpers ----------------------------------------------------------------- -# The pure magic-byte sniffers (_looks_like_hl7 / _sniff_head / _content_matches_declared) were hoisted -# to parsing/sniff.py (ASVS 5.2.2) so the leaf uploads.py can reuse them without importing a transport; -# they are re-imported at the top of this module and re-exported (see __all__) so remotefile.py and the +# The pure magic-byte sniffers were hoisted to parsing/sniff.py (ASVS 5.2.2) so the leaf uploads.py +# can reuse them without importing a transport; _looks_like_hl7 and _content_matches_declared are +# re-imported at the top of this module and re-exported (see __all__) so remotefile.py and the # existing tests that import them from here are unchanged. diff --git a/tests/test_user_seal_routes.py b/tests/test_user_seal_routes.py index daf422fa47..127e47c6f6 100644 --- a/tests/test_user_seal_routes.py +++ b/tests/test_user_seal_routes.py @@ -39,7 +39,6 @@ from messagefoundry.config.settings import AuthSettings, EgressSettings from messagefoundry.pipeline import Engine from messagefoundry.store.crypto import generate_key, make_cipher -from messagefoundry.store.row_seal import TransitSealUnavailableError from messagefoundry.store.store import AdminRemoval, MessageStore, UserRecord from tests.test_api_auth import ABSENT_USER_ID, _add, _auth, _login, _reauth from tests.test_user_seal import _raw_for @@ -226,38 +225,6 @@ async def send(user_id: str) -> httpx.Response: assert served.status_code == 200, served.text -async def test_a_reset_refused_for_a_vault_outage_gives_its_grant_back( - keyed: tuple[Engine, Path], monkeypatch: pytest.MonkeyPatch -) -> None: - """The reset's checked read answers a Vault transit outage 503 before anything is changed, so - the ``admin_reset_password`` grant its gate spent is given back, as for the route's other - no-change 503: the retry the 503 asks for is served with no new proof. The control is the 423, - which keeps the cost docs/SECURITY.md states.""" - engine, path = keyed - service, _alerts, intact, victim = await _setup(engine) - await _tamper(path, victim) - real = service.checked_user - - async def outage(user_id: str) -> None: - raise TransitSealUnavailableError() - - async with _client(engine, service) as c: - token = (await _login(c, "root")).json()["token"] - _, token = await _reauth(c, token, purpose="admin_reset_password") - monkeypatch.setattr(service, "checked_user", outage) - refused = await c.post(f"/users/{intact}/reset-password", headers=_auth(token)) - monkeypatch.setattr(service, "checked_user", real) - retried = await c.post(f"/users/{intact}/reset-password", headers=_auth(token)) - # Control: a 423 spends the grant, so the next reset needs a new proof. - _, token = await _reauth(c, token, purpose="admin_reset_password") - locked = await c.post(f"/users/{victim}/reset-password", headers=_auth(token)) - spent = await c.post(f"/users/{intact}/reset-password", headers=_auth(token)) - assert refused.status_code == 503, refused.text - assert retried.status_code == 200, retried.text - assert locked.status_code == 423, locked.text - assert spent.status_code == 403, spent.text - - async def test_checked_user_tells_a_failing_record_from_a_missing_one( keyed: tuple[Engine, Path], ) -> None: @@ -557,7 +524,7 @@ def test_the_security_doc_states_what_a_423_reports_and_costs() -> None: "Each engine process sharing the store keeps its own interval", "Where `[auth].require_action_step_up` is on, the default", "the single-use `admin_user_update` grant, so its 423 and its 404 cost that proof", - "the single-use `admin_reset_password` grant, so its 423 and its 404 cost that proof", + "the single-use `admin_reset_password` grant, so its 423, its 404 and the 503", "Where it is off, the gate checks the step-up session window instead and spends nothing", ): assert fact in body, fact diff --git a/tests/test_username_rule.py b/tests/test_username_rule.py index 00db741d1d..b34d73c974 100644 --- a/tests/test_username_rule.py +++ b/tests/test_username_rule.py @@ -100,6 +100,8 @@ "\u2039oidc>", "cli" + chr(0x0903) + "root", # DEVANAGARI SIGN VISARGA "cli" + chr(0x0A83) + "root", # GUJARATI SIGN VISARGA + "cli" + chr(0x17D6) + "root", # KHMER SIGN CAMNUC PII KUUH + chr(0x1D236) + "oidc" + chr(0x1D237), # GREEK INSTRUMENTAL NOTATION SYMBOL-38/39 ] #: The controls: names beside each refused form that the rule must leave alone. From 29540e635eea7a58e50239a99c743e5c6a036530 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 19:05:57 -0600 Subject: [PATCH 09/12] Console reads the username rule's reason from the model's refusal; correct rule and doc text Manager decisions of 2026-11-23 on review round-a2d3572e01: - Finding 1: POST /ui/users takes the rule's reason from the UserCreateRequest refusal (_username_rule_reason) instead of running username_refusal again, so a name the length cap refused is never walked whole on the event loop. Pinned by test_the_console_create_does_not_run_the_rule_over_an_over_long_name, which fails on the previous head (the rule ran over 1,044,480 characters). - Findings 7, 8, 9, 11: NFKC takes U+FE30 to "..", the test names SYMBOL-40 and SYMBOL-42, the docstring names same-script lookalikes that pass, and the marker is named for both the directory sign-in and the reconciler. - Finding 2: docs/SECURITY.md states that the honest-race false alarm answers 423 on PUT /users/{user_id}/roles and the write does not happen (decision d20261123T150929936-d70a0b). BACKLOG #5520. --- docs/SECURITY.md | 5 ++- messagefoundry/auth/usernames.py | 14 +++++--- messagefoundry_webconsole/routes/admin.py | 17 +++++++-- .../tests/test_webui_users.py | 35 +++++++++++++++++++ tests/test_username_rule.py | 2 +- 5 files changed, 64 insertions(+), 9 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 9ff8413379..3e42519680 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1732,7 +1732,10 @@ or federated pair cannot make it vanish from these reads. One that keeps changin unreported. Honest writes that race all three checks the same way would be a false alarm too. **Two honest role writes to the account that commit across both of those reads are still answered as a failing record and reported**, a false alarm the reads cannot tell from -tampering, because the role rows are read apart from the account's row. Where +tampering, because the role rows are read apart from the account's row. Since +`PUT /users/{user_id}/roles` reads the account this way before it writes, that false alarm there +answers 423 and the role write does not happen, where before this read it would have gone ahead: +an over-refusal, kept by decision d20261123T150929936-d70a0b. Where `[auth].require_action_step_up` is on, the default, `PATCH /users/{user_id}` reads the account after its gate has spent the single-use `admin_user_update` grant, so its 423 and its 404 cost that proof, as the console's `POST /ui/users/{user_id}/update` does after its own gate. So does its 422 diff --git a/messagefoundry/auth/usernames.py b/messagefoundry/auth/usernames.py index a5d746a58b..1314f59262 100644 --- a/messagefoundry/auth/usernames.py +++ b/messagefoundry/auth/usernames.py @@ -29,13 +29,17 @@ ``tests/test_username_rule.py::test_the_rule_refuses``. The bare word ``directory`` is NOT reserved: nothing at HEAD writes it as an audit actor. The -directory sign-in's marker ```` (``api.security.DIRECTORY_GRANTED_BY``) is, by the -``<...>`` form. +``granted_by`` marker ```` (``api.security.DIRECTORY_GRANTED_BY``), which a directory +sign-in and the directory reconciler put on the ``administrator_granted`` alert, is reserved, by +the ``<...>`` form. What it admits, at least: a space separator inside the name (U+00A0, U+3000), a blank glyph :data:`_BLANK_GLYPHS` does not list, and a lookalike letter from another script, so a Cyrillic spelling that reads as ``system`` passes, as does a reserved form spelled with a delimiter -lookalike :data:`_DELIMITER_LOOKALIKES` does not list. It matches the reserved forms after NFKC, +lookalike :data:`_DELIMITER_LOOKALIKES` does not list. At least some lookalikes from the same +script pass too: ``cli:root`` spelled with a dotless i (U+0131), ```` spelled with the +modifier low arrowheads U+02F1 and U+02F2, and ```` followed by a combining low line +(U+0332). It matches the reserved forms after NFKC, with the delimiter lookalikes that table lists taken to ASCII, and case folding; it does not fold confusable letters across scripts. @@ -67,8 +71,8 @@ #: for ``:``, ``<`` and ``>``, and not every lookalike of them. At least these are left out: some #: letters it lists (Canadian syllabics PA and PO, a runic letter and a Lisu tone letter), so a #: name in those scripts is not refused as a ``<...>`` form, though the modifier letters U+02D0, -#: U+02F8, U+A789, U+02C2 and U+02C3 are kept; and U+FE30, which NFKC turns into a two-dot leader -#: rather than a colon. Applied after NFKC, which takes U+2329 and U+232A to U+3008 and U+3009. +#: U+02F8, U+A789, U+02C2 and U+02C3 are kept; and U+FE30, which NFKC turns into two full stops +#: (``..``) rather than a colon. Applied after NFKC, which takes U+2329 and U+232A to U+3008 and U+3009. _DELIMITER_LOOKALIKES: Final = str.maketrans( dict.fromkeys( (0x02D0, 0x02F8, 0x0589, 0x05C3, 0x0703, 0x0704, 0x0903, 0x0A83, 0x16EC, 0x17D6, 0x1803) diff --git a/messagefoundry_webconsole/routes/admin.py b/messagefoundry_webconsole/routes/admin.py index d37afd6d37..fbd2a69ba5 100644 --- a/messagefoundry_webconsole/routes/admin.py +++ b/messagefoundry_webconsole/routes/admin.py @@ -53,7 +53,6 @@ STEP_UP_ACTION_SAVE_ENDS_OWN_SESSIONS, AuthService, ) -from messagefoundry.auth.usernames import username_refusal from messagefoundry.controlchars import scrub_log_argument from .. import pages @@ -248,6 +247,18 @@ def _refusal_status(exc: Exception) -> int: return status.HTTP_400_BAD_REQUEST +def _username_rule_reason(exc: ValidationError) -> str | None: + """The new-username rule's reason from a ``UserCreateRequest`` refusal, or ``None`` when the + rule did not refuse the name (BACKLOG #5520 items 7 and 16). The rule raises a ``ValueError`` + whose text is fixed and never echoes the value; any other error on the field, such as the + length cap, which refuses before the rule runs, gives ``None``.""" + for error in exc.errors(include_url=False, include_input=False): + cause = error.get("ctx", {}).get("error") + if error["loc"] == ("username",) and isinstance(cause, ValueError): + return str(cause) + return None + + def _group_keys(pairs: list[tuple[str, str]]) -> list[str]: """The form's AD group values, trimmed of a space, a tab and a line break only. @@ -454,7 +465,9 @@ async def ui_user_create( if isinstance(exc, ValidationError): # BACKLOG #5520 items 7 and 16: the username rule's reason is fixed text that never # echoes the value, so the form can say why; any other field keeps "invalid input". - detail = username_refusal(form.get("username", "").strip()) or detail + # Read from the model's own refusal rather than by running the rule again, so a name + # the length cap refused is never walked whole on the event loop. + detail = _username_rule_reason(exc) or detail all_roles = await admin.list_roles(service=service, _=identity) return HTMLResponse( pages.user_new_page( diff --git a/packaging/messagefoundry-webconsole/tests/test_webui_users.py b/packaging/messagefoundry-webconsole/tests/test_webui_users.py index 2b26422a7b..a212ac897b 100644 --- a/packaging/messagefoundry-webconsole/tests/test_webui_users.py +++ b/packaging/messagefoundry-webconsole/tests/test_webui_users.py @@ -309,6 +309,41 @@ async def test_the_console_create_shows_why_the_username_rule_refused(engine: En assert other.status_code == 400 and "invalid input" in other.text +async def test_the_console_create_does_not_run_the_rule_over_an_over_long_name( + engine: Engine, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #5520, the reason limb's cost: a name over the request model's length cap is refused + by the model without its rule running, and the console must not then run the rule over the + whole value on the event loop to find a reason. No call of the rule may see more than the cap; + the refusal stays "invalid input". The control is a refused name under the cap, whose reason is + still shown.""" + from messagefoundry.api import auth_models + from messagefoundry.auth import usernames + from messagefoundry_webconsole.routes import admin as console_admin + + seen: list[int] = [] + real = usernames.username_refusal + + def spy(name: str) -> str | None: + seen.append(len(name)) + return real(name) + + monkeypatch.setattr(auth_models, "username_refusal", spy) + monkeypatch.setattr(console_admin, "username_refusal", spy, raising=False) + service = await _service(engine) + async with _boss_client(engine, service) as c: + long = await _post_pairs( + c, "/ui/users", [("username", "a" * (1024 * 1024 - 4096)), ("email", "x@example.test")] + ) + control = await _post_pairs( + c, "/ui/users", [("username", "system"), ("email", "x@example.test")] + ) + assert long.status_code == 400 and "invalid input" in long.text + assert all(n <= 256 for n in seen), max(seen) + assert control.status_code == 400 + assert "reserved for the audit trail" in html.unescape(control.text) + + async def test_create_user_duplicate_rerenders_without_password(engine: Engine) -> None: service = await _service(engine) await _add(service, "op", Role.OPERATOR) diff --git a/tests/test_username_rule.py b/tests/test_username_rule.py index b34d73c974..cfbb85641c 100644 --- a/tests/test_username_rule.py +++ b/tests/test_username_rule.py @@ -101,7 +101,7 @@ "cli" + chr(0x0903) + "root", # DEVANAGARI SIGN VISARGA "cli" + chr(0x0A83) + "root", # GUJARATI SIGN VISARGA "cli" + chr(0x17D6) + "root", # KHMER SIGN CAMNUC PII KUUH - chr(0x1D236) + "oidc" + chr(0x1D237), # GREEK INSTRUMENTAL NOTATION SYMBOL-38/39 + chr(0x1D236) + "oidc" + chr(0x1D237), # GREEK INSTRUMENTAL NOTATION SYMBOL-40 and SYMBOL-42 ] #: The controls: names beside each refused form that the rule must leave alone. From 92c0ef14633e9804cf2174ada0a9b8c796899d39 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 19:37:16 -0600 Subject: [PATCH 10/12] Correct three statements from review round-a51283c38a - docs/SECURITY.md: the over-refusal sentence names the console twin of PUT roles, and says a directory account's role write was refused 400 before, not that it went ahead. - usernames.py: the rule folds no confusable letters in any script (not only across scripts); an over-long comment line wrapped. - console create route comment: an over-long name is never run through the rule (it is still echoed in the re-rendered form). Text only; no code change. BACKLOG #5520. --- docs/SECURITY.md | 10 ++++++---- messagefoundry/auth/usernames.py | 7 ++++--- messagefoundry_webconsole/routes/admin.py | 2 +- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 3e42519680..ab1a20a266 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1732,10 +1732,12 @@ or federated pair cannot make it vanish from these reads. One that keeps changin unreported. Honest writes that race all three checks the same way would be a false alarm too. **Two honest role writes to the account that commit across both of those reads are still answered as a failing record and reported**, a false alarm the reads cannot tell from -tampering, because the role rows are read apart from the account's row. Since -`PUT /users/{user_id}/roles` reads the account this way before it writes, that false alarm there -answers 423 and the role write does not happen, where before this read it would have gone ahead: -an over-refusal, kept by decision d20261123T150929936-d70a0b. Where +tampering, because the role rows are read apart from the account's row. Since BACKLOG #5520, +`PUT /users/{user_id}/roles`, and the console's `POST /ui/users/{user_id}/roles` that calls it, +read the account this way before they write, so that false alarm there refuses the role change +with the 423 (the console shows its text on a 400 page) and is reported as above. Before, a local +account's role write went ahead in that case, and a directory account's was refused 400: an +over-refusal, kept by decision d20261123T150929936-d70a0b. Where `[auth].require_action_step_up` is on, the default, `PATCH /users/{user_id}` reads the account after its gate has spent the single-use `admin_user_update` grant, so its 423 and its 404 cost that proof, as the console's `POST /ui/users/{user_id}/update` does after its own gate. So does its 422 diff --git a/messagefoundry/auth/usernames.py b/messagefoundry/auth/usernames.py index 1314f59262..3987ba4607 100644 --- a/messagefoundry/auth/usernames.py +++ b/messagefoundry/auth/usernames.py @@ -40,8 +40,8 @@ script pass too: ``cli:root`` spelled with a dotless i (U+0131), ```` spelled with the modifier low arrowheads U+02F1 and U+02F2, and ```` followed by a combining low line (U+0332). It matches the reserved forms after NFKC, -with the delimiter lookalikes that table lists taken to ASCII, and case folding; it does not fold -confusable letters across scripts. +with the delimiter lookalikes that table lists taken to ASCII, and case folding; it folds no +confusable letters, in any script. This docstring is the one statement of the rule; the request model, the service and docs/SECURITY.md point here rather than restate it. @@ -72,7 +72,8 @@ #: letters it lists (Canadian syllabics PA and PO, a runic letter and a Lisu tone letter), so a #: name in those scripts is not refused as a ``<...>`` form, though the modifier letters U+02D0, #: U+02F8, U+A789, U+02C2 and U+02C3 are kept; and U+FE30, which NFKC turns into two full stops -#: (``..``) rather than a colon. Applied after NFKC, which takes U+2329 and U+232A to U+3008 and U+3009. +#: (``..``) rather than a colon. Applied after NFKC, which takes U+2329 and U+232A to U+3008 +#: and U+3009. _DELIMITER_LOOKALIKES: Final = str.maketrans( dict.fromkeys( (0x02D0, 0x02F8, 0x0589, 0x05C3, 0x0703, 0x0704, 0x0903, 0x0A83, 0x16EC, 0x17D6, 0x1803) diff --git a/messagefoundry_webconsole/routes/admin.py b/messagefoundry_webconsole/routes/admin.py index fbd2a69ba5..214aaa2fbd 100644 --- a/messagefoundry_webconsole/routes/admin.py +++ b/messagefoundry_webconsole/routes/admin.py @@ -466,7 +466,7 @@ async def ui_user_create( # BACKLOG #5520 items 7 and 16: the username rule's reason is fixed text that never # echoes the value, so the form can say why; any other field keeps "invalid input". # Read from the model's own refusal rather than by running the rule again, so a name - # the length cap refused is never walked whole on the event loop. + # the length cap refused is never run through the rule. detail = _username_rule_reason(exc) or detail all_roles = await admin.list_roles(service=service, _=identity) return HTMLResponse( From f2d19c993630963f18260bed2a0862d1855ae119 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 12:06:04 -0600 Subject: [PATCH 11/12] Write the two sniff skip patterns as literals the regex scan reads Answers the Lander hold at 92c0ef14633e: the two leading-noise skip patterns in parsing/sniff.py were built by concatenation, so the static regex scan in test_security_static.py could not read them and test_the_scanners_blind_spots_are_the_recorded_ones went red. They are now literals, and test_the_written_out_noise_classes_match_the_noise_sets pins each class to its noise set byte by byte and code point by code point, so the literal cannot drift from _LEADING_WS / _LEADING_WS_STR. BACKLOG #5520 --- messagefoundry/parsing/sniff.py | 11 +++++++---- tests/test_sniff_head_copy.py | 13 +++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/messagefoundry/parsing/sniff.py b/messagefoundry/parsing/sniff.py index bd7302a7e2..78d4c7e7aa 100644 --- a/messagefoundry/parsing/sniff.py +++ b/messagefoundry/parsing/sniff.py @@ -67,8 +67,10 @@ def _looks_like_hl7(raw: bytes) -> bool: _LEADING_WS = b" \t\r\n\x0b\x0c" -#: The first byte that is not :data:`_LEADING_WS`, found in C without copying the body. -_PAST_LEADING_WS = re.compile(b"[^" + re.escape(_LEADING_WS) + b"]") +#: The first byte that is not :data:`_LEADING_WS`, found in C without copying the body. Written out +#: as a literal so the static regex scan in tests/test_security_static.py can read it; a test in +#: tests/test_sniff_head_copy.py pins its class to :data:`_LEADING_WS`. +_PAST_LEADING_WS = re.compile(rb"[^ \t\r\n\x0b\x0c]") #: How much of the body past the leading noise :func:`_sniff_head` returns: more than the longest #: signature any caller compares (the 8-byte PNG magic). @@ -99,8 +101,9 @@ def _sniff_head(raw: bytes, past_noise: re.Pattern[bytes] = _PAST_LEADING_WS) -> #: The first character that is not :data:`_LEADING_WS_STR`, found without copying the text, so a #: large decoded body with leading noise is not copied whole (BACKLOG #5520, filing review -#: finding 3). -_PAST_LEADING_WS_STR = re.compile("[^" + re.escape(_LEADING_WS_STR) + "]") +#: finding 3). A literal for the same reason as :data:`_PAST_LEADING_WS`, and pinned to +#: :data:`_LEADING_WS_STR` by the same test file. +_PAST_LEADING_WS_STR = re.compile(r"[^ \t\r\n\x0b\x0c]") def text_sniff_head(text: str) -> bytes: diff --git a/tests/test_sniff_head_copy.py b/tests/test_sniff_head_copy.py index 531d9abd7a..7551eda4b7 100644 --- a/tests/test_sniff_head_copy.py +++ b/tests/test_sniff_head_copy.py @@ -20,6 +20,7 @@ import pytest from messagefoundry.content_type import ContentType +from messagefoundry.parsing import sniff from messagefoundry.parsing.sniff import ( _content_matches_declared, nontext_upload_reason, @@ -111,3 +112,15 @@ def test_the_content_sniffs_read_the_same_head( ) -> None: """What the sniffs admit is unchanged.""" assert _content_matches_declared(content_type, body) is agrees + + +def test_the_written_out_noise_classes_match_the_noise_sets() -> None: + """The two skip patterns are literals so the static regex scan can read them; each must match + exactly what its noise set does not hold, so the literal cannot drift from the set.""" + for byte in range(256): + one = bytes([byte]) + assert (sniff._PAST_LEADING_WS.fullmatch(one) is None) == (one in sniff._LEADING_WS), byte + for code in [*range(0x3100), 0xFEFF, 0x10FFFF]: + char = chr(code) + skipped = sniff._PAST_LEADING_WS_STR.fullmatch(char) is None + assert skipped == (char in sniff._LEADING_WS_STR), code From f34a43f5f81639e416f69b00eac0c794c994c701 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 12:45:46 -0600 Subject: [PATCH 12/12] Review round-cdb2aacef0: pin every code point, escape the BOM, correct the noise-set comment The str pin now checks every code point, not a sample, so its claim that the literal cannot drift holds. The str skip pattern writes U+FEFF as an escape rather than a raw zero-width character (same compiled pattern). The _LEADING_WS_STR comment no longer claims one definition; it names the two literals and the test that holds them equal. BACKLOG #5520 --- messagefoundry/parsing/sniff.py | 5 +++-- tests/test_sniff_head_copy.py | 7 ++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/messagefoundry/parsing/sniff.py b/messagefoundry/parsing/sniff.py index 78d4c7e7aa..fd9ec4ac0b 100644 --- a/messagefoundry/parsing/sniff.py +++ b/messagefoundry/parsing/sniff.py @@ -91,7 +91,8 @@ def _sniff_head(raw: bytes, past_noise: re.Pattern[bytes] = _PAST_LEADING_WS) -> #: The str-domain twin of :data:`_LEADING_WS`, plus U+FEFF (what a UTF-8/UTF-16 BOM decodes to). Derived -#: from the byte set rather than retyped, so the tolerated leading noise has ONE definition. +#: from the byte set rather than retyped. The two skip patterns below restate both sets as regex +#: literals, and tests/test_sniff_head_copy.py holds each literal equal to its set. _LEADING_WS_STR = _LEADING_WS.decode("ascii") + "\ufeff" #: Characters of a decoded body that :func:`text_sniff_head` encodes. The longest text magic is three @@ -103,7 +104,7 @@ def _sniff_head(raw: bytes, past_noise: re.Pattern[bytes] = _PAST_LEADING_WS) -> #: large decoded body with leading noise is not copied whole (BACKLOG #5520, filing review #: finding 3). A literal for the same reason as :data:`_PAST_LEADING_WS`, and pinned to #: :data:`_LEADING_WS_STR` by the same test file. -_PAST_LEADING_WS_STR = re.compile(r"[^ \t\r\n\x0b\x0c]") +_PAST_LEADING_WS_STR = re.compile(r"[^ \t\r\n\x0b\x0c\ufeff]") def text_sniff_head(text: str) -> bytes: diff --git a/tests/test_sniff_head_copy.py b/tests/test_sniff_head_copy.py index 7551eda4b7..ad5e3db1df 100644 --- a/tests/test_sniff_head_copy.py +++ b/tests/test_sniff_head_copy.py @@ -115,12 +115,13 @@ def test_the_content_sniffs_read_the_same_head( def test_the_written_out_noise_classes_match_the_noise_sets() -> None: - """The two skip patterns are literals so the static regex scan can read them; each must match - exactly what its noise set does not hold, so the literal cannot drift from the set.""" + """_PAST_LEADING_WS and _PAST_LEADING_WS_STR are literals so the static regex scan can read + them; each must match exactly what its noise set does not hold, checked over every byte and + every code point, so the literal cannot drift from the set.""" for byte in range(256): one = bytes([byte]) assert (sniff._PAST_LEADING_WS.fullmatch(one) is None) == (one in sniff._LEADING_WS), byte - for code in [*range(0x3100), 0xFEFF, 0x10FFFF]: + for code in range(0x110000): char = chr(code) skipped = sniff._PAST_LEADING_WS_STR.fullmatch(char) is None assert skipped == (char in sniff._LEADING_WS_STR), code