Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
10a0b89
The anchor walk refuses a drive-relative spelling on every pass, not …
wshallwshall Nov 17, 2026
282f641
A passkey response nested past json's depth limit is the audited refusal
wshallwshall Nov 17, 2026
8a864bd
A sign-in naming a control character is refused at the body, before t…
wshallwshall Nov 17, 2026
0f27da8
The subst splice leaves its drive-relative refusal to the loop top
wshallwshall Nov 17, 2026
ed0f03e
Review round 1: refuse only a NUL username at sign-in, and correct tw…
wshallwshall Nov 17, 2026
cc3f538
Review round 2: catch RecursionError around the response parse only
wshallwshall Nov 17, 2026
39a5e13
The _invalid_response_errors docstring states the catch's real scope
wshallwshall Nov 17, 2026
907969a
Merge b613-c-authmisc onto main after PR 2999
wshallwshall Nov 17, 2026
83b6fcb
Console passkey routes refuse a too-deep body; sign-in name rule cove…
wshallwshall Nov 17, 2026
73aa44d
Review round 1: log the form's NUL refusal; correct three control claims
wshallwshall Nov 17, 2026
b0a2d19
Review round 2: every form sign-in refusal ends the passkey handle; c…
wshallwshall Nov 17, 2026
6441830
Correct four control claims in the auth-misc comments and docs
wshallwshall Nov 17, 2026
af28eb1
A malformed android-safetynet statement is a clean passkey refusal
wshallwshall Nov 17, 2026
daad647
Name the registration catch's exception tuple so strict mypy accepts it
wshallwshall Nov 17, 2026
dfebf99
Correct the sign-in name, NUL and refusal-path claims in comments and…
wshallwshall Nov 17, 2026
5e150df
Review round 1: narrow two webauthn claims, one source for the NUL fact
wshallwshall Nov 17, 2026
6c93192
The deep-nesting tests parse on a fixed 2 MiB thread stack
wshallwshall Nov 17, 2026
3a8e550
Merge origin/main into b613-s-authmisc
wshallwshall Nov 17, 2026
560fa02
The too-deep re-auth body expects the service's audited refusal
wshallwshall Nov 17, 2026
f2bc689
The form sign-in leaves a NUL name to the service's audited refusal
wshallwshall Nov 17, 2026
8ab5daf
A malformed attestation certificate is the audited passkey refusal, n…
wshallwshall Nov 17, 2026
46a4190
The JSON sign-in leaves a NUL name to the service's audited, charged …
wshallwshall Nov 17, 2026
593b49f
Both WebAuthn verify calls refuse on any exception from the library
wshallwshall Nov 17, 2026
a22238d
Sign-in NUL text names where the combined passkey sign-in is charged
wshallwshall Nov 17, 2026
b7b65e3
Sign-in NUL and passkey refusal prose cut to test pointers
wshallwshall Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 27 additions & 9 deletions docs/API-INPUT-VALIDATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,30 @@ It covers the control plane: the ids, connection names, time bounds and search t
client sends to the engine. It does not cover message payloads. Those are the data plane, and they
have their own documents: [HL7-VALIDATION.md](HL7-VALIDATION.md) and [CODESETS.md](CODESETS.md).

The rules live in one module, [`messagefoundry/api/validation.py`](../messagefoundry/api/validation.py).
The rules table below is quoted from it. `tests/test_api_input_validation.py` checks that six
phrases on this page still match the code, and fails if the page drops one. It does not check every
number on this page. The connection-name pattern is the one exception to where it is written:
it is defined in [`messagefoundry/connection_names.py`](../messagefoundry/connection_names.py) and
imported by that module, because the config loader enforces the same rule.
Most of the rules live in one module,
[`messagefoundry/api/validation.py`](../messagefoundry/api/validation.py), and most of the rules
table below is quoted from it. `tests/test_api_input_validation.py` checks that six phrases on this
page still match the code, and fails if the page drops one. It does not check every number on this
page. At least four rules in the table are written, in whole or in part, elsewhere. The
connection-name pattern is defined in
[`messagefoundry/connection_names.py`](../messagefoundry/connection_names.py) and imported by that
module, because the config loader enforces the same rule. The directory user name's NUL rule is
in `validation.py`, but its length bounds, 1 to 256 characters, are set on the request model in
[`messagefoundry/api/auth_models.py`](../messagefoundry/api/auth_models.py).
The HL7 field-path grammar is `parse_path` in
[`messagefoundry/parsing/peek.py`](../messagefoundry/parsing/peek.py). The layered preset ids'
pattern is in `validation.py`, but their 1024-character bound is set on the route in
[`messagefoundry/api/app.py`](../messagefoundry/api/app.py).

Two later sections quote rules held in other files: the items checked behind a route, and the rules
over two or more items. Each entry there names the code that holds its rule. No test compares those
sections with the code, so read the named code when a number matters.

A value that breaks one of these rules gets an HTTP 422 with the field named. The engine refuses it
before the value reaches a database query, a filesystem path, a log line or a CSV export.
A value that breaks one of these rules gets an HTTP 422 with the field named, except a malformed HL7
field path, which gets a 400: its rule is enforced outside the API models, as the note on the field
path below says.
Whatever the status, the value that breaks a rule is refused before it reaches a database query, a
filesystem path, a log line or a CSV export.

---

Expand All @@ -43,11 +54,18 @@ before the value reaches a database query, a filesystem path, a log line or a CS
| Audit action filter | Printable text, no control characters, 1 to 128 characters | `action` on `GET /audit` and `GET /audit/export` |
| Display label | Printable text, no control characters, 1 to 128 characters | `name` on `POST /search/presets` |
| Filesystem path | Printable text, no control characters, 1 to 4096 characters | `config_dir` on `POST /config/reload`, and `archive` on `POST /dr/activate` |
| Directory user name | No NUL, 1 to 256 characters. Pinned by `tests/test_auth_federated_identity_routes.py::test_the_directory_create_refuses_a_nul_in_the_name_before_the_directory` | `username` on `POST /users/directory` |
| Layered preset ids | Resource ids joined by single commas with no spaces, up to 1024 characters in all | `presets` on `GET /search/layered` |

The email-address row covers `recipient_override` only. The account email fields follow a different
rule, set out under [Items checked a second time](#items-checked-a-second-time-behind-the-route).

A NUL in a sign-in name (vault BACKLOG #5342): behaviour pinned by
`tests/test_api_auth.py::test_login_answers_a_nul_username_as_an_audited_unknown_name`,
`tests/test_auth_hardening.py::test_a_username_with_a_nul_is_an_unknown_name_on_both_sign_in_surfaces`,
and, in the web console suite,
`packaging/messagefoundry-webconsole/tests/test_ui_passkey_body_refusals.py`.

"Printable text, no control characters" means every character except the C0 range, DEL, and the C1
range. In practice: no NUL, no tab, no carriage return, no line feed.

Expand Down Expand Up @@ -339,7 +357,7 @@ replace it.** The first two are below. The third is the DR archive path, under
2. A log `level` is checked against the engine's own level names, which is why a wrong one gets a
400. The shape rule only keeps an arbitrary-length string out of that error message.

**One rule is documented here but enforced elsewhere.** The HL7 field path grammar belongs to
**The field path is documented here but enforced elsewhere.** The HL7 field path grammar belongs to
`messagefoundry.parsing.peek.parse_path`, and `messagefoundry.store.content_search.make_spec` applies
it at every point the API accepts a `field_path`. A malformed path is already a 400. Copying that
pattern into the API models would create a second definition of a rule that has one.
Expand Down
7 changes: 6 additions & 1 deletion messagefoundry/api/auth_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from messagefoundry.api.request_model import RequestModel
from messagefoundry.api.validation import (
MAX_MAP_ENTRIES,
SIGN_IN_NAME_PATTERN,
ChannelScopeEntry,
PermissionId,
RoleId,
Expand Down Expand Up @@ -55,6 +56,8 @@ class CredentialReply(BaseModel):


class LoginRequest(RequestModel):
# A NUL in ``username`` (vault BACKLOG #5342): behaviour pinned by
# tests/test_api_auth.py::test_login_answers_a_nul_username_as_an_audited_unknown_name.
username: str = Field(max_length=_NAME_MAX)
password: str = Field(max_length=_PASSWORD_MAX)
provider: str = Field(default="local", max_length=16) # 'local' | 'ad'
Expand Down Expand Up @@ -321,7 +324,9 @@ class DirectoryUserCreateRequest(RequestModel):
cannot point the holder's notices away from the directory's (ASVS 6.3.7).
"""

username: str = Field(min_length=1, max_length=_NAME_MAX)
# vault BACKLOG #5342. Pinned by tests/test_auth_federated_identity_routes.py::
# test_the_directory_create_refuses_a_nul_in_the_name_before_the_directory.
username: str = Field(min_length=1, max_length=_NAME_MAX, pattern=SIGN_IN_NAME_PATTERN)
notify_email: str | None = Field(default=None, max_length=_NAME_MAX)


Expand Down
5 changes: 5 additions & 0 deletions messagefoundry/api/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,11 @@
#: Printable text: no C0 control, no DEL, no C1 control. One or more characters.
PRINTABLE_TEXT_PATTERN = r"^[^\x00-\x1f\x7f-\x9f]+$"

#: Any text without a NUL, empty included (vault BACKLOG #5342). Pinned by
#: tests/test_auth_federated_identity_routes.py::
#: test_the_directory_create_refuses_a_nul_in_the_name_before_the_directory.
SIGN_IN_NAME_PATTERN = r"^[^\x00]*$"

#: A member of one of the engine's own closed vocabularies -- ``MessageStatus``, ``OutboxStatus``,
#: the connection-event kinds. Every member of all three is letters and underscores only. The
#: vocabulary itself stays the store's to define; this is the shape a member can have.
Expand Down
12 changes: 9 additions & 3 deletions messagefoundry/auth/anchor_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,8 @@ def windows_chain(

At least these end the walk with a cause, since Windows would open another object than the text
names (vault BACKLOG #5197): a drive-relative spelling (:func:`_drive_relative`), in the path, a
link target or a ``subst`` target joined to the rest of the path; a name ending in a space or a
link target or a ``subst`` target joined to the rest of the path, or in the path joined to the
working directory (vault BACKLOG #5337); a name ending in a space or a
dot; and a link target rooted with no drive (:data:`_ROOTED_LINK`); a
device prefix written with forward slashes (``//?/S:/x``); and a stream name after a link.

Expand Down Expand Up @@ -680,6 +681,12 @@ def add(obj: str, kind: str) -> None:
if len(drive) != 2 and not rest:
# A volume GUID with no separator after it (``//?/Volume{x}``) opens the volume device.
return chain, WalkCause.plain(_DEVICE_PATH)
if _drive_relative(norm):
# Checked on every pass, not only on the text the caller gave: a drive-relative working
# directory (``C:``) joined to ``ca.pem`` reads ``C:ca.pem``, which the loop below
# would walk from the drive root, and which a subst splice would join to its target
# with no separator (vault BACKLOG #5337). So ``rest`` below is rooted or empty.
return chain, WalkCause.plain(_DRIVE_RELATIVE)
try:
substituted = drive_target(drive) if len(drive) == 2 else None
except OSError as exc:
Expand All @@ -700,9 +707,8 @@ def add(obj: str, kind: str) -> None:
)
# The target with the rest of the path, not the target alone: a letter defined onto a
# bare drive (``\??\C:``) makes ``S:\ca.pem`` read as ``C:\ca.pem``, which is rooted.
# A drive-relative result (``\??\C:certs``) is refused at the top of the next pass.
pending = target + rest
if _drive_relative(pending):
return chain, WalkCause.plain(_DRIVE_RELATIVE)
continue
root = drive + "\\"
why = volume_cause(root)
Expand Down
3 changes: 2 additions & 1 deletion messagefoundry/auth/usernames.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
U+2800 among them), or when it takes one of the forms the audit trail writes for its own
synthetic actors (:data:`RESERVED_ACTOR_FORMS`). An account named
``system`` would otherwise be indistinguishable from the engine in ``GET /audit?actor=system``
and in an audit export, and a NUL would reach a store that cannot hold one.
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.

Expand Down
42 changes: 21 additions & 21 deletions messagefoundry/auth/webauthn.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,15 +167,17 @@ def _supported_pub_key_algs() -> list[COSEAlgorithmIdentifier]:


def _invalid_input_errors() -> tuple[type[Exception], ...]:
"""Every exception py_webauthn raises for bad input, which must all reach the audited path.
"""Exceptions py_webauthn raises for bad input. Behaviour pinned by tests/test_webauthn.py::
test_an_unusable_stored_key_fails_the_assertion_audited_not_raised.

``WebAuthnException`` is the library's own base class. The other three entries catch four raw
``WebAuthnException`` is the library's own base class. The next three entries catch four raw
exception types (``LookupError`` covers both ``KeyError`` and ``IndexError``) that it lets
out when a COSE key is malformed rather than merely wrong: its key decoder indexes an
untyped CBOR value, so a missing label is a ``KeyError``, a short array an ``IndexError``, a
bare integer a ``TypeError``, and a point that is not on its stated curve a ``ValueError`` from
``cryptography``. Measured at engine ``0076e3cec`` on the pinned ``webauthn==3.0.0`` (BACKLOG
#1166). Each is attacker-shaped input, so each must land on the audited invalid-input path ADR
``cryptography``. Measured at engine ``0076e3cec`` on ``webauthn`` 3.0.0 (BACKLOG #1166);
``pyproject.toml`` allows ``webauthn>=3.0.0,<4`` and ``requirements.lock`` pins 3.0.1.
Each is attacker-shaped input, so each must land on the audited invalid-input path ADR
0068 decision 1 requires rather than escape as a 500. Use it only around library calls, never
around our own logic, where the same exceptions would mean a bug.

Expand Down Expand Up @@ -579,20 +581,20 @@ def verify_registration(
_require_webauthn()
from webauthn import verify_registration_response

supported_algs = _supported_pub_key_algs()
try:
verified = verify_registration_response(
credential=response_json,
expected_challenge=challenge,
expected_rp_id=rp_id,
expected_origin=origin,
supported_pub_key_algs=_supported_pub_key_algs(),
supported_pub_key_algs=supported_algs,
)
except _invalid_input_errors() as exc:
# The BASE class, deliberately (PR-A review HIGH): structurally-malformed browser input
# raises siblings of InvalidRegistrationResponse (InvalidJSONStructure, InvalidCBORData,
# ...) — every library-side rejection must land on the audited return-False/400 path,
# never an unhandled 500. The raw decode errors join it for the same reason (BACKLOG
# #1166): a malformed COSE key raised them straight out of this call.
except Exception as exc:
# vault BACKLOG #5341. Pinned by tests/test_webauthn.py::
# test_a_deeply_nested_registration_response_is_the_audited_refusal,
# test_a_malformed_safetynet_statement_is_the_audited_refusal and
# test_a_malformed_attestation_certificate_is_the_audited_refusal.
raise _refusal(exc, ceremony="registration") from exc
_require_usable_public_key(verified.credential_public_key, ceremony="registration")
return RegistrationResult(
Expand Down Expand Up @@ -685,12 +687,9 @@ def verify_assertion(
credential_public_key=public_key,
credential_current_sign_count=current_sign_count,
)
except _invalid_input_errors() as exc:
# The BASE class, deliberately (PR-A review HIGH): malformed input raises siblings of
# InvalidAuthenticationResponse — every rejection lands audited, never a 500. The
# sign-count regression message ("...sign count...") still rides through for the
# service's clone-signal classification. The raw types stay caught although the stored
# key was screened above: the response itself is attacker input too.
except Exception as exc:
# vault BACKLOG #5341. Pinned by tests/test_webauthn.py::
# test_a_deeply_nested_assertion_response_is_the_audited_refusal.
raise _refusal(exc, ceremony="assertion") from exc
return AssertionResult(verified.new_sign_count, bool(verified.user_verified))

Expand Down Expand Up @@ -780,11 +779,12 @@ def resident_key_from_response(response_json: str) -> bool | None:

def _transports_from_response(response_json: str) -> list[str] | None:
"""Best-effort ``response.transports`` extraction (browser hint — absence is fine)."""
try:
parsed = json.loads(response_json)
transports = parsed.get("response", {}).get("transports")
except (ValueError, AttributeError): # pragma: no cover - verify_registration already parsed
# vault BACKLOG #5341.
parsed, refused = json_loads_or_refusal(response_json)
if refused is not None or not isinstance(parsed, dict):
return None
response = parsed.get("response")
transports = response.get("transports") if isinstance(response, dict) else None
if isinstance(transports, list) and all(isinstance(t, str) for t in transports):
return list(transports) or None
return None
19 changes: 13 additions & 6 deletions messagefoundry_webconsole/routes/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,7 @@
return await auth.identity_for_token(token, activity=False) is None


def register(app: FastAPI, deps: UiDeps) -> None:

Check warning on line 608 in messagefoundry_webconsole/routes/core.py

View workflow job for this annotation

GitHub Actions / complexity triage (advisory)

Complexity increased

`register` complexity 159 -> 160 (mccabe threshold 10)
"""Register the phase-0 /ui routes (login, dashboard, messages, dead-letters, replay,
reauth). Runs first in ``_UI_REGISTRARS``; a page lane adds its own
``_register_<area>(app)`` + one tuple entry below, so parallel lanes never edit this
Expand Down Expand Up @@ -764,10 +764,20 @@
# selector, and "ad" stays in the allow-list only so the ENGINE (_dispatch_login) is the
# single point that refuses and audits it. Directory accounts sign in by Windows SSO or
# OIDC, and the AD bind as the user survives only as the step-up re-bind at /ui/reauth
# (and the JSON /me/reauth).
# (and the JSON /me/reauth). A NUL name (BACKLOG #5342): pinned by
# test_ui_passkey_body_refusals.py::test_the_form_sign_in_refuses_a_nul_username_before_the_store.

def _refused() -> Response:
# Pinned by test_ui_passkey_body_refusals.py::
# test_the_combined_passkey_sign_in_refuses_a_nul_username_and_ends_its_challenge.
refused = RedirectResponse("/ui/login?e=bad", status_code=303)
if handle:
clear_passkey_sign_in_cookie(refused, request)
return refused

provider_value = form.get("provider", "local")
if provider_value not in ("local", "ad"):
return RedirectResponse("/ui/login?e=bad", status_code=303)
return _refused()
# ADR 0197 Amendment A, wave 2: the combined passkey sign-in. The assertion rides the form,
# the handle of its challenge the cookie the begin leg set; both or neither. Clamped, so an
# oversized assertion is simply an invalid one.
Expand Down Expand Up @@ -795,10 +805,7 @@
passkey_challenge=staged.challenge if staged is not None else None,
)
if not outcome.ok or outcome.token is None:
refused = RedirectResponse("/ui/login?e=bad", status_code=303)
if handle:
clear_passkey_sign_in_cookie(refused, request)
return refused
return _refused()
# A must-change account goes straight to the browser rotation page (L4b) — every other
# /ui route would bounce it there anyway (require_ui). An MFA-pending session lands on the
# second-factor page for the same reason (ASVS 6.3.3). must_change comes first for an
Expand Down
Loading
Loading