diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 7bec8504a5..813eff7dc0 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1667,14 +1667,14 @@ 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 | | `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` | | `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 @@ -1730,12 +1732,19 @@ 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 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 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, 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 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/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/service.py b/messagefoundry/auth/service.py index 692c4e0fc4..e370b0efb7 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -2309,13 +2309,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: @@ -13769,8 +13770,12 @@ 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, 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 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/auth/usernames.py b/messagefoundry/auth/usernames.py index 97ee288dab..3987ba4607 100644 --- a/messagefoundry/auth/usernames.py +++ b/messagefoundry/auth/usernames.py @@ -5,8 +5,16 @@ 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 ``POST /users`` refuses a name it refuses. The console's +``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``), +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 +28,20 @@ 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 +``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. 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. 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 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. @@ -48,6 +64,33 @@ #: 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. 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 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) + + (0x1809, 0x205A, 0x2236, 0xA789), + ":", + ) + | dict.fromkeys((0x02C2, 0x2039, 0x276C, 0x276E, 0x27E8, 0x3008, 0x1D236), "<") + | dict.fromkeys((0x02C3, 0x203A, 0x276D, 0x276F, 0x27E9, 0x3009, 0x1D237), ">") +) + + +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 +166,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/messagefoundry/parsing/sniff.py b/messagefoundry/parsing/sniff.py index dcdeddcf99..fd9ec4ac0b 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 @@ -41,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)? @@ -50,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 @@ -65,15 +67,32 @@ def _looks_like_hl7(raw: bytes) -> bool: _LEADING_WS = b" \t\r\n\x0b\x0c" -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 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). +_SNIFF_HEAD_BYTES = 16 + + +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_noise.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 -#: 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 @@ -81,6 +100,12 @@ 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). 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\ufeff]") + def text_sniff_head(text: str) -> bytes: """UTF-8 head bytes of an already-DECODED body, to hand to :func:`_content_matches_declared`. @@ -96,7 +121,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: @@ -116,7 +143,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, @@ -127,9 +154,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 @@ -169,9 +196,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 @@ -217,7 +244,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 935ed408c0..c108ce62be 100644 --- a/messagefoundry/transports/file.py +++ b/messagefoundry/transports/file.py @@ -2674,9 +2674,9 @@ 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 -# 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/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/messagefoundry_webconsole/routes/admin.py b/messagefoundry_webconsole/routes/admin.py index 5a5d6a83c1..214aaa2fbd 100644 --- a/messagefoundry_webconsole/routes/admin.py +++ b/messagefoundry_webconsole/routes/admin.py @@ -247,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. @@ -450,6 +462,12 @@ 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". + # Read from the model's own refusal rather than by running the rule again, so a name + # 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( pages.user_new_page( 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/packaging/messagefoundry-webconsole/tests/test_webui_users.py b/packaging/messagefoundry-webconsole/tests/test_webui_users.py index 9e50f451a4..a212ac897b 100644 --- a/packaging/messagefoundry-webconsole/tests/test_webui_users.py +++ b/packaging/messagefoundry-webconsole/tests/test_webui_users.py @@ -284,6 +284,66 @@ 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_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_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", [ 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_sniff_head_copy.py b/tests/test_sniff_head_copy.py new file mode 100644 index 0000000000..ad5e3db1df --- /dev/null +++ b/tests/test_sniff_head_copy.py @@ -0,0 +1,127 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""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 import sniff +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(call: Callable[[], object]) -> int: + tracemalloc.start() + try: + tracemalloc.reset_peak() + call() + return tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + + +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(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( + "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), + (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: + """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: + """_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(0x110000): + char = chr(code) + skipped = sniff._PAST_LEADING_WS_STR.fullmatch(char) is None + assert skipped == (char in sniff._LEADING_WS_STR), code 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.py b/tests/test_user_seal.py index 1f7bb2b516..79d62ebfc1 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( diff --git a/tests/test_user_seal_routes.py b/tests/test_user_seal_routes.py index ccee7b6f1b..127e47c6f6 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, 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 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 diff --git a/tests/test_username_rule.py b/tests/test_username_rule.py index a36d986337..cfbb85641c 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,28 @@ "\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>", + "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-40 and SYMBOL-42 ] #: The controls: names beside each refused form that the rule must leave alone. @@ -98,6 +122,13 @@ "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", + # 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), ] @@ -111,6 +142,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):