From cf26cceee46fe3d17628f63aea0f838b17b81fe3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 20:29:36 -0600 Subject: [PATCH 01/19] Pace the cost-bearing monitoring:read GETs per actor Vault BACKLOG #1191 (ASVS 15.2.2), monitoring:read pacing limb, under the Manager's rulings of 2026-11-22. A new gate, require_monitoring_read, charges a per-actor sliding window at admission on GET /graph/edges, /status, /stats, /metrics, /metrics/history and /connections: 429 with the actor's Retry-After, a WARNING, and an auth.gate_refused row with reason throttled. New [auth] knobs monitoring_read_rate_limit_enabled, _per_actor (600), _global (0 = off) and _window_seconds (60). The measured basis of the default is in docs/SECURITY.md, "Monitoring-read pacing". A looser value is named by security_loosenings(). The console's in-process calls into these handlers are not charged; that is left open. --- docs/CONFIGURATION.md | 4 + docs/SECURITY-LOOSENING.md | 20 ++- docs/SECURITY.md | 68 +++++++-- messagefoundry/api/app.py | 13 +- messagefoundry/api/security.py | 39 +++++ messagefoundry/auth/service.py | 24 +++ messagefoundry/config/settings.py | 47 ++++++ tests/test_derived_gate_decision_audit.py | 12 +- tests/test_docs_security_pathways.py | 1 + tests/test_monitoring_read_pacing.py | 172 ++++++++++++++++++++++ tests/test_security_doc_drift.py | 10 +- tests/test_security_doc_rate_limits.py | 12 +- tests/test_security_posture_defaults.py | 23 +++ 13 files changed, 413 insertions(+), 32 deletions(-) create mode 100644 tests/test_monitoring_read_pacing.py diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 737f6c8885..0071db6fab 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -829,6 +829,10 @@ document ([SECURITY-DOCS-POLICY.md](SECURITY-DOCS-POLICY.md)). | `phi_read_rate_limit_per_actor` | int | 120 | max PHI reads per user per window (generous — clears console/human use; `0` disables this dimension) | | `phi_read_rate_limit_global` | int | 0 | max PHI reads across all users per window (`0` = off) | | `phi_read_rate_limit_window_seconds` | float | 60 | sliding-window length | +| `monitoring_read_rate_limit_enabled` | bool | `true` | per-actor pace on the six cost-bearing `monitoring:read` GETs (vault BACKLOG #1191, ASVS 15.2.2), charged at admission by `require_monitoring_read`; the routes, the key and the measured basis of the default are in [SECURITY.md](SECURITY.md), *Monitoring-read pacing* | +| `monitoring_read_rate_limit_per_actor` | int | 600 | max monitoring reads per user per window (`0` disables this dimension) | +| `monitoring_read_rate_limit_global` | int | 0 | max monitoring reads across all users per window (`0` = off) | +| `monitoring_read_rate_limit_window_seconds` | float | 60 | sliding-window length; must be above `0` | | `admin_write_rate_limit_enabled` | bool | `true` | per-actor anti-automation pacing on the **state-changing admin surface** (ASVS 2.4.2) — **NON-GET only**, charged from one per-actor bucket by `require_step_up`, `require_step_up_action` and `require_paced`. Charged on the `/ui` surface too, by `require_ui` -- the console reaches the handlers in-process, so it re-applies the floor rather than inheriting it ([BACKLOG #287](BACKLOG.md)) | | `admin_write_rate_limit_per_actor` | int | 12 | max state-changing admin writes per actor per window (`0` disables this dimension; a negative value is refused at load); there is deliberately **no global arm** — one operator's bulk work must never throttle another's | | `admin_write_rate_limit_window_seconds` | float | 15.0 | sliding-window length, above 0. The default is a **provisional** human-timing floor ([BACKLOG #287](BACKLOG.md)). A script making more than 12 admin writes in 15 s is refused. Over budget → `429` + a `Retry-After` naming the caller's own wait, the same on the JSON API and the `/ui` console ([SECURITY.md](SECURITY.md), *The write floor's `Retry-After` is the actor's real wait*), refused before any further work | diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index 7e430bc3d6..1bcf0370d7 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -229,6 +229,7 @@ Earlier versions of this guide called this an open owner question. The 2026-10-2 | | `[auth].login_rate_limit_enabled`, `login_rate_limit_per_ip`, `login_rate_limit_global`, `login_rate_limit_window_seconds` | `true` / `10` / `60` / `60` s (`false`, a count of `0` or above its default, or a window below `60` s is named, and `0` or a window of `0` or less turns a limit off) | | | `[auth].lockout_minutes`, `lockout_threshold`, `lockout_max_minutes` | `15` / `5` / `1440` (minutes below `15` or a ceiling below `1440` is named, and so is a threshold above `5`; minutes of `0` or less means no lock ever holds) | | | `[auth].phi_read_rate_limit_enabled`, `phi_read_rate_limit_per_actor`, `phi_read_rate_limit_window_seconds` | `true` / `120` / `60` s (`false`, a count of `0` or above `120`, or a window below `60` s) | +| | `[auth].monitoring_read_rate_limit_enabled`, `monitoring_read_rate_limit_per_actor`, `monitoring_read_rate_limit_window_seconds` | `true` / `600` / `60` s (`false`, a count of `0` or above `600`, or a window below `60` s) | | | `[auth].admin_write_rate_limit_enabled`, `admin_write_rate_limit_per_actor`, `admin_write_rate_limit_window_seconds`, `admin_write_min_interval_seconds` | `true` / `12` / `15` s / `0.15` s (`false`, a count of `0` or above `12`, a window below `15` s, or a gap below `0.15` s) | | | `[auth].mfa_verify_min_elapsed_seconds`, `oidc_callback_min_elapsed_seconds` | `1.0` s / `1.0` s (*conditional* — the second a loosening only with OIDC on; a floor below `1.0` s, and `0` turns it off) | | | `[auth].oidc_callback_floor_exempt_amr` | `[]` (*conditional* — a loosening only with OIDC on and the callback floor on; any value listed) | @@ -271,7 +272,8 @@ Earlier versions of this guide called this an open owner question. The 2026-10-2 `[auth].ad_connect_timeout`, `[auth].ad_receive_timeout`, `[auth].ad_group_search_deadline`, `[auth].admin_new_ip_step_up`, `[auth].require_action_step_up`, the three `[auth].password_check_*` keys, the four `[auth].login_rate_limit_*` keys, the three `[auth].lockout_*` -keys, the three named `[auth].phi_read_rate_limit_*` keys, the four `[auth].admin_write_*` keys, +keys, the three named `[auth].phi_read_rate_limit_*` keys, the three named +`[auth].monitoring_read_rate_limit_*` keys, the four `[auth].admin_write_*` keys, `[auth].mfa_verify_min_elapsed_seconds`, `[auth].oidc_callback_min_elapsed_seconds`, `[auth].oidc_callback_floor_exempt_amr`, `[auth].max_sessions_per_user`, `[auth].oidc_flow_cache_max`, @@ -1166,6 +1168,22 @@ count is above `0` (vault BACKLOG #2613). `[security].allowed_client_networks`, and review the PHI-access audit rows. - **Reversible:** yes, immediately — restore the default (or delete the line) and restart. +### `[auth].monitoring_read_rate_limit_*` looser than its default — monitoring reads go less paced +> No sign-in condition applies (vault BACKLOG #1191, ASVS 15.2.2). Named: +> `monitoring_read_rate_limit_enabled = false`; a `monitoring_read_rate_limit_window_seconds` below +> `60` s; a `monitoring_read_rate_limit_per_actor` of `0` (off) or above `600`. The window cannot be +> `0` or less (the load refuses it). With the limiter off, its parts are not named again. +> `monitoring_read_rate_limit_global` ships **off** (`0`), so no value of it is looser than the +> default and it is never named. +- **What you lose:** the per-account pace on the cost-bearing `monitoring:read` GETs + ([SECURITY.md](SECURITY.md), *Monitoring-read pacing*, names them). One signed-in account can make + the engine rebuild the wiring graph and scan the store faster, up to as fast as it answers. +- **When acceptable:** a monitoring tool on one known account that polls faster than the default + allows, on a host no untrusted client can reach. Prefer a modest raise to turning it off. +- **Compensating controls:** keep sessions short, and restrict who reaches the API with + `[security].allowed_client_networks`. +- **Reversible:** yes, immediately — restore the default (or delete the line) and restart. + ### `[auth].admin_write_*` looser than its default — state-changing admin actions go less paced > No sign-in condition applies ([BACKLOG #1131](BACKLOG.md), ASVS 2.4.2). Named: > `admin_write_rate_limit_enabled = false`; an `admin_write_rate_limit_window_seconds` below `15` s; an diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 15f9e09876..70dbddc068 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1440,15 +1440,16 @@ route handler only when all of them pass. export skips such a row instead (*Single-route data rules* below). Connection control and inbound injection return **403**. Denials are audited `auth.channel_denied`. -The table below has **seven** rows. `require` is the ladder itself; five wrappers extend it -(`require_paced`, `require_phi_read`, `require_step_up`, `require_step_up_action`, and the shared +The table below has **eight** rows. `require` is the ladder itself; six wrappers extend it +(`require_monitoring_read`, `require_paced`, `require_phi_read`, `require_step_up`, `require_step_up_action`, and the shared `require_reauth_only`/`require_reauth_only_action` row); `require_service_cert` deliberately **bypasses** it — a separate, cert-only identity plane where none of `require`'s session concerns apply. What each **adds** over plain `require()`: | Gate wrapper | Routes | What it adds over `require()` | |---|---|---| -| `require` | 42 | nothing — the ladder itself | +| `require` | 36 | nothing — the ladder itself | +| `require_monitoring_read` | 6 | the per-actor monitoring-read pace (`allow_monitoring_read`), 429 + a `Retry-After` naming the actor's wait (the whole window while the global count is spent); see *Monitoring-read pacing* | | `require_paced` | 17 | the **new-client-IP** refusal (403 + `X-Step-Up-Required: 1`, vault BACKLOG #2620), then per-actor anti-automation pacing on **non-GET** requests (`allow_admin_write`), 429 + a `Retry-After` naming the actor's wait | | `require_phi_read` | 8 | the ADR 0092 PHI-read hop refusal (`enforce_phi_read_hop`) **before** any identity work, then the **new-client-IP** refusal (403 + `X-Step-Up-Required: 1`, vault BACKLOG #2620), then the per-actor PHI-read budget, 429 + a `Retry-After` naming the actor's wait (the whole window while the global count is spent) | | `require_step_up` | 23 | the same non-GET pacing, then the **MFA gate** (403 + `X-MFA-Required: 1`), the **new-client-IP** signal, and the credential-recency window (403 + `X-Step-Up-Required: 1`) | @@ -1762,17 +1763,17 @@ exempt like any other, and the save re-seals the row as it always has. |---|---|---|---| | `GET` | `/security/posture` | `monitoring:read` | `require` | | `GET` | `/channels` | `monitoring:read` | `require` | -| `GET` | `/connections` | `monitoring:read` | `require` — `error` gated on `messages:view_summary` and masked; the `reveal=` act also needs `messages:view_summary` (BACKLOG #2443) | +| `GET` | `/connections` | `monitoring:read` | `require_monitoring_read` — `error` gated on `messages:view_summary` and masked; the `reveal=` act also needs `messages:view_summary` (BACKLOG #2443) | | `GET` | `/connections/{name}/metadata` | `monitoring:read` | `require` — per-channel for inbound; a shared outbound is barred to scoped users; credentials scrubbed unconditionally; `error` gated on `messages:view_summary` and masked; the `reveal=true` act also needs `messages:view_summary` (BACKLOG #2443) | | `GET` | `/events` | `monitoring:read` | `require` — data rule: *Single-route data rules* below (BACKLOG #1151) | | `GET` | `/connections/{name}/events` | `monitoring:read` | `require` | -| `GET` | `/stats` | `monitoring:read` | `require` | -| `GET` | `/metrics` | `monitoring:read` | `require` | -| `GET` | `/metrics/history` | `monitoring:read` | `require` | -| `GET` | `/graph/edges` | `monitoring:read` | `require` | +| `GET` | `/stats` | `monitoring:read` | `require_monitoring_read` | +| `GET` | `/metrics` | `monitoring:read` | `require_monitoring_read` | +| `GET` | `/metrics/history` | `monitoring:read` | `require_monitoring_read` | +| `GET` | `/graph/edges` | `monitoring:read` | `require_monitoring_read` | | `GET` | `/alerts/rules` | `monitoring:read` | `require` | | `GET` | `/config/provenance` | `monitoring:read` | `require` | -| `GET` | `/status` | `monitoring:read` | `require` — data rule: *Single-route data rules* below (BACKLOG #1151) | +| `GET` | `/status` | `monitoring:read` | `require_monitoring_read` — data rule: *Single-route data rules* below (BACKLOG #1151) | | `GET` | `/cluster/status` | `monitoring:read` | `require` | | `GET` | `/cluster/nodes` | `monitoring:read` | `require` | | `GET` | `/dr/status` | `monitoring:read` | `require` | @@ -5034,6 +5035,7 @@ slack. | Live directory group membership vs. the session's channel scope | the AD groups returned by that same reconciliation probe, mapped through the AD-group→channel-scope map, decided by `decide_ad_channel_scope` (the function login applies) | on a **successful (PRESENT)** probe, the directory would withdraw the stored scope or drop a channel from it — a **single** pass, **no** strike accrual. A widened scope, an administrator's scope with no mapped group, and an Administrator do not fire. A group ADD can fire: a matching group replaces an administrator's scope, so it narrows one the group does not cover | **DENY** by revocation of every session for that account, `auth.ad_session_revoked` with `reason = scope_changed`. The pass never writes the scope; the next login does (ADR 0198). A principal whose roles also changed is revoked once, under the row above, so it is one count against the mass-revoke breaker | **300 s** (same loop; `0` disables it) | `[auth].ad_session_recheck_seconds` | | Live directory mass-revoke breaker | the size of one pass's revocation set vs the probed population | the set exceeds **both** `ad_session_revoke_max` (**5**) **and** `ad_session_revoke_max_fraction` (**0.34**) — a second **binary** predicate layered on the three rows above, never a score (see "Directory session reconciliation") | **LOG** — the pass aborts revoking **nothing**, logs at ERROR and writes an `auth.ad_reconcile_aborted` audit row + loud alert | 5 / 0.34 | `[auth].ad_session_revoke_max`, `ad_session_revoke_max_fraction` | | PHI-read volume, per actor | `identity.user_id` | > 120 reads (`phi_read_rate_limit_per_actor`) per 60 s (`phi_read_rate_limit_window_seconds`); the global dimension `phi_read_rate_limit_global` defaults to `0` = **off** | **THROTTLE** 429 + a `Retry-After` naming the actor's wait (the whole window while `phi_read_rate_limit_global` is spent), charged at **admission** before any store work. WARNING-logged on the JSON API; the `/ui` `phi=True` arm is not (see *The console's refusal differs from the JSON floor's*) | on, 120 / 60 s | `[auth].phi_read_rate_limit_enabled` | +| Monitoring-read volume, per actor | `identity.user_id` | > 600 reads (`monitoring_read_rate_limit_per_actor`) per 60 s (`monitoring_read_rate_limit_window_seconds`) across the six routes *Monitoring-read pacing* names; the global dimension `monitoring_read_rate_limit_global` defaults to `0` = **off** | **THROTTLE** 429 + a `Retry-After` naming the actor's wait (the whole window while `monitoring_read_rate_limit_global` is spent), charged at **admission**. WARNING-logged | on, 600 / 60 s | `[auth].monitoring_read_rate_limit_enabled` | | Admin-write rate, per actor | `identity.user_id` × request method | **non-GET only**; > 12 writes (`admin_write_rate_limit_per_actor`) per 15 s (`admin_write_rate_limit_window_seconds`), or a write less than 0.15 s after the actor's last admitted one (`admin_write_min_interval_seconds`, BACKLOG #2301), both provisional human-timing defaults; no global dimension (`glob=0`) | **THROTTLE** 429 + a `Retry-After` naming the actor's wait, the same on the JSON API and on `/ui`. Charged on the JSON API and on `/ui`, which re-applies it. WARNING-logged on the JSON API; the `/ui` refusal is not (see *The console's refusal differs from the JSON floor's*) | on, 12 writes / 15 s | `[auth].admin_write_rate_limit_enabled` | | Time from sign-in to the second factor | `session.created_at` vs the service's wall clock, while `session.mfa_verified_at` is unset | a TOTP or recovery code (`verify_mfa`), a passkey assertion, or an enrolment (`confirm_mfa_enrollment`, `finish_webauthn_registration`, BACKLOG #2389) that completes an MFA-pending session less than 1 s after the session was minted (`mfa_verify_min_elapsed_seconds`, BACKLOG #2301), a provisional human-timing default; a session whose factor is already satisfied, or that owes none, is not floored | **DENY** with the leg's ordinary failure, which says nothing about timing, though a caller that knows its proof is good, or resubmits it, can tell the floor fired (the answers per leg, and the tells, are under *Two second steps have a time floor too*); audited `auth.mfa_failed` or `auth.webauthn_failed` with `reason=too_early`, and `phase=enroll` on an enrolment, except a code the console refuses at the JSON model's length bound first, at least on `POST /ui/mfa`, `POST /ui/reauth` and `POST /ui/account/mfa/verify`, which never reaches the floor and writes no row, though on `POST /ui/account/mfa/verify` the route's gate runs first, so a pending session on an account that already holds a factor still gets the factor-binding refusal and its `auth.mfa_denied` row (BACKLOG #5398, #5399); no lockout count, no code or challenge spent, though under the default `require_action_step_up` a TOTP enrolment confirm's route has already spent its password step-up | on, 1 s | `[auth].mfa_verify_min_elapsed_seconds` (`0` = off) | | Time from a federated start to its callback | at least the flow cache's monotonic clock when the flow was staged vs at the callback, and the verified ID token's `auth_time` (sign-in) and `amr` | a step-up callback less than 1 s after its `POST /ui/reauth/oidc` start (`oidc_callback_min_elapsed_seconds`, BACKLOG #2301), a provisional human-timing default; a sign-in callback likewise, **only** when the verified `auth_time` is at or after the flow's start rounded down to the whole second, because an IdP holding a live single sign-on session answers with no human step; on either leg the floor does not apply when a verified `amr` value is in `oidc_callback_floor_exempt_amr` (what an exempted pass records is under *What these floors do not do*) | **DENY** with the leg's ordinary failure: `federated sign-in failed`, audited `auth.login_failed` with `reason=too_early`, or the generic step-up refusal, audited `auth.reauth` with `reason=too_early`. The callback's age runs to the instant the flow cache consumes its flow, so at least the code exchange and the store reads after that consume do not count toward it; work the callback route does before the consume still does (BACKLOG #3221). The step-up is refused before its code is redeemed while `oidc_callback_floor_exempt_amr` is empty. On the sign-in leg, and on the step-up leg with the list set, the refusal waits for the code exchange, so a too-early callback whose exchange fails is refused and audited as that failure, not as `too_early`; on the step-up leg that row carries `callback_floor_deferred` (BACKLOG #3728) | on, 1 s; `oidc_callback_floor_exempt_amr` empty | `[auth].oidc_callback_min_elapsed_seconds` (`0` = off), `[auth].oidc_callback_floor_exempt_amr` | @@ -7566,8 +7568,8 @@ seam digest, so no such engine mounts it; the shim was unreachable, and BACKLOG Every enforced limit, with both dimensions stated even where one is hard-coded off, because "per-user **and** globally" is the requirement's own wording. **Enforcement scope is stated per row, because it -is not uniform.** The four sliding-window limiters (sign-in, credential ceremony, PHI read, admin -write) and the two pending-flow caches are **in-process, per API process** — N engine shards multiply +is not uniform.** The five sliding-window limiters (sign-in, credential ceremony, PHI read, +monitoring read, admin write) and the two pending-flow caches are **in-process, per API process** — N engine shards multiply *those* budgets by N. So are at least the three audit-row budgets of the 6.1.1 set (controls 10 to 12), which this table does not list. The account lockout and the concurrent-session cap are **store-backed** (`increment_login_failure` / `enforce_session_cap` against the one unified store), so they are **shared** by every API process and are **not** multiplied by N. For @@ -7588,6 +7590,7 @@ additionally front the API with a proxy/WAF limiter and TLS. | Credential ceremonies | *(shares* `login_rate_limit_per_ip` *and* `login_rate_limit_window_seconds`*, and the same enable flag)* | on / 10 / — / 60.0 s | 60 s | **yes** (`login_rate_limit_per_ip` per key): the user's id, which every other route here charges, and for an `oidc` session's IdP step-up a key of its own (`oidc-step-up-return:`), which only `GET /ui/oidc/callback` on a step-up return charges (BACKLOG #3374). So an `oidc` user's two keys admit 2 x `login_rate_limit_per_ip` charges per window (**20** by default), and every other user's one key `login_rate_limit_per_ip` (10). Each IdP step-up still starts at `POST /ui/reauth/oidc` on the user's id key, so no more than `login_rate_limit_per_ip` IdP step-ups start per window | no (`glob=0`) | no | **in-process** — 3 JSON + 7 console ceremony routes (`POST /ui/mfa`, `POST /ui/reauth`, `POST /ui/reauth/webauthn`, `POST /ui/reauth/oidc`, `GET /ui/oidc/callback` on a step-up return, `POST /ui/account/mfa/verify`, `POST /ui/account/webauthn/verify`; the fourth and fifth are registered only with federation on), plus `POST /ui/account/password`, which inherits the JSON handler's single charge | 429; `Retry-After: 30` on `POST /ui/mfa`, `POST /ui/reauth`, `POST /ui/reauth/webauthn` and `POST /ui/account/webauthn/verify`, none on the three JSON routes, `POST /ui/reauth/oidc` (its 429 re-renders the step-up page), `GET /ui/oidc/callback` on a step-up return (likewise), `POST /ui/account/mfa/verify` or `POST /ui/account/password`; logged | | Account lockout | `[auth].lockout_threshold`, `lockout_minutes`, `lockout_max_minutes` | 5 / 15 min / 24 h | — | **yes** | no | no | **store-backed**, on **two counters** per account (ADR 0197). While the credential in force is engine-generated (an administrator's account creation and both resets set it), a sign-in failure is still counted and audited but arms no sign-in lock (`lockout_arms`, ADR 0197 Amendment A); the second-step lock arms as usual. The **sign-in** counter takes the local password leg, a combined sign-in (password and TOTP code in one request) with both factors wrong, and the step-up re-auth re-proof (AD re-binds included) + the password-change re-proof (local accounts only). The **second-step** counter takes the TOTP/recovery leg of any account with TOTP enrolled, directory ones included, and a combined sign-in with exactly one factor right. Each attempt is counted by one atomic `increment_login_failure` (SQLite under the store lock, PostgreSQL under `SELECT ... FOR UPDATE`, SQL Server under `UPDLOCK`), so concurrent attempts against one account serialize on the row instead of each reading the same pre-increment count | refuse + an audit row, named per leg — on the password leg the uniform `auth.login_failed` (`bad_credentials`) row and then `auth.login_locked`, which only `users:manage` reads (the sign-in lock does **not** refuse a combined sign-in on a local account with TOTP enrolled; the second-step lock does), `auth.mfa_failed` / `auth.webauthn_failed` with `reason=locked` on the factor legs (the second-step lock only; the sign-in lock refuses neither), `auth.directory_login_locked` with `reason=locked` on the Kerberos and OIDC sign-ins (which do not feed it), the re-proofs are not refused by either lock, and the failure that spends a session's cap revokes that session: `auth.reauth` (`session_revoked=true`) / `auth.password_change_failed` (`reason=session_revoked`) | | PHI reads | `[auth].phi_read_rate_limit_enabled`, `phi_read_rate_limit_per_actor`, `phi_read_rate_limit_global`, `phi_read_rate_limit_window_seconds` | on / 120 / **0 = off** / 60.0 s | 60 s | **yes** (120) | off by default | no | **in-process** — 8 JSON routes via `require_phi_read`, 4 bulk-PHI step-up GETs charged at admission, 11 `/ui` views via `require_ui(phi=True)`, 1 further `/ui` GET that inherits the charge by delegating into the handler body, and the `reveal` act on the monitoring JSON routes that carry one (at least `GET /events`, `GET /connections/{name}/events`, `GET /alerts/active`, `GET /connections` and `GET /connections/{name}/metadata`), charged at admission (BACKLOG #2443) | 429 + a `Retry-After` naming the actor's wait (the whole window while the global count is spent); logged on the JSON API, not by `require_ui` (see *The console's refusal differs from the JSON floor's*) | +| Monitoring reads | `[auth].monitoring_read_rate_limit_enabled`, `monitoring_read_rate_limit_per_actor`, `monitoring_read_rate_limit_global`, `monitoring_read_rate_limit_window_seconds` | on / 600 / **0 = off** / 60.0 s | 60 s | **yes** (600) | off by default | no | **in-process** — the 6 JSON routes gated by `require_monitoring_read`, charged at admission; the console's in-process calls into the same handlers are not charged (*Monitoring-read pacing* below) | 429 + a `Retry-After` naming the actor's wait (the whole window while the global count is spent); WARNING-logged, and an `auth.gate_refused` row with reason `throttled` | | Admin writes | `[auth].admin_write_rate_limit_enabled`, `admin_write_rate_limit_per_actor`, `admin_write_rate_limit_window_seconds`, `admin_write_min_interval_seconds` | on / 12 / 15 s / 0.15 s gap | 15 s | **yes** (12, and a 0.15 s minimum gap) | no (`glob=0`) | no | **in-process** — **non-GET only**, via `require_step_up`, `require_step_up_action` **and** `require_paced`; `/ui` re-applies it in `require_ui` | JSON API: 429 + a `Retry-After` naming the actor's wait, logged. `/ui`: the same 429 + `Retry-After`, no WARNING line (see *The console's refusal differs from the JSON floor's*) | | Concurrent sessions | `[auth].max_sessions_per_user` | 5 (`0` = unlimited) | — | **yes** | no | no | **store-backed** — every login and every completed second factor | the user's oldest live session is revoked; sessions past the idle or absolute limit do not count and are revoked; see the *Concurrent session count* signal row for sign-ins that still owe a second factor | | Request body | `[store].max_upload_bytes` (the upload routes only; control 5 names them) | 1 MiB elsewhere | per request | no | no | no | **stateless** — every route, in ASGI middleware | **413** over the cap, **400** or **411** on framing; control 5 above gives the rule | @@ -7598,6 +7601,39 @@ additionally front the API with a proxy/WAF limiter and TLS. | WebAuthn pending ceremonies | `GLOBAL_PENDING_CAP`, `PER_USER_PENDING_CAP`, `CHALLENGE_TTL_SECONDS` (module constants, no knobs) | 4096 / 16 / 120 s | 120 s TTL | **yes** (16) | **yes** (4096) | no | **in-process** — every passkey registration + assertion ceremony | per-user: evicts that user's **own** oldest pending ceremony (silent); global: `ChallengeCacheFullError` naming the cause + the `admin_reset_mfa` recovery path | | **Ingest plane** | `max_messages_per_second`, `message_burst` (MLLP, raw-TCP, X12 and HTTP inbounds) | **off** (unset = no rate bound) | per message | no | no | no | **in-process** — one bucket per MLLP / raw-TCP / X12 **connection** and one per HTTP **listener**, so it neither coordinates across engine shards nor aggregates per peer | **Ships OFF, and the off default is ruled rather than accidental** — a rate on a clinical interface is only safe at a number taken from a real feed profile. **So a default install has NO message-RATE bound on the ingest plane**, and that is a deliberate posture, not a gap in the control. Both keys are parameters of the `MLLP()`, `Tcp()`, `X12()` and `Http()` factories, so **the code-first surface expresses them on all four**. `connections.toml` desugars through those same factories, so **the TOML surface expresses them on three of the four**: `X12` is absent from that loader's `_TRANSPORTS` map entirely, so **no** X12 setting is expressible in `connections.toml` and the pacing keys are not a special case of that. Closing it means adding the transport, which is a separate decision from this control; the gap is pinned with its own positive control at `tests/test_ingress_message_pacing.py::test_x12_has_no_toml_surface_at_all_which_is_a_separate_gap` (BACKLOG #1249 for MLLP, BACKLOG #1114 for the other three — until #1249 landed the pacer was built and no documented configuration could turn it on, and until #1114 landed the other three intakes had no rate control in **any** configuration, which is a different and worse thing than being off). *What it does when set:* the listener **pauses reading before its next read** so TCP back-pressures the sender; no message is dropped, refused, NAK'd, 429'd or reordered — the count-and-log invariant forbids accept-and-drop, so a discarding limiter was never available. **The HTTP bucket is listener-wide, not per-connection**, because that connector answers one request per connection; a `GET`/`HEAD` probe waits behind an outstanding debt but charges nothing. **Two SIBLING intake bounds on different units, added by BACKLOG #1114 — read them as separate controls, not as this row's keys reaching further.** (1) `max_associations_per_second` / `association_burst` bound the **DICOM C-STORE SCP**, and the unit is an **association**, not a message: `pynetdicom` owns the read loop, so by the time a C-STORE reaches the engine the object has already been read and decoded, and a pace after decode would delay a message the count-and-log invariant has already obliged us to account for. The pacer waits before reading the association request and never refuses one itself. A waiting connection does hold one of the SCP's slots for connections with no association yet, and a connection over those caps is closed ([DICOM.md](DICOM.md) section 3). The engine-wide intake pause is a separate control that does refuse a new association as busy while it holds (BACKLOG #290; the `[inbound].max_staged_depth` row of [CONFIGURATION.md](CONFIGURATION.md) says how). An established association is still **unbounded in the objects it may push** (`max_object_bytes` and `timeout_seconds` bound those instead). It **ships OFF**, for the reason in bold above, so it does not soften the sentence about a default install. (2) `poll_max_files` (the `File`, `Sftp` and `Ftp` sources) and `poll_max_rows` (the `DatabasePoll` source) cap how many items one **poll tick** takes, not how many it lists, and both **ship ON at 500**. That is the opposite default, deliberately, because a poll source has no sender to back-pressure. The excess is **deferred, not refused**: it stays in the drop directory or the table for a later tick. That holds on the Database source only under conditions, and a file source can still spend the cap on a file it leaves in place; [CONNECTIONS.md §*Per-tick poll ceilings*](CONNECTIONS.md#per-tick-poll-ceilings) states both, with what spends the cap on each source, why 500 and when to raise it. A negative or non-numeric value is **refused when the connection is built**, before it starts. **Still not covered even when set:** any **per-message** bound on the DICOM SCP, and any **per-peer MESSAGE-RATE** bound (MLLP, TCP and X12 peers are unauthenticated, so the only key would be source IP, which NAT collapses). **A per-peer CONNECTION bound does now ship on the MLLP, raw-TCP and X12 listeners** — `max_connections_per_host` (32). BACKLOG #1725 added it to MLLP, and vault BACKLOG #2606 to the other two. It is a different unit: it caps concurrent sockets from one address, refusing pre-ingress, and never bounds how fast an admitted peer may send. It keys on source IP, so the NAT objection still applies to it and is recorded at its constant; behind a source-NAT proxy set it to `None`/`0`. The HTTP listener takes the same key but **ships it off**. Behind a reverse proxy every partner arrives from one address, so a cap there would be the listener's whole capacity. It does ship `max_handshakes_per_host` (32) on. That is not a per-host connection cap: it counts only the sockets one address holds while their TLS handshake runs, and only with `tls = true` (vault BACKLOG #4888; [DEPLOYMENT.md](DEPLOYMENT.md#per-address-listener-caps-behind-the-vip)). The DICOM intake has no such key. It caps only connections with no association yet, per host and per listener, by constant, and it gives each one a deadline ([DICOM.md](DICOM.md) section 3). **Resource bounds that DO ship on** — at least `max_connections` (256), the MLLP, raw-TCP and X12 listeners' `max_connections_per_host` (32) and `max_frame_seconds` (60.0 s), the HTTP listener's `max_handshakes_per_host` (32, with `tls = true` only), `receive_timeout` (60.0 s), `max_frame_bytes` (16 MiB), per-connection `max_message_bytes`, `poll_max_files` and `poll_max_rows` (500, on the poll sources), `source_ip_allowlist`. On the MLLP, raw-TCP and X12 listeners `receive_timeout` resets on every byte received, so it bounds only silence; `max_frame_seconds` bounds the frame. Bytes outside a frame count toward that deadline too (vault BACKLOG #2847 brought MLLP into line). [CONNECTIONS.md](CONNECTIONS.md#resource-management--limits-asvs-1312--1313--1326) states when its clock starts and stops. | +#### Monitoring-read pacing + +Vault BACKLOG #1191 (ASVS 15.2.2). Six `monitoring:read` GETs cost work that grows per call: +`GET /graph/edges` rebuilds the wiring graph, and `GET /status`, `/stats`, `/metrics`, +`/metrics/history` and `/connections` read aggregates whose cost grows with the store. They are +gated by `require_monitoring_read`, which charges a per-actor sliding window at admission, before +the route's own work. The other `monitoring:read` routes stay on plain `require`. + +**Key.** `identity.user_id` of the bearer session the request presents. A Prometheus-style scraper +on `/metrics` authenticates the same way, so it draws the bucket of the account its token belongs +to, shared with that account's other API reads. A verified mTLS client certificate does not reach +these routes: the certificate plane is `require_service_cert` alone, and these six use the bearer +ladder. With `allow_no_auth` there is no actor, so nothing is charged. + +**How the default was set, measured from the console at this release.** One console tab shows one +page. Its timers, read from `messagefoundry_webconsole/static/app.js` and the pages that set them: +the nav poll of `/ui/nav-status` every 15 s, on every page, which calls the `GET /status` handler; +the Connections page's poll of `/ui/connections` every 5 s, which calls the `GET /connections` +handler (paused while `/ws/stats` is open; the measurement counts it running); and the Flow and +trends page's `/ui/monitoring/live` every 5 s, which calls the `GET /graph/edges` and +`GET /metrics/history` handlers. The worst page is Flow and trends: 24 + 4 = 28 handler calls per +minute per tab. A scraper on `/metrics` every 15 s adds 4 per minute. The rule is at least 4 times +(tabs x 28 + 4), rounded up, and never below 600 per 60 s. For five tabs that is 4 x 144 = 576, so +the floor of 600 applies. 600 per minute is 21 such tabs at 1x, or 5 tabs at the 4x margin. The +tab count of five is a judgment, not a measurement. The global count ships off, as +`phi_read_rate_limit_global` does. + +**What it does not charge.** The console calls these handlers in process, through `require_ui`, +so the route's own dependency does not run and a console tab spends none of this budget. Measured +the other way, a console tab makes no HTTP request to the six routes, so the console's rate above +bounds a future charge on that path rather than this one. A value looser than the default is +named by `security_loosenings()`; [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md) has its row. + **What these limits defend, and what they do not.** The full inventory of resource-demanding functionality — including the surfaces that remain **unbounded** at this release — is security/THREAT-MODEL.md §Resource-demanding functionality (ASVS 15.1.3). @@ -7605,9 +7641,11 @@ Read the two together: the table above is the operator-surface half, and that se picture including the ingest plane. That document is maintainer-internal; [SECURITY-DOCS-POLICY.md](SECURITY-DOCS-POLICY.md) explains what is withheld and what you can request. -**Almost no limiter has a validator floor.** None of the eleven `*_rate_limit_*` fields carries a -lower-bound validator except `admin_write_rate_limit_window_seconds`, which must be above `0`, and -`admin_write_rate_limit_per_actor`, which must be `0` or more (BACKLOG #3293); the windows' other +**Almost no limiter has a validator floor.** None of the fifteen `*_rate_limit_*` fields carries a +lower-bound validator except `admin_write_rate_limit_window_seconds` and +`monitoring_read_rate_limit_window_seconds`, which must be above `0`, and +`admin_write_rate_limit_per_actor`, `monitoring_read_rate_limit_per_actor` and +`monitoring_read_rate_limit_global`, which must be `0` or more (BACKLOG #3293); the windows' other validators refuse NaN, infinity and a very long window, not a small one. And neither `lockout_threshold` nor `lockout_minutes` carries one. So a `per_key` or `glob` of `0` disables that dimension, and a sign-in or PHI-read `*_window_seconds` of `0` ages every recorded hit out @@ -7616,7 +7654,7 @@ security-relevant values, not tuning knobs. **These limits are no longer silent ([BACKLOG #1131](BACKLOG.md), ASVS 6.1.1). While sign-in is on, `security_loosenings()` names any value **looser than its shipped default** for the sign-in limiter, the lockout (`lockout_minutes`, `lockout_threshold`, `lockout_max_minutes`), the PHI-read limiter, the -admin-write limiter and its minimum gap, `max_sessions_per_user`, and, with OIDC on, +monitoring-read limiter, the admin-write limiter and its minimum gap, `max_sessions_per_user`, and, with OIDC on, `oidc_flow_cache_max`. That covers an off switch, a zeroed count and a window of `0` or less, and also a weak but non-zero value: a `1e-6` s window or a count of `1e9` is named. A value at or stricter than the default is not. The one count with no looser value is `phi_read_rate_limit_global`, which diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index e3c1443b88..52d2def82f 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -273,6 +273,7 @@ refuse_from_new_address, refuse_undeclared_route, require, + require_monitoring_read, require_paced, require_phi_read, require_service_cert, @@ -5680,7 +5681,7 @@ async def list_channels( async def list_connections( request: Request, engine: Engine = Depends(_get_engine), - identity: Identity = Depends(require(Permission.MONITORING_READ)), + identity: Identity = Depends(require_monitoring_read(Permission.MONITORING_READ)), # Annotated rather than ``= Query(None)``, for the reason get_message gives: the web console # calls this handler in-process, and a call that leaves it out must get None. reveal: Annotated[ConnectionName | None, Query()] = None, @@ -10390,7 +10391,7 @@ async def refuse(preset_id: str, refusal: HTTPException, cause: str) -> HTTPExce @app.get("/stats", response_model=StatsResponse) async def stats( engine: Engine = Depends(_get_engine), - _user: Identity = Depends(require(Permission.MONITORING_READ)), + _user: Identity = Depends(require_monitoring_read(Permission.MONITORING_READ)), ) -> StatsResponse: # B11 (read-only, additive): the runner's empty-claim counters (idle-poll vs wake-fanout herd) # for the connection-scale harness. Default-zero when no runner is attached (graph-less engine). @@ -10428,7 +10429,7 @@ async def stats( @app.get("/metrics") async def metrics_endpoint( engine: Engine = Depends(_get_engine), - _user: Identity = Depends(require(Permission.MONITORING_READ)), + _user: Identity = Depends(require_monitoring_read(Permission.MONITORING_READ)), ) -> Response: """Prometheus exposition (text/plain). Gated by monitoring:read like /stats — a scraper authenticates with a service token. Contains only aggregate counts/latency keyed by @@ -10438,7 +10439,7 @@ async def metrics_endpoint( @app.get("/metrics/history", response_model=MetricsHistoryResponse) async def metrics_history( request: Request, - _user: Identity = Depends(require(Permission.MONITORING_READ)), + _user: Identity = Depends(require_monitoring_read(Permission.MONITORING_READ)), ) -> MetricsHistoryResponse: """The in-memory metrics-history ring for the console trend charts (BACKLOG #76, ADR 0065 amendment). Oldest-first samples of the outbound-row-by-status counts, fed by the ~1s /ws/stats @@ -10458,7 +10459,7 @@ async def metrics_history( @app.get("/graph/edges", response_model=GraphResponse) async def graph_edges( engine: Engine = Depends(_get_engine), - identity: Identity = Depends(require(Permission.MONITORING_READ)), + identity: Identity = Depends(require_monitoring_read(Permission.MONITORING_READ)), ) -> GraphResponse: """The by-name data-flow graph (BACKLOG #76, ADR 0065 amendment): the **static Registry edge set** (:func:`messagefoundry.config.graph.build_wiring_graph` — the same inbound → router → @@ -10723,7 +10724,7 @@ async def config_provenance( async def system_status( request: Request, engine: Engine = Depends(_get_engine), - _user: Identity = Depends(require(Permission.MONITORING_READ)), + _user: Identity = Depends(require_monitoring_read(Permission.MONITORING_READ)), ) -> SystemStatus: now = time.time() total = running = 0 diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 45d12d14d6..a9bfc53430 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1986,6 +1986,45 @@ async def dependency(request: Request) -> Identity: return _gate(dependency, before_body) +def require_monitoring_read(*permissions: Permission) -> Callable[[Request], Awaitable[Identity]]: + """Like :func:`require`, plus a **per-actor pace** on the cost-bearing ``monitoring:read`` GETs + (vault BACKLOG #1191, ASVS 15.2.2): the routes that rebuild the wiring graph or scan the store + per call. docs/SECURITY.md, *Monitoring-read pacing*, names the routes and the default's basis. + + Charged at ADMISSION, before the route does its work. A throttled read is logged (not silent), + answered 429 with the actor's ``Retry-After``, and recorded as an ``auth.gate_refused`` row with + reason ``throttled``. It does not ask the new-address question: :func:`refuse_from_new_address` + says why the monitoring polls stay outside it. No pace on the embedding/no-auth path (there is + no per-actor identity to key on).""" + + async def dependency(request: Request) -> Identity: + auth, identity = await _admit(request, permissions, mfa_gate=True) + if auth is not None: + async with _recorded_decision(request, auth, identity, permissions): + enforce_monitoring_read_pacing(request, auth, identity) + return identity + + return _gate(dependency, _authenticate_session_before_body) + + +def enforce_monitoring_read_pacing(request: Request, auth: AuthService, identity: Identity) -> None: + """Charge the per-actor monitoring-read budget (vault BACKLOG #1191), raising 429 when it is + spent. Logged, not silent. Its Retry-After is the actor's own wait, in whole seconds, or the + whole window while the all-accounts count is spent (:meth:`AuthService.monitoring_read_retry_after`).""" + if not auth.allow_monitoring_read(identity.user_id): + log.warning( + "monitoring-read throttled (anti-automation): actor=%s path=%s", + identity.username, + request.url.path, + ) + raise _GateRefusal( + status.HTTP_429_TOO_MANY_REQUESTS, + "too many requests; please slow down", + reason="throttled", + headers={"Retry-After": str(auth.monitoring_read_retry_after(identity.user_id))}, + ) + + def enforce_phi_read_pacing(request: Request, identity: Identity) -> None: """Charge the per-actor PHI-read budget (WP-8, ASVS 2.4.1), raising 429 when it is spent. diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 69872166e1..7ade44cce5 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -4292,6 +4292,18 @@ def __init__( if settings.phi_read_rate_limit_enabled else None ) + # Per-actor pacing for the cost-bearing monitoring:read GETs (vault BACKLOG #1191, ASVS + # 15.2.2), consulted by require_monitoring_read. Its own bucket, so dashboard polling never + # spends the PHI-read budget. + self._monitoring_read_limiter: SlidingWindowRateLimiter | None = ( + SlidingWindowRateLimiter( + per_key=settings.monitoring_read_rate_limit_per_actor, + glob=settings.monitoring_read_rate_limit_global, + window_seconds=settings.monitoring_read_rate_limit_window_seconds, + ) + if settings.monitoring_read_rate_limit_enabled + else None + ) # Per-actor anti-automation pacing for the state-changing admin surface (BACKLOG #193, ASVS # 2.4.2). Built like _phi_read_limiter but consulted from the step-up gate for NON-GET sensitive # ops. glob=0 (no cross-actor dimension): one operator's write burst must never throttle @@ -4782,6 +4794,18 @@ def phi_read_retry_after(self, actor: str) -> int: API and the ``/ui`` console both send it.""" return _retry_after_seconds(self._phi_read_limiter, actor) + def allow_monitoring_read(self, actor: str) -> bool: + """Per-actor pacing for the cost-bearing monitoring:read GETs (vault BACKLOG #1191, ASVS + 15.2.2). True = proceed; False = throttle. Always True when the limiter is disabled.""" + if self._monitoring_read_limiter is None: + return True + return self._monitoring_read_limiter.allow(actor) + + def monitoring_read_retry_after(self, actor: str) -> int: + """The ``Retry-After`` value for a monitoring read just refused for ``actor``, rounded as + :meth:`phi_read_retry_after` rounds it, on the monitoring-read limiter.""" + return _retry_after_seconds(self._monitoring_read_limiter, actor) + def login_retry_after(self) -> int: """The ``Retry-After`` value for a sign-in attempt refused by :meth:`allow_login_attempt`: the whole sign-in window, rounded UP to whole seconds, never below 1 (BACKLOG #3293). diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index c94f44d1cb..c46b7d9651 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -4029,6 +4029,19 @@ class AuthSettings(_Section): default=60.0, allow_inf_nan=False, le=_RATE_WINDOW_MAX_SECONDS ) + # Per-actor pacing on the cost-bearing monitoring:read GETs (vault BACKLOG #1191, ASVS 15.2.2): + # /graph/edges, /status, /stats, /metrics, /metrics/history and /connections, charged at + # admission by require_monitoring_read. The default's measured basis and multiplier are written + # once, in docs/SECURITY.md, "Monitoring-read pacing". In-process only, like the PHI-read + # throttle. 0 disables that dimension. + monitoring_read_rate_limit_enabled: bool = True + monitoring_read_rate_limit_per_actor: int = Field(default=600, ge=0) + monitoring_read_rate_limit_global: int = Field(default=0, ge=0) # 0 = off + # No nan/inf and capped, for the reason login_rate_limit_window_seconds gives. + monitoring_read_rate_limit_window_seconds: float = Field( + default=60.0, gt=0, allow_inf_nan=False, le=_RATE_WINDOW_MAX_SECONDS + ) + # Anti-automation on the state-changing admin surface (BACKLOG #193, ASVS 2.4.2): a per-actor # sliding window folded into the step-up gate (require_step_up) for every NON-GET sensitive op — # purge, replay, config deploy/reload. It paces scripted admin-write abuse on top of RBAC + step-up @@ -9845,6 +9858,40 @@ def _window( ), ) + # --- the monitoring-read limiter (vault BACKLOG #1191, ASVS 15.2.2): per actor, on the six + # cost-bearing monitoring:read GETs. Its window cannot be 0 or less (gt=0 at load), and the + # all-users count ships OFF (0), so neither has an off value to name. + if not auth.monitoring_read_rate_limit_enabled: + out.append( + ( + "monitoring_read_rate_limit_enabled", + "the cost-bearing monitoring reads (the wiring graph, status, stats, metrics and " + "the connections dashboard) have NO pace -- one signed-in account may make the " + "engine rebuild the graph and scan the store as fast as it answers", + ) + ) + elif _window( + "monitoring_read_rate_limit_window_seconds", + auth.monitoring_read_rate_limit_window_seconds, + what="the monitoring-read rate-limit window", + off=None, + counts=(auth.monitoring_read_rate_limit_per_actor, auth.monitoring_read_rate_limit_global), + ): + _count( + "monitoring_read_rate_limit_per_actor", + auth.monitoring_read_rate_limit_per_actor, + what="the per-account monitoring-read limit", + so=( + "one signed-in account may make that many cost-bearing monitoring reads per " + "window before it is refused" + ), + off=( + "there is no per-account monitoring-read limit, so one signed-in account may " + "drive the graph rebuild and the store scans as fast as the engine answers (only " + "an all-users limit, if one is set, holds)" + ), + ) + # --- the admin-write limiter (BACKLOG #193 / #2301, ASVS 2.4.2): per actor, on every non-GET # sensitive action. Its window cannot be 0 or less (gt=0 at load), so it has no off value. if not auth.admin_write_rate_limit_enabled: diff --git a/tests/test_derived_gate_decision_audit.py b/tests/test_derived_gate_decision_audit.py index e99abd1580..f905f435a3 100644 --- a/tests/test_derived_gate_decision_audit.py +++ b/tests/test_derived_gate_decision_audit.py @@ -32,6 +32,7 @@ _record_route_refusal, _recorded_decision, refuse_unless_step_up_window_live, + require_monitoring_read, require_paced, require_phi_read, require_reauth_only, @@ -73,7 +74,7 @@ async def engine(tmp_path: Path) -> AsyncIterator[Engine]: async def _service(engine: Engine, **overrides: Any) -> AuthService: - """One administrator; one paced write and one PHI read per window; the new-address check on. + """One administrator; one paced write, one PHI read and one monitoring read per window; the new-address check on. ``require_mfa`` is off so the base gate's factor refusal does not answer first, and the minimum write interval is off so the second write is refused by the count alone. ``overrides`` replace @@ -84,6 +85,7 @@ async def _service(engine: Engine, **overrides: Any) -> AuthService: "admin_write_min_interval_seconds": 0, "admin_write_rate_limit_per_actor": 1, "phi_read_rate_limit_per_actor": 1, + "monitoring_read_rate_limit_per_actor": 1, } service = AuthService(engine.store, AuthSettings(**(settings | overrides))) await service.initialize() @@ -187,6 +189,9 @@ class _Case: "require_paced, new address": _Case(_PACED, _CONTROL, "POST", "step_up", _AWAY), "require_phi_read, throttled": _Case(_PHI_READ, _READ, "GET", "throttled"), "require_phi_read, new address": _Case(_PHI_READ, _READ, "GET", "step_up", _AWAY), + "require_monitoring_read, throttled": _Case( + require_monitoring_read, Permission.MONITORING_READ, "GET", "throttled" + ), "require_step_up, throttled": _Case(_STEP_UP, _MANAGE, "POST", "throttled"), "require_step_up, new address": _Case(_STEP_UP, _MANAGE, "POST", "step_up", _AWAY), "require_reauth_only, new address": _Case( @@ -301,6 +306,7 @@ async def test_require_step_up_action_records_its_throttle_too(engine: Engine) - { "_enforce_admin_write_pacing", "enforce_phi_read_pacing", + "enforce_monitoring_read_pacing", "refuse_from_new_address", "_step_up_refusal", "_mfa_refusal", @@ -321,7 +327,7 @@ def test_every_gate_that_runs_admit_decides_inside_its_decision_block() -> None: """RED when: a gate factory calls ``_admit`` with no ``_recorded_decision`` block, so it writes no grant row for the requests it admits, or makes one of its own checks outside that block, so the grant row is written before that check decides. ``require`` is the one factory that writes - its grant directly. The counts are the positive control: the walk found the six gates, and a + its grant directly. The counts are the positive control: the walk found the seven gates, and a check in each.""" from messagefoundry.api import security @@ -333,7 +339,7 @@ def test_every_gate_that_runs_admit_decides_inside_its_decision_block() -> None: and node.name not in {"_admit", "require"} and "_admit" in _names_called(node) ] - assert len(gates) == 6, sorted(g.name for g in gates) + assert len(gates) == 7, sorted(g.name for g in gates) for gate in gates: blocks = [ node diff --git a/tests/test_docs_security_pathways.py b/tests/test_docs_security_pathways.py index 3a1ac0309b..270f4a43b7 100644 --- a/tests/test_docs_security_pathways.py +++ b/tests/test_docs_security_pathways.py @@ -128,6 +128,7 @@ _REQUIRE_FACTORIES = frozenset( { "require", + "require_monitoring_read", "require_paced", "require_phi_read", "require_reauth_only", diff --git a/tests/test_monitoring_read_pacing.py b/tests/test_monitoring_read_pacing.py new file mode 100644 index 0000000000..7cb5692566 --- /dev/null +++ b/tests/test_monitoring_read_pacing.py @@ -0,0 +1,172 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""Per-actor pacing on the cost-bearing monitoring:read GETs (vault BACKLOG #1191, ASVS 15.2.2). + +Driven through the real routes, so a route that drops back to plain ``require`` goes red here. The +six paced routes, their key and the default's basis are stated in docs/SECURITY.md, +*Monitoring-read pacing*. +""" + +from __future__ import annotations + +import json +from collections.abc import AsyncIterator +from pathlib import Path +from types import SimpleNamespace + +import httpx +import pytest + +from messagefoundry.api import create_app +from messagefoundry.auth import Role +from messagefoundry.auth.identity import ALL_CHANNELS +from messagefoundry.auth.service import AuthService +from messagefoundry.config.settings import AuthSettings, EgressSettings +from messagefoundry.pipeline import Engine +from tests._admin_account import create_local_user_chosen + +PW = "a-strong-test-passphrase" + +#: The routes docs/SECURITY.md names as paced. +PACED = ("/graph/edges", "/status", "/stats", "/metrics", "/metrics/history", "/connections") + + +@pytest.fixture +async def engine(tmp_path: Path) -> AsyncIterator[Engine]: + eng = await Engine.create( + tmp_path / "monitoring-pacing.db", + poll_interval=0.02, + egress_settings=EgressSettings(deny_by_default=False), + ) + yield eng + await eng.stop() + + +async def _service(engine: Engine, **overrides: object) -> AuthService: + settings: dict[str, object] = {"require_mfa": False, "admin_new_ip_step_up": False} + service = AuthService(engine.store, AuthSettings(**(settings | overrides))) # type: ignore[arg-type] + await service.initialize() + for name in ("vw", "other"): + user_id = await create_local_user_chosen( + service, + username=name, + password=PW, + display_name=None, + email=None, + roles=[Role.VIEWER.value], + actor="test", + ) + user = await service.store.get_user(user_id) + assert user is not None and user.password_hash is not None + await service.store.set_password( + user_id, + password_hash=user.password_hash, + must_change_password=False, + password_generated=False, + ) + await service.set_channel_scope(user_id, [ALL_CHANNELS], actor="test") + return service + + +def _client(engine: Engine, service: AuthService) -> httpx.AsyncClient: + transport = httpx.ASGITransport(app=create_app(engine, auth=service), client=("127.0.0.1", 123)) + return httpx.AsyncClient(transport=transport, base_url="http://t") + + +async def _bearer(c: httpx.AsyncClient, username: str) -> dict[str, str]: + r = await c.post( + "/auth/login", json={"username": username, "password": PW, "provider": "local"} + ) + assert r.status_code == 200, r.text + return {"Authorization": f"Bearer {r.json()['token']}"} + + +def test_default_is_on_at_600_per_60_seconds_with_the_global_count_off() -> None: + s = AuthSettings() + assert s.monitoring_read_rate_limit_enabled is True + assert s.monitoring_read_rate_limit_per_actor == 600 + assert s.monitoring_read_rate_limit_global == 0 + assert s.monitoring_read_rate_limit_window_seconds == 60.0 + + +@pytest.mark.parametrize("path", PACED) +async def test_each_paced_route_admits_under_the_limit_and_refuses_over_it( + engine: Engine, path: str +) -> None: + service = await _service(engine, monitoring_read_rate_limit_per_actor=2) + async with _client(engine, service) as c: + h = await _bearer(c, "vw") + for _ in range(2): + assert (await c.get(path, headers=h)).status_code == 200 + refused = await c.get(path, headers=h) + assert refused.status_code == 429 + assert int(refused.headers["Retry-After"]) >= 1 + + +async def test_the_six_routes_share_one_bucket_per_actor(engine: Engine) -> None: + service = await _service(engine, monitoring_read_rate_limit_per_actor=len(PACED)) + async with _client(engine, service) as c: + h = await _bearer(c, "vw") + for path in PACED: + assert (await c.get(path, headers=h)).status_code == 200, path + assert (await c.get(PACED[0], headers=h)).status_code == 429 + # Another account keeps its own budget. + assert (await c.get(PACED[0], headers=await _bearer(c, "other"))).status_code == 200 + + +async def test_retry_after_is_the_actors_wait( + engine: Engine, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = [1000.0] + monkeypatch.setattr( + "messagefoundry.auth.ratelimit.time", SimpleNamespace(monotonic=lambda: clock[0]) + ) + service = await _service( + engine, + monitoring_read_rate_limit_per_actor=1, + monitoring_read_rate_limit_window_seconds=37.5, + ) + async with _client(engine, service) as c: + h = await _bearer(c, "vw") + assert (await c.get("/stats", headers=h)).status_code == 200 # t=1000 + clock[0] = 1020.0 + refused = await c.get("/stats", headers=h) # the t=1000 read leaves at 1037.5 + assert (refused.status_code, refused.headers["Retry-After"]) == (429, "18") + + +async def test_a_refusal_writes_a_throttled_gate_record_and_no_grant(engine: Engine) -> None: + service = await _service(engine, monitoring_read_rate_limit_per_actor=1) + async with _client(engine, service) as c: + h = await _bearer(c, "vw") + assert (await c.get("/metrics/history", headers=h)).status_code == 200 + assert (await c.get("/metrics/history", headers=h)).status_code == 429 + rows = sorted(await engine.store.list_audit(limit=1000), key=lambda row: int(row["id"])) + decisions = [ + (str(row["action"]), json.loads(str(row["detail"] or "{}"))) + for row in rows + if row["action"] in {"auth.permission_granted", "auth.gate_refused"} + ] + on_path = [(a, d) for a, d in decisions if d.get("path") == "/metrics/history"] + assert [a for a, _ in on_path] == ["auth.permission_granted", "auth.gate_refused"], on_path + assert on_path[1][1]["reason"] == "throttled" + assert on_path[1][1]["permission"] == "monitoring:read" + + +async def test_an_unpaced_monitoring_route_is_unaffected(engine: Engine) -> None: + service = await _service(engine, monitoring_read_rate_limit_per_actor=1) + async with _client(engine, service) as c: + h = await _bearer(c, "vw") + assert (await c.get("/stats", headers=h)).status_code == 200 + assert (await c.get("/stats", headers=h)).status_code == 429 # the budget is spent + for _ in range(5): + assert (await c.get("/security/posture", headers=h)).status_code == 200 + + +async def test_disabled_knob_means_no_pacing(engine: Engine) -> None: + service = await _service( + engine, monitoring_read_rate_limit_enabled=False, monitoring_read_rate_limit_per_actor=1 + ) + async with _client(engine, service) as c: + h = await _bearer(c, "vw") + for _ in range(5): + assert (await c.get("/status", headers=h)).status_code == 200 diff --git a/tests/test_security_doc_drift.py b/tests/test_security_doc_drift.py index 936dc3a63f..5983019cdb 100644 --- a/tests/test_security_doc_drift.py +++ b/tests/test_security_doc_drift.py @@ -682,8 +682,9 @@ # -1 BACKLOG #1136 (ADR 0183 Amendment A, Wave 4): the first-run account's claim-state row went with # that account; +2 BACKLOG #288: the first-seen sign-in address, split by outcome; +1 BACKLOG #1957 # (ADR 0198): the reconciler's scope re-diff; +2 BACKLOG #2301: the two second-step time floors; -# +1 BACKLOG #2298: a session whose temporary credential lapsed is ended. -_CONTEXT_TABLE_A_ROWS = 43 +# +1 BACKLOG #2298: a session whose temporary credential lapsed is ended; +1 vault BACKLOG #1191: +# the monitoring-read volume per actor. +_CONTEXT_TABLE_A_ROWS = 44 # +1 BACKLOG #4907 (Table B): the MLLP listener's expected-sender allowlist, tls_client_subjects. _CONTEXT_TABLE_B_ROWS = 14 @@ -1383,6 +1384,7 @@ def _gates_by_operation() -> dict[tuple[str, str], _GateInfo]: _NOT_STEP_UP_GATES = frozenset( { "require", + "require_monitoring_read", "require_paced", "require_phi_read", "require_ui", @@ -2318,9 +2320,9 @@ def test_gate_wrapper_preamble_matches_the_table_it_introduces() -> None: block = _section(_doc_text(), _H_DESIGN) table = _table_with_header(block, "Gate wrapper") rows = len(table) - 1 - assert rows == 7, f"the gate-wrapper table now has {rows} rows; restate the preamble" + assert rows == 8, f"the gate-wrapper table now has {rows} rows; restate the preamble" assert ( - f"The table below has **{['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'][rows]}** rows" + f"The table below has **{['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'][rows]}** rows" in block ), f"the gate-wrapper preamble must state the real row count ({rows})" assert "deliberately\n**bypasses**" in block or "deliberately **bypasses**" in block, ( diff --git a/tests/test_security_doc_rate_limits.py b/tests/test_security_doc_rate_limits.py index 0eb45c7c33..316cecf654 100644 --- a/tests/test_security_doc_rate_limits.py +++ b/tests/test_security_doc_rate_limits.py @@ -64,8 +64,8 @@ _H_CONFIG_AUTH = "### `[auth]` — authentication & RBAC" -#: The four limiter accessors that defend the AUTHENTICATION surface (6.1.1). The other two -#: (``allow_phi_read``, ``allow_admin_write``) are post-authentication business-logic limits and +#: The four limiter accessors that defend the AUTHENTICATION surface (6.1.1). The other three +#: (``allow_phi_read``, ``allow_admin_write``, ``allow_monitoring_read``) are post-authentication business-logic limits and #: belong to the 2.1.3 table instead. The split is asserted rather than assumed: #: ``test_every_sliding_window_limiter_is_filed_under_the_right_requirement`` fails if a new #: limiter appears, forcing an explicit decision about which table it joins. @@ -78,7 +78,10 @@ "allow_step_up_return_audit", } ) -_BUSINESS_LIMIT_ACCESSORS = frozenset({"allow_phi_read", "allow_admin_write"}) +_BUSINESS_LIMIT_ACCESSORS = frozenset( + # vault BACKLOG #1191: the monitoring-read pace joins the 2.1.3 table. + {"allow_phi_read", "allow_admin_write", "allow_monitoring_read"} +) #: Anti-automation controls that are not objects and so cannot be derived: they are enforcement #: SHAPES (a counter on a user row, a semaphore, ASGI middleware, a CIDR test). Each is pinned to a @@ -104,6 +107,9 @@ 10: "Ten", 11: "Eleven", 12: "Twelve", + 13: "Thirteen", + 14: "Fourteen", + 15: "Fifteen", } _H_BRUTE = "## Brute-force & abuse protection" diff --git a/tests/test_security_posture_defaults.py b/tests/test_security_posture_defaults.py index 2e4cbc6e30..8dd85459db 100644 --- a/tests/test_security_posture_defaults.py +++ b/tests/test_security_posture_defaults.py @@ -440,6 +440,11 @@ def test_new_ip_step_up_off_is_a_named_loosening() -> None: ("phi_read_rate_limit_window_seconds", -1.0), ("phi_read_rate_limit_window_seconds", 59.0), ("phi_read_rate_limit_window_seconds", 1e-6), + ("monitoring_read_rate_limit_enabled", False), + ("monitoring_read_rate_limit_per_actor", 0), + ("monitoring_read_rate_limit_per_actor", 601), + ("monitoring_read_rate_limit_window_seconds", 59.0), + ("monitoring_read_rate_limit_window_seconds", 1e-6), ("admin_write_rate_limit_enabled", False), ("admin_write_rate_limit_per_actor", 0), ("admin_write_rate_limit_per_actor", 13), @@ -503,6 +508,13 @@ def test_new_ip_step_up_off_is_a_named_loosening() -> None: ("phi_read_rate_limit_global", 1), ("phi_read_rate_limit_window_seconds", 60.0), ("phi_read_rate_limit_window_seconds", 61.0), + ("monitoring_read_rate_limit_per_actor", 600), + ("monitoring_read_rate_limit_per_actor", 599), + # The all-users monitoring-read count ships OFF, so no value of it is looser. + ("monitoring_read_rate_limit_global", 0), + ("monitoring_read_rate_limit_global", 1), + ("monitoring_read_rate_limit_window_seconds", 60.0), + ("monitoring_read_rate_limit_window_seconds", 61.0), ("admin_write_rate_limit_per_actor", 12), ("admin_write_rate_limit_per_actor", 11), # A negative admin-write count is refused at load (BACKLOG #3293), so it has no row here. @@ -1032,6 +1044,16 @@ def _oidc_on(**over: object) -> AuthSettings: 59.0, "phi_read_rate_limit_window_seconds", ), + "monitoring_read_rate_limit_per_actor": ( + AuthSettings, + 601, + "monitoring_read_rate_limit_per_actor", + ), + "monitoring_read_rate_limit_window_seconds": ( + AuthSettings, + 59.0, + "monitoring_read_rate_limit_window_seconds", + ), "admin_write_rate_limit_per_actor": (AuthSettings, 13, "admin_write_rate_limit_per_actor"), "admin_write_rate_limit_window_seconds": ( AuthSettings, @@ -1045,6 +1067,7 @@ def _oidc_on(**over: object) -> AuthSettings: "oidc_session_max_hours": "never looser", # Ships OFF (0), so no value of it is looser than the default. "phi_read_rate_limit_global": "ships off", + "monitoring_read_rate_limit_global": "ships off", } From 2d1c1912b2c1eec8f2e458e415d5184fe4f16e74 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 20:51:13 -0600 Subject: [PATCH 02/19] Fix round-1 review findings on the monitoring-read pace Vault BACKLOG #1191. The load harness engines run with the pace off, since the rig pollers outrun it as one account; the DAST scan posture relaxes and records it; SECURITY.md stops claiming /metrics/history scans the store and names both global counts that ship off; the loosening docstring names the new limiter. --- docs/SECURITY.md | 14 +++++++++----- harness/load/failover.py | 5 +++++ messagefoundry/config/settings.py | 9 ++++++--- scripts/security/dast_target.py | 2 ++ tests/test_dast_auth_sweep.py | 3 ++- 5 files changed, 24 insertions(+), 9 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 70dbddc068..c0b2700bf1 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7604,8 +7604,10 @@ additionally front the API with a proxy/WAF limiter and TLS. #### Monitoring-read pacing Vault BACKLOG #1191 (ASVS 15.2.2). Six `monitoring:read` GETs cost work that grows per call: -`GET /graph/edges` rebuilds the wiring graph, and `GET /status`, `/stats`, `/metrics`, -`/metrics/history` and `/connections` read aggregates whose cost grows with the store. They are +`GET /graph/edges` rebuilds the wiring graph, and `GET /status`, `/stats`, `/metrics` and +`/connections` read aggregates whose cost grows with the store. `GET /metrics/history` copies the +in-memory metrics ring and reads no store; it is paced with them because the console reads it beside +`/graph/edges`. They are gated by `require_monitoring_read`, which charges a per-actor sliding window at admission, before the route's own work. The other `monitoring:read` routes stay on plain `require`. @@ -7626,7 +7628,9 @@ minute per tab. A scraper on `/metrics` every 15 s adds 4 per minute. The rule i (tabs x 28 + 4), rounded up, and never below 600 per 60 s. For five tabs that is 4 x 144 = 576, so the floor of 600 applies. 600 per minute is 21 such tabs at 1x, or 5 tabs at the 4x margin. The tab count of five is a judgment, not a measurement. The global count ships off, as -`phi_read_rate_limit_global` does. +`phi_read_rate_limit_global` does. That measurement is of the console, which this pace does not +charge (below). The in-repo load harness polls the charged routes faster than 600 per minute as one +account, so its engines run with the pace off (`harness/load/failover.py`, `EngineNode`). **What it does not charge.** The console calls these handlers in process, through `require_ui`, so the route's own dependency does not run and a console tab spends none of this budget. Measured @@ -7657,8 +7661,8 @@ value **looser than its shipped default** for the sign-in limiter, the lockout monitoring-read limiter, the admin-write limiter and its minimum gap, `max_sessions_per_user`, and, with OIDC on, `oidc_flow_cache_max`. That covers an off switch, a zeroed count and a window of `0` or less, and also a weak but non-zero value: a `1e-6` s window or a count of `1e9` is named. A value at or stricter -than the default is not. The one count with no looser value is `phi_read_rate_limit_global`, which -ships off. Each named value reaches the `serve` loosening warning, `messagefoundry security show` and +than the default is not. The two counts with no looser value are `phi_read_rate_limit_global` and +`monitoring_read_rate_limit_global`, which ship off. Each named value reaches the `serve` loosening warning, `messagefoundry security show` and `GET /security/posture`; see [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md) for the table of values. The BACKLOG #2301 time floors are named the same way: `admin_write_min_interval_seconds`, `mfa_verify_min_elapsed_seconds` and, with OIDC on, `oidc_callback_min_elapsed_seconds`, each when diff --git a/harness/load/failover.py b/harness/load/failover.py index a689d07e32..611ad09ef9 100644 --- a/harness/load/failover.py +++ b/harness/load/failover.py @@ -181,6 +181,11 @@ def __init__( self._env.pop(rigadmin.ADMIN_FACTOR_ENV, None) for name, value in rigadmin.SERVE_ENV.items(): self._env.setdefault(name, value) + # The rig's own pollers (connscale's EnginePoller, the batch fleet) read /stats, /status and + # /connections every tick as the one rig Administrator, which outruns the per-actor + # monitoring-read pace (vault BACKLOG #1191) and would turn samples into 429s. A bench + # measures its own engine, so the pace is off here; setdefault, so a scenario can keep it. + self._env.setdefault("MEFOR_AUTH_MONITORING_READ_RATE_LIMIT_ENABLED", "false") self._config_dir = config_dir self._cwd = cwd self._proc: asyncio.subprocess.Process | None = None diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index c46b7d9651..5ee182de08 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -9537,7 +9537,8 @@ def _auth_limit_loosenings(auth: AuthSettings) -> list[tuple[str, str]]: """The ``[auth]`` anti-automation limits, and the other numeric ``[auth]`` knobs that weaken a control (vault BACKLOG #2600 step 4), set LOOSER THAN THEIR SHIPPED DEFAULT, as ``(switch, risk)`` entries for :func:`security_loosenings`, which always calls this, since sign-in - is always on (BACKLOG #1131; ASVS 6.1.1, 6.3.1, 2.3.2, and the 2.4.1, 2.4.2 and 7.1.2 each field cites). + is always on (BACKLOG #1131; ASVS 6.1.1, 6.3.1, 2.3.2, and the 2.4.1, 2.4.2, 7.1.2 and 15.2.2 each + field cites). **Why the default is the cutoff.** The first pass named only the values the code reads as OFF, and a vault re-read then measured near-off values that were just as off in effect and silent: a @@ -9548,11 +9549,13 @@ def _auth_limit_loosenings(auth: AuthSettings) -> list[tuple[str, str]]: **The direction is read from each consumer, not from the name.** - * ``SlidingWindowRateLimiter`` (the sign-in, ceremony, PHI-read and admin-write limiters) treats a + * ``SlidingWindowRateLimiter`` (at least the sign-in, ceremony, PHI-read, monitoring-read and + admin-write limiters) treats a falsy count as "no limit on that dimension" and admits more as a count rises. It prunes every hit older than the window, so a SHORTER window admits more, and one of 0 or less prunes each hit before it is counted. A negative count refuses more, so it is not named; the admin-write - count refuses a negative value at load (BACKLOG #3293), so only the others reach here. A NaN or infinite + count and the two monitoring-read counts refuse a negative value at load (BACKLOG #3293), so + only the others reach here. A NaN or infinite window never reaches this function: the load refuses it (vault BACKLOG #2466), since a NaN or ``+inf`` one never prunes. A ``min_interval_seconds`` of 0 turns the gap off, and a shorter gap admits a faster burst. diff --git a/scripts/security/dast_target.py b/scripts/security/dast_target.py index 9d34fd0bb4..4121dc264e 100644 --- a/scripts/security/dast_target.py +++ b/scripts/security/dast_target.py @@ -133,6 +133,7 @@ def _auth_settings() -> AuthSettings: require_mfa=False, login_rate_limit_enabled=False, phi_read_rate_limit_enabled=False, + monitoring_read_rate_limit_enabled=False, admin_write_rate_limit_enabled=False, lockout_threshold=1_000_000, step_up_max_age_seconds=86400, @@ -145,6 +146,7 @@ def _posture(*, canary: str | None) -> dict[str, str]: "require_mfa": "OFF", "login_rate_limit": "OFF", "phi_read_rate_limit": "OFF", + "monitoring_read_rate_limit": "OFF", "admin_write_rate_limit": "OFF", "lockout_threshold": "1000000", "step_up_max_age": "86400s", diff --git a/tests/test_dast_auth_sweep.py b/tests/test_dast_auth_sweep.py index d475bd7ec9..61ddc31c3a 100644 --- a/tests/test_dast_auth_sweep.py +++ b/tests/test_dast_auth_sweep.py @@ -173,7 +173,7 @@ def test_receipt_names_what_it_examined(clean_run: tuple[int, dict[str, Any]]) - outcomes = receipt["write_probe_outcomes"] assert sum(outcomes.values()) == receipt["write_rows"], outcomes - # The scan RELAXES five controls to stay deterministic. The receipt must print every relaxation, so + # The scan RELAXES controls to stay deterministic. The receipt must print every relaxation, so # no reader can mistake the scanned posture for the shipped default. posture = receipt["posture"] assert posture["auth"] == "ENABLED" @@ -181,6 +181,7 @@ def test_receipt_names_what_it_examined(clean_run: tuple[int, dict[str, Any]]) - "require_mfa", "login_rate_limit", "phi_read_rate_limit", + "monitoring_read_rate_limit", "admin_write_rate_limit", ): assert posture[knob] == "OFF", f"the receipt does not record {knob} as scanned" From ec867ed274f9514f462c72334eb8e0ee1f369201 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 21:12:28 -0600 Subject: [PATCH 03/19] Fix round-2 review findings on the monitoring-read pace Vault BACKLOG #1191. SECURITY.md moves the Monitoring-read pacing subsection to the end of the business-logic limits, so the general paragraphs no longer file under it; the gate_refused row is stated as conditional on audit_all_authz; the ge=0 counts cite #1191, not #3293; the harness rate is stated as measured; refuse_from_new_address names the new gate. --- docs/SECURITY.md | 81 ++++++++++++++++--------------- messagefoundry/api/security.py | 5 +- messagefoundry/config/settings.py | 4 +- 3 files changed, 46 insertions(+), 44 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index c0b2700bf1..97f1248cb9 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7590,7 +7590,7 @@ additionally front the API with a proxy/WAF limiter and TLS. | Credential ceremonies | *(shares* `login_rate_limit_per_ip` *and* `login_rate_limit_window_seconds`*, and the same enable flag)* | on / 10 / — / 60.0 s | 60 s | **yes** (`login_rate_limit_per_ip` per key): the user's id, which every other route here charges, and for an `oidc` session's IdP step-up a key of its own (`oidc-step-up-return:`), which only `GET /ui/oidc/callback` on a step-up return charges (BACKLOG #3374). So an `oidc` user's two keys admit 2 x `login_rate_limit_per_ip` charges per window (**20** by default), and every other user's one key `login_rate_limit_per_ip` (10). Each IdP step-up still starts at `POST /ui/reauth/oidc` on the user's id key, so no more than `login_rate_limit_per_ip` IdP step-ups start per window | no (`glob=0`) | no | **in-process** — 3 JSON + 7 console ceremony routes (`POST /ui/mfa`, `POST /ui/reauth`, `POST /ui/reauth/webauthn`, `POST /ui/reauth/oidc`, `GET /ui/oidc/callback` on a step-up return, `POST /ui/account/mfa/verify`, `POST /ui/account/webauthn/verify`; the fourth and fifth are registered only with federation on), plus `POST /ui/account/password`, which inherits the JSON handler's single charge | 429; `Retry-After: 30` on `POST /ui/mfa`, `POST /ui/reauth`, `POST /ui/reauth/webauthn` and `POST /ui/account/webauthn/verify`, none on the three JSON routes, `POST /ui/reauth/oidc` (its 429 re-renders the step-up page), `GET /ui/oidc/callback` on a step-up return (likewise), `POST /ui/account/mfa/verify` or `POST /ui/account/password`; logged | | Account lockout | `[auth].lockout_threshold`, `lockout_minutes`, `lockout_max_minutes` | 5 / 15 min / 24 h | — | **yes** | no | no | **store-backed**, on **two counters** per account (ADR 0197). While the credential in force is engine-generated (an administrator's account creation and both resets set it), a sign-in failure is still counted and audited but arms no sign-in lock (`lockout_arms`, ADR 0197 Amendment A); the second-step lock arms as usual. The **sign-in** counter takes the local password leg, a combined sign-in (password and TOTP code in one request) with both factors wrong, and the step-up re-auth re-proof (AD re-binds included) + the password-change re-proof (local accounts only). The **second-step** counter takes the TOTP/recovery leg of any account with TOTP enrolled, directory ones included, and a combined sign-in with exactly one factor right. Each attempt is counted by one atomic `increment_login_failure` (SQLite under the store lock, PostgreSQL under `SELECT ... FOR UPDATE`, SQL Server under `UPDLOCK`), so concurrent attempts against one account serialize on the row instead of each reading the same pre-increment count | refuse + an audit row, named per leg — on the password leg the uniform `auth.login_failed` (`bad_credentials`) row and then `auth.login_locked`, which only `users:manage` reads (the sign-in lock does **not** refuse a combined sign-in on a local account with TOTP enrolled; the second-step lock does), `auth.mfa_failed` / `auth.webauthn_failed` with `reason=locked` on the factor legs (the second-step lock only; the sign-in lock refuses neither), `auth.directory_login_locked` with `reason=locked` on the Kerberos and OIDC sign-ins (which do not feed it), the re-proofs are not refused by either lock, and the failure that spends a session's cap revokes that session: `auth.reauth` (`session_revoked=true`) / `auth.password_change_failed` (`reason=session_revoked`) | | PHI reads | `[auth].phi_read_rate_limit_enabled`, `phi_read_rate_limit_per_actor`, `phi_read_rate_limit_global`, `phi_read_rate_limit_window_seconds` | on / 120 / **0 = off** / 60.0 s | 60 s | **yes** (120) | off by default | no | **in-process** — 8 JSON routes via `require_phi_read`, 4 bulk-PHI step-up GETs charged at admission, 11 `/ui` views via `require_ui(phi=True)`, 1 further `/ui` GET that inherits the charge by delegating into the handler body, and the `reveal` act on the monitoring JSON routes that carry one (at least `GET /events`, `GET /connections/{name}/events`, `GET /alerts/active`, `GET /connections` and `GET /connections/{name}/metadata`), charged at admission (BACKLOG #2443) | 429 + a `Retry-After` naming the actor's wait (the whole window while the global count is spent); logged on the JSON API, not by `require_ui` (see *The console's refusal differs from the JSON floor's*) | -| Monitoring reads | `[auth].monitoring_read_rate_limit_enabled`, `monitoring_read_rate_limit_per_actor`, `monitoring_read_rate_limit_global`, `monitoring_read_rate_limit_window_seconds` | on / 600 / **0 = off** / 60.0 s | 60 s | **yes** (600) | off by default | no | **in-process** — the 6 JSON routes gated by `require_monitoring_read`, charged at admission; the console's in-process calls into the same handlers are not charged (*Monitoring-read pacing* below) | 429 + a `Retry-After` naming the actor's wait (the whole window while the global count is spent); WARNING-logged, and an `auth.gate_refused` row with reason `throttled` | +| Monitoring reads | `[auth].monitoring_read_rate_limit_enabled`, `monitoring_read_rate_limit_per_actor`, `monitoring_read_rate_limit_global`, `monitoring_read_rate_limit_window_seconds` | on / 600 / **0 = off** / 60.0 s | 60 s | **yes** (600) | off by default | no | **in-process** — the 6 JSON routes gated by `require_monitoring_read`, charged at admission; the console's in-process calls into the same handlers are not charged (*Monitoring-read pacing* below) | 429 + a `Retry-After` naming the actor's wait (the whole window while the global count is spent); WARNING-logged, and an `auth.gate_refused` row with reason `throttled` while `[diagnostics].audit_all_authz` is on (the default) | | Admin writes | `[auth].admin_write_rate_limit_enabled`, `admin_write_rate_limit_per_actor`, `admin_write_rate_limit_window_seconds`, `admin_write_min_interval_seconds` | on / 12 / 15 s / 0.15 s gap | 15 s | **yes** (12, and a 0.15 s minimum gap) | no (`glob=0`) | no | **in-process** — **non-GET only**, via `require_step_up`, `require_step_up_action` **and** `require_paced`; `/ui` re-applies it in `require_ui` | JSON API: 429 + a `Retry-After` naming the actor's wait, logged. `/ui`: the same 429 + `Retry-After`, no WARNING line (see *The console's refusal differs from the JSON floor's*) | | Concurrent sessions | `[auth].max_sessions_per_user` | 5 (`0` = unlimited) | — | **yes** | no | no | **store-backed** — every login and every completed second factor | the user's oldest live session is revoked; sessions past the idle or absolute limit do not count and are revoked; see the *Concurrent session count* signal row for sign-ins that still owe a second factor | | Request body | `[store].max_upload_bytes` (the upload routes only; control 5 names them) | 1 MiB elsewhere | per request | no | no | no | **stateless** — every route, in ASGI middleware | **413** over the cap, **400** or **411** on framing; control 5 above gives the rule | @@ -7601,43 +7601,6 @@ additionally front the API with a proxy/WAF limiter and TLS. | WebAuthn pending ceremonies | `GLOBAL_PENDING_CAP`, `PER_USER_PENDING_CAP`, `CHALLENGE_TTL_SECONDS` (module constants, no knobs) | 4096 / 16 / 120 s | 120 s TTL | **yes** (16) | **yes** (4096) | no | **in-process** — every passkey registration + assertion ceremony | per-user: evicts that user's **own** oldest pending ceremony (silent); global: `ChallengeCacheFullError` naming the cause + the `admin_reset_mfa` recovery path | | **Ingest plane** | `max_messages_per_second`, `message_burst` (MLLP, raw-TCP, X12 and HTTP inbounds) | **off** (unset = no rate bound) | per message | no | no | no | **in-process** — one bucket per MLLP / raw-TCP / X12 **connection** and one per HTTP **listener**, so it neither coordinates across engine shards nor aggregates per peer | **Ships OFF, and the off default is ruled rather than accidental** — a rate on a clinical interface is only safe at a number taken from a real feed profile. **So a default install has NO message-RATE bound on the ingest plane**, and that is a deliberate posture, not a gap in the control. Both keys are parameters of the `MLLP()`, `Tcp()`, `X12()` and `Http()` factories, so **the code-first surface expresses them on all four**. `connections.toml` desugars through those same factories, so **the TOML surface expresses them on three of the four**: `X12` is absent from that loader's `_TRANSPORTS` map entirely, so **no** X12 setting is expressible in `connections.toml` and the pacing keys are not a special case of that. Closing it means adding the transport, which is a separate decision from this control; the gap is pinned with its own positive control at `tests/test_ingress_message_pacing.py::test_x12_has_no_toml_surface_at_all_which_is_a_separate_gap` (BACKLOG #1249 for MLLP, BACKLOG #1114 for the other three — until #1249 landed the pacer was built and no documented configuration could turn it on, and until #1114 landed the other three intakes had no rate control in **any** configuration, which is a different and worse thing than being off). *What it does when set:* the listener **pauses reading before its next read** so TCP back-pressures the sender; no message is dropped, refused, NAK'd, 429'd or reordered — the count-and-log invariant forbids accept-and-drop, so a discarding limiter was never available. **The HTTP bucket is listener-wide, not per-connection**, because that connector answers one request per connection; a `GET`/`HEAD` probe waits behind an outstanding debt but charges nothing. **Two SIBLING intake bounds on different units, added by BACKLOG #1114 — read them as separate controls, not as this row's keys reaching further.** (1) `max_associations_per_second` / `association_burst` bound the **DICOM C-STORE SCP**, and the unit is an **association**, not a message: `pynetdicom` owns the read loop, so by the time a C-STORE reaches the engine the object has already been read and decoded, and a pace after decode would delay a message the count-and-log invariant has already obliged us to account for. The pacer waits before reading the association request and never refuses one itself. A waiting connection does hold one of the SCP's slots for connections with no association yet, and a connection over those caps is closed ([DICOM.md](DICOM.md) section 3). The engine-wide intake pause is a separate control that does refuse a new association as busy while it holds (BACKLOG #290; the `[inbound].max_staged_depth` row of [CONFIGURATION.md](CONFIGURATION.md) says how). An established association is still **unbounded in the objects it may push** (`max_object_bytes` and `timeout_seconds` bound those instead). It **ships OFF**, for the reason in bold above, so it does not soften the sentence about a default install. (2) `poll_max_files` (the `File`, `Sftp` and `Ftp` sources) and `poll_max_rows` (the `DatabasePoll` source) cap how many items one **poll tick** takes, not how many it lists, and both **ship ON at 500**. That is the opposite default, deliberately, because a poll source has no sender to back-pressure. The excess is **deferred, not refused**: it stays in the drop directory or the table for a later tick. That holds on the Database source only under conditions, and a file source can still spend the cap on a file it leaves in place; [CONNECTIONS.md §*Per-tick poll ceilings*](CONNECTIONS.md#per-tick-poll-ceilings) states both, with what spends the cap on each source, why 500 and when to raise it. A negative or non-numeric value is **refused when the connection is built**, before it starts. **Still not covered even when set:** any **per-message** bound on the DICOM SCP, and any **per-peer MESSAGE-RATE** bound (MLLP, TCP and X12 peers are unauthenticated, so the only key would be source IP, which NAT collapses). **A per-peer CONNECTION bound does now ship on the MLLP, raw-TCP and X12 listeners** — `max_connections_per_host` (32). BACKLOG #1725 added it to MLLP, and vault BACKLOG #2606 to the other two. It is a different unit: it caps concurrent sockets from one address, refusing pre-ingress, and never bounds how fast an admitted peer may send. It keys on source IP, so the NAT objection still applies to it and is recorded at its constant; behind a source-NAT proxy set it to `None`/`0`. The HTTP listener takes the same key but **ships it off**. Behind a reverse proxy every partner arrives from one address, so a cap there would be the listener's whole capacity. It does ship `max_handshakes_per_host` (32) on. That is not a per-host connection cap: it counts only the sockets one address holds while their TLS handshake runs, and only with `tls = true` (vault BACKLOG #4888; [DEPLOYMENT.md](DEPLOYMENT.md#per-address-listener-caps-behind-the-vip)). The DICOM intake has no such key. It caps only connections with no association yet, per host and per listener, by constant, and it gives each one a deadline ([DICOM.md](DICOM.md) section 3). **Resource bounds that DO ship on** — at least `max_connections` (256), the MLLP, raw-TCP and X12 listeners' `max_connections_per_host` (32) and `max_frame_seconds` (60.0 s), the HTTP listener's `max_handshakes_per_host` (32, with `tls = true` only), `receive_timeout` (60.0 s), `max_frame_bytes` (16 MiB), per-connection `max_message_bytes`, `poll_max_files` and `poll_max_rows` (500, on the poll sources), `source_ip_allowlist`. On the MLLP, raw-TCP and X12 listeners `receive_timeout` resets on every byte received, so it bounds only silence; `max_frame_seconds` bounds the frame. Bytes outside a frame count toward that deadline too (vault BACKLOG #2847 brought MLLP into line). [CONNECTIONS.md](CONNECTIONS.md#resource-management--limits-asvs-1312--1313--1326) states when its clock starts and stops. | -#### Monitoring-read pacing - -Vault BACKLOG #1191 (ASVS 15.2.2). Six `monitoring:read` GETs cost work that grows per call: -`GET /graph/edges` rebuilds the wiring graph, and `GET /status`, `/stats`, `/metrics` and -`/connections` read aggregates whose cost grows with the store. `GET /metrics/history` copies the -in-memory metrics ring and reads no store; it is paced with them because the console reads it beside -`/graph/edges`. They are -gated by `require_monitoring_read`, which charges a per-actor sliding window at admission, before -the route's own work. The other `monitoring:read` routes stay on plain `require`. - -**Key.** `identity.user_id` of the bearer session the request presents. A Prometheus-style scraper -on `/metrics` authenticates the same way, so it draws the bucket of the account its token belongs -to, shared with that account's other API reads. A verified mTLS client certificate does not reach -these routes: the certificate plane is `require_service_cert` alone, and these six use the bearer -ladder. With `allow_no_auth` there is no actor, so nothing is charged. - -**How the default was set, measured from the console at this release.** One console tab shows one -page. Its timers, read from `messagefoundry_webconsole/static/app.js` and the pages that set them: -the nav poll of `/ui/nav-status` every 15 s, on every page, which calls the `GET /status` handler; -the Connections page's poll of `/ui/connections` every 5 s, which calls the `GET /connections` -handler (paused while `/ws/stats` is open; the measurement counts it running); and the Flow and -trends page's `/ui/monitoring/live` every 5 s, which calls the `GET /graph/edges` and -`GET /metrics/history` handlers. The worst page is Flow and trends: 24 + 4 = 28 handler calls per -minute per tab. A scraper on `/metrics` every 15 s adds 4 per minute. The rule is at least 4 times -(tabs x 28 + 4), rounded up, and never below 600 per 60 s. For five tabs that is 4 x 144 = 576, so -the floor of 600 applies. 600 per minute is 21 such tabs at 1x, or 5 tabs at the 4x margin. The -tab count of five is a judgment, not a measurement. The global count ships off, as -`phi_read_rate_limit_global` does. That measurement is of the console, which this pace does not -charge (below). The in-repo load harness polls the charged routes faster than 600 per minute as one -account, so its engines run with the pace off (`harness/load/failover.py`, `EngineNode`). - -**What it does not charge.** The console calls these handlers in process, through `require_ui`, -so the route's own dependency does not run and a console tab spends none of this budget. Measured -the other way, a console tab makes no HTTP request to the six routes, so the console's rate above -bounds a future charge on that path rather than this one. A value looser than the default is -named by `security_loosenings()`; [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md) has its row. - **What these limits defend, and what they do not.** The full inventory of resource-demanding functionality — including the surfaces that remain **unbounded** at this release — is security/THREAT-MODEL.md §Resource-demanding functionality (ASVS 15.1.3). @@ -7648,8 +7611,8 @@ picture including the ingest plane. That document is maintainer-internal; **Almost no limiter has a validator floor.** None of the fifteen `*_rate_limit_*` fields carries a lower-bound validator except `admin_write_rate_limit_window_seconds` and `monitoring_read_rate_limit_window_seconds`, which must be above `0`, and -`admin_write_rate_limit_per_actor`, `monitoring_read_rate_limit_per_actor` and -`monitoring_read_rate_limit_global`, which must be `0` or more (BACKLOG #3293); the windows' other +`admin_write_rate_limit_per_actor` (BACKLOG #3293), `monitoring_read_rate_limit_per_actor` and +`monitoring_read_rate_limit_global` (vault BACKLOG #1191), which must be `0` or more; the windows' other validators refuse NaN, infinity and a very long window, not a small one. And neither `lockout_threshold` nor `lockout_minutes` carries one. So a `per_key` or `glob` of `0` disables that dimension, and a sign-in or PHI-read `*_window_seconds` of `0` ages every recorded hit out @@ -7710,6 +7673,44 @@ API port keeps a separate one. The default global limiter / WAF in front (a modest unconditional global login/second-factor ceiling independent of IP is a backlog follow-up). +#### Monitoring-read pacing + +Vault BACKLOG #1191 (ASVS 15.2.2). Six `monitoring:read` GETs cost work that grows per call: +`GET /graph/edges` rebuilds the wiring graph, and `GET /status`, `/stats`, `/metrics` and +`/connections` read aggregates whose cost grows with the store. `GET /metrics/history` copies the +in-memory metrics ring and reads no store; it is paced with them because the console reads it beside +`/graph/edges`. They are +gated by `require_monitoring_read`, which charges a per-actor sliding window at admission, before +the route's own work. The other `monitoring:read` routes stay on plain `require`. + +**Key.** `identity.user_id` of the bearer session the request presents. A Prometheus-style scraper +on `/metrics` authenticates the same way, so it draws the bucket of the account its token belongs +to, shared with that account's other API reads. A verified mTLS client certificate does not reach +these routes: the certificate plane is `require_service_cert` alone, and these six use the bearer +ladder. With `allow_no_auth` there is no actor, so nothing is charged. + +**How the default was set, measured from the console at this release.** One console tab shows one +page. Its timers, read from `messagefoundry_webconsole/static/app.js` and the pages that set them: +the nav poll of `/ui/nav-status` every 15 s, on every page, which calls the `GET /status` handler; +the Connections page's poll of `/ui/connections` every 5 s, which calls the `GET /connections` +handler (paused while `/ws/stats` is open; the measurement counts it running); and the Flow and +trends page's `/ui/monitoring/live` every 5 s, which calls the `GET /graph/edges` and +`GET /metrics/history` handlers. The worst page is Flow and trends: 24 + 4 = 28 handler calls per +minute per tab. A scraper on `/metrics` every 15 s adds 4 per minute. The rule is at least 4 times +(tabs x 28 + 4), rounded up, and never below 600 per 60 s. For five tabs that is 4 x 144 = 576, so +the floor of 600 applies. 600 per minute is 21 such tabs at 1x, or 5 tabs at the 4x margin. The +tab count of five is a judgment, not a measurement. The global count ships off, as +`phi_read_rate_limit_global` does. That measurement is of the console, which this pace does not +charge (below). The in-repo load harness's poller makes 3 charged reads per sample as one account, +720 per minute at the 0.25 s interval two of its profiles use, so the engines it spawns run with the +pace off (`harness/load/failover.py`, `EngineNode`). An engine it attaches to by URL keeps the pace. + +**What it does not charge.** The console calls these handlers in process, through `require_ui`, +so the route's own dependency does not run and a console tab spends none of this budget. Measured +the other way, a console tab makes no HTTP request to the six routes, so the console's rate above +bounds a future charge on that path rather than this one. A value looser than the default is +named by `security_loosenings()`; [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md) has its row. + ## Audit Every authentication and authorization event is written to the durable `audit_log` with the acting diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index a9bfc53430..2fa043d0ed 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1634,7 +1634,8 @@ async def refuse_from_new_address(request: Request) -> None: ``auth.new_address_reverify_required`` and a notice, deduped and capped per session as :meth:`AuthService.flag_new_client_ip` says. - It is NOT in :func:`require`, deliberately: the base gate carries the monitoring polls, and an + It is NOT in :func:`require` or :func:`require_monitoring_read`, deliberately: those gates carry + the monitoring polls, and an operator whose address changes behind a NAT pool would be refused on every one until a step-up. Costs one session read per request while ``[auth].admin_new_ip_step_up`` is on, and one more @@ -1993,7 +1994,7 @@ def require_monitoring_read(*permissions: Permission) -> Callable[[Request], Awa Charged at ADMISSION, before the route does its work. A throttled read is logged (not silent), answered 429 with the actor's ``Retry-After``, and recorded as an ``auth.gate_refused`` row with - reason ``throttled``. It does not ask the new-address question: :func:`refuse_from_new_address` + reason ``throttled`` wherever :func:`_audited_permission` names one (on by default). It does not ask the new-address question: :func:`refuse_from_new_address` says why the monitoring polls stay outside it. No pace on the embedding/no-auth path (there is no per-actor identity to key on).""" diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 5ee182de08..bb36cabafb 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -9554,8 +9554,8 @@ def _auth_limit_loosenings(auth: AuthSettings) -> list[tuple[str, str]]: falsy count as "no limit on that dimension" and admits more as a count rises. It prunes every hit older than the window, so a SHORTER window admits more, and one of 0 or less prunes each hit before it is counted. A negative count refuses more, so it is not named; the admin-write - count and the two monitoring-read counts refuse a negative value at load (BACKLOG #3293), so - only the others reach here. A NaN or infinite + count (BACKLOG #3293) and the two monitoring-read counts (vault BACKLOG #1191) refuse a + negative value at load, so only the others reach here. A NaN or infinite window never reaches this function: the load refuses it (vault BACKLOG #2466), since a NaN or ``+inf`` one never prunes. A ``min_interval_seconds`` of 0 turns the gap off, and a shorter gap admits a faster burst. From 0ff96d4b2439e31cabbd0bc938681f37d3f8a7e0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 21:41:29 -0600 Subject: [PATCH 04/19] State what each monitoring-read paced route costs; add the changelog fragment Vault BACKLOG #1191. The require_monitoring_read docstring no longer claims all six routes scan the store: five do, and /metrics/history is paced by the Manager ruling. A changelog.d fragment records the pace. Text-only change after the last review round; no further review round was run, per the Manager. --- changelog.d/1191-monitoring-read-pace.security.md | 6 ++++++ messagefoundry/api/security.py | 9 ++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 changelog.d/1191-monitoring-read-pace.security.md diff --git a/changelog.d/1191-monitoring-read-pace.security.md b/changelog.d/1191-monitoring-read-pace.security.md new file mode 100644 index 0000000000..c905ba2df8 --- /dev/null +++ b/changelog.d/1191-monitoring-read-pace.security.md @@ -0,0 +1,6 @@ +- **The cost-bearing `monitoring:read` GETs are paced per account.** `GET /graph/edges`, `/status`, + `/stats`, `/metrics`, `/metrics/history` and `/connections` answer 429 with a `Retry-After` past + 600 reads per 60 s per account, the shipped default of the new `[auth].monitoring_read_rate_limit_*` + settings; the all-accounts count ships off. The web console's in-process reads of the same + handlers are not charged. The routes, the key and the basis of the default are in + [SECURITY.md](../docs/SECURITY.md), *Monitoring-read pacing*. (vault `BACKLOG #1191`) diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 2fa043d0ed..6078f5964b 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1988,9 +1988,12 @@ async def dependency(request: Request) -> Identity: def require_monitoring_read(*permissions: Permission) -> Callable[[Request], Awaitable[Identity]]: - """Like :func:`require`, plus a **per-actor pace** on the cost-bearing ``monitoring:read`` GETs - (vault BACKLOG #1191, ASVS 15.2.2): the routes that rebuild the wiring graph or scan the store - per call. docs/SECURITY.md, *Monitoring-read pacing*, names the routes and the default's basis. + """Like :func:`require`, plus a **per-actor pace** on six ``monitoring:read`` GETs (vault BACKLOG + #1191, ASVS 15.2.2). Five of them cost store or parse work per call: ``/graph/edges`` rebuilds + the wiring graph, and ``/status``, ``/stats``, ``/metrics`` and ``/connections`` read aggregates + whose cost grows with the store. ``/metrics/history`` copies an in-memory ring and reads no + store; it is paced by the Manager's ruling, because the console polls it beside + ``/graph/edges``. docs/SECURITY.md, *Monitoring-read pacing*, says the default's basis. Charged at ADMISSION, before the route does its work. A throttled read is logged (not silent), answered 429 with the actor's ``Retry-After``, and recorded as an ``auth.gate_refused`` row with From 30adb2a921ac22baa4d239e502627aeabd6d5d57 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 09:46:24 -0600 Subject: [PATCH 05/19] Monitoring-read pacing: correct the nine false statements the Lander's hold names The pacing record, the changelog fragment and the require_monitoring_read and refuse_from_new_address docstrings now state what the control does: - the six paced routes are named, and they share one budget per account, per API process, so N engine shards multiply it; - /ws/stats, /events, /connections/{name}/events and /config/provenance cost work and are not charged; /ws/stats can reach about 3,840 dashboard reads a minute on one account; - /metrics/history is no longer called cost-bearing; - the console is not charged (it reaches the handlers through require_ui), so the 600 is restated as sized from an uncharged path, 576 rounded up, with the charged clients named: the harness monitor (at most 80 a minute at its 1.5 s poll), a /metrics scrape and the load harness poller; - the bucket is shared with the other five paced routes, not every API read; - a refused read's Retry-After is the actor's wait, or the whole window while the global count is spent; - the "Manager's ruling" attribution is dropped (no decision record id found). Adds tests for the console staying uncharged and the global-spent Retry-After. No behaviour change. Vault BACKLOG #1191. --- .../1191-monitoring-read-pace.security.md | 12 +-- docs/CONFIGURATION.md | 2 +- docs/SECURITY-LOOSENING.md | 2 +- docs/SECURITY.md | 77 +++++++++++-------- messagefoundry/api/security.py | 22 ++++-- messagefoundry/auth/service.py | 4 +- messagefoundry/config/settings.py | 8 +- tests/test_monitoring_read_pacing.py | 53 ++++++++++++- 8 files changed, 128 insertions(+), 52 deletions(-) diff --git a/changelog.d/1191-monitoring-read-pace.security.md b/changelog.d/1191-monitoring-read-pace.security.md index c905ba2df8..e84065ba9e 100644 --- a/changelog.d/1191-monitoring-read-pace.security.md +++ b/changelog.d/1191-monitoring-read-pace.security.md @@ -1,6 +1,8 @@ -- **The cost-bearing `monitoring:read` GETs are paced per account.** `GET /graph/edges`, `/status`, - `/stats`, `/metrics`, `/metrics/history` and `/connections` answer 429 with a `Retry-After` past - 600 reads per 60 s per account, the shipped default of the new `[auth].monitoring_read_rate_limit_*` - settings; the all-accounts count ships off. The web console's in-process reads of the same - handlers are not charged. The routes, the key and the basis of the default are in +- **Six `monitoring:read` GETs are paced per account.** `GET /graph/edges`, `/status`, `/stats`, + `/metrics`, `/metrics/history` and `/connections` share one budget per account: past 600 reads per + 60 s across the six, the shipped default of the new `[auth].monitoring_read_rate_limit_*` + settings, a read is answered 429 with a `Retry-After`. The budget is per API process, so N engine + shards multiply it by N; the all-accounts count ships off. The web console's in-process reads of + the same handlers are not charged, and neither are `/ws/stats`, `/events`, + `/connections/{name}/events` or `/config/provenance`. The key and the basis of the default are in [SECURITY.md](../docs/SECURITY.md), *Monitoring-read pacing*. (vault `BACKLOG #1191`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index eabfe957b6..9e2df2fcd9 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -829,7 +829,7 @@ document ([SECURITY-DOCS-POLICY.md](SECURITY-DOCS-POLICY.md)). | `phi_read_rate_limit_per_actor` | int | 120 | max PHI reads per user per window (generous — clears console/human use; `0` disables this dimension) | | `phi_read_rate_limit_global` | int | 0 | max PHI reads across all users per window (`0` = off) | | `phi_read_rate_limit_window_seconds` | float | 60 | sliding-window length | -| `monitoring_read_rate_limit_enabled` | bool | `true` | per-actor pace on the six cost-bearing `monitoring:read` GETs (vault BACKLOG #1191, ASVS 15.2.2), charged at admission by `require_monitoring_read`; the routes, the key and the measured basis of the default are in [SECURITY.md](SECURITY.md), *Monitoring-read pacing* | +| `monitoring_read_rate_limit_enabled` | bool | `true` | per-actor pace on six `monitoring:read` GETs, one budget per account per API process (vault BACKLOG #1191, ASVS 15.2.2), charged at admission by `require_monitoring_read`; the routes, the key and the measured basis of the default are in [SECURITY.md](SECURITY.md), *Monitoring-read pacing* | | `monitoring_read_rate_limit_per_actor` | int | 600 | max monitoring reads per user per window (`0` disables this dimension) | | `monitoring_read_rate_limit_global` | int | 0 | max monitoring reads across all users per window (`0` = off) | | `monitoring_read_rate_limit_window_seconds` | float | 60 | sliding-window length; must be above `0` | diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index 1bcf0370d7..d99b846087 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -1175,7 +1175,7 @@ count is above `0` (vault BACKLOG #2613). > `0` or less (the load refuses it). With the limiter off, its parts are not named again. > `monitoring_read_rate_limit_global` ships **off** (`0`), so no value of it is looser than the > default and it is never named. -- **What you lose:** the per-account pace on the cost-bearing `monitoring:read` GETs +- **What you lose:** the per-account pace on six `monitoring:read` GETs ([SECURITY.md](SECURITY.md), *Monitoring-read pacing*, names them). One signed-in account can make the engine rebuild the wiring graph and scan the store faster, up to as fast as it answers. - **When acceptable:** a monitoring tool on one known account that polls faster than the default diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 23f9b54f06..845f715b14 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7684,41 +7684,58 @@ IP is a backlog follow-up). #### Monitoring-read pacing -Vault BACKLOG #1191 (ASVS 15.2.2). Six `monitoring:read` GETs cost work that grows per call: -`GET /graph/edges` rebuilds the wiring graph, and `GET /status`, `/stats`, `/metrics` and -`/connections` read aggregates whose cost grows with the store. `GET /metrics/history` copies the -in-memory metrics ring and reads no store; it is paced with them because the console reads it beside -`/graph/edges`. They are -gated by `require_monitoring_read`, which charges a per-actor sliding window at admission, before -the route's own work. The other `monitoring:read` routes stay on plain `require`. +Vault BACKLOG #1191 (ASVS 15.2.2). `require_monitoring_read` gates six `monitoring:read` GETs: +`GET /graph/edges`, `/status`, `/stats`, `/metrics`, `/metrics/history` and `/connections`. Five of +them cost work per call: `/graph/edges` rebuilds the wiring graph, and `/status`, `/stats`, +`/metrics` and `/connections` read aggregates whose cost grows with the store. `/metrics/history` +copies the in-memory metrics ring and reads no store; it is paced with them because the console's +Flow and trends page reads it beside `/graph/edges`. The gate charges a per-actor sliding window at +admission, before the route's own work. The six routes share ONE budget per account: a read of any +of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N +(*Business-logic limits* above). + +Other `monitoring:read` reads that cost work are **not** charged. At least `GET /events`, +`GET /connections/{name}/events` and `GET /config/provenance` stay on plain `require`, and the +`/ws/stats` socket runs the connections-dashboard read (`_dashboard_rows`, the work behind +`GET /connections`) once per frame, a frame a second, with no charge here. The socket cap of 64 is +per API process, not per account, so one account may hold all 64: about 3,840 such reads a minute, +with no 429. **Key.** `identity.user_id` of the bearer session the request presents. A Prometheus-style scraper on `/metrics` authenticates the same way, so it draws the bucket of the account its token belongs -to, shared with that account's other API reads. A verified mTLS client certificate does not reach -these routes: the certificate plane is `require_service_cert` alone, and these six use the bearer -ladder. With `allow_no_auth` there is no actor, so nothing is charged. - -**How the default was set, measured from the console at this release.** One console tab shows one -page. Its timers, read from `messagefoundry_webconsole/static/app.js` and the pages that set them: -the nav poll of `/ui/nav-status` every 15 s, on every page, which calls the `GET /status` handler; -the Connections page's poll of `/ui/connections` every 5 s, which calls the `GET /connections` -handler (paused while `/ws/stats` is open; the measurement counts it running); and the Flow and -trends page's `/ui/monitoring/live` every 5 s, which calls the `GET /graph/edges` and -`GET /metrics/history` handlers. The worst page is Flow and trends: 24 + 4 = 28 handler calls per -minute per tab. A scraper on `/metrics` every 15 s adds 4 per minute. The rule is at least 4 times -(tabs x 28 + 4), rounded up, and never below 600 per 60 s. For five tabs that is 4 x 144 = 576, so -the floor of 600 applies. 600 per minute is 21 such tabs at 1x, or 5 tabs at the 4x margin. The -tab count of five is a judgment, not a measurement. The global count ships off, as -`phi_read_rate_limit_global` does. That measurement is of the console, which this pace does not -charge (below). The in-repo load harness's poller makes 3 charged reads per sample as one account, -720 per minute at the 0.25 s interval two of its profiles use, so the engines it spawns run with the -pace off (`harness/load/failover.py`, `EngineNode`). An engine it attaches to by URL keeps the pace. +to, shared with that account's reads of the other five paced routes. A verified mTLS client +certificate does not reach these routes: the certificate plane is `require_service_cert` alone, and +these six use the bearer ladder. With `allow_no_auth` there is no actor, so nothing is charged. + +**Who is charged, and how the default was set.** The web console is not charged (below). The +charged clients in this repository are at least: + +- the standalone test harness's monitor (`harness/monitor.py`), which reads `GET /stats` and + `GET /connections` every 1.5 s (`_POLL_INTERVAL_MS`), at most 80 charged reads per minute per open + monitor window. Its dead-letter read is not paced; +- a scraper on `/metrics`, 4 per minute at a 15 s scrape; +- the load harness's poller, 3 charged reads per sample as one account, 720 per minute at the + 0.25 s interval two of its profiles use. The engines it spawns therefore run with the pace off + (`harness/load/failover.py`, `EngineNode`); an engine it attaches to by URL keeps the pace. + +The 600 per 60 s default was sized from the console's own polling, measured at this release from +`messagefoundry_webconsole/static/app.js` and the pages that set its timers, as the bound a future +charge on the console path would need. The console is not charged today, so this sizing is of an +uncharged path. One console tab shows one page: the nav poll of `/ui/nav-status` every 15 s, on +every page, calls the `GET /status` handler; the Connections page's poll of `/ui/connections` every +5 s calls the `GET /connections` handler (paused while `/ws/stats` is open; the measurement counts +it running); and the Flow and trends page's `/ui/monitoring/live` every 5 s calls the +`GET /graph/edges` and `GET /metrics/history` handlers. The worst page is Flow and trends: 24 + 4 = +28 handler calls per minute per tab. Five tabs plus a 15 s `/metrics` scrape is 144 per minute; +four times that is 576, and 600 is a round figure chosen above it. The tab count of five and the +margin of four are judgments, not measurements. Against the charged clients above, 600 per minute +admits seven harness monitor windows (560) on one account, plus a `/metrics` scrape. The global +count ships off, as `phi_read_rate_limit_global` does. **What it does not charge.** The console calls these handlers in process, through `require_ui`, -so the route's own dependency does not run and a console tab spends none of this budget. Measured -the other way, a console tab makes no HTTP request to the six routes, so the console's rate above -bounds a future charge on that path rather than this one. A value looser than the default is -named by `security_loosenings()`; [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md) has its row. +so the route's own dependency does not run and a console tab spends none of this budget; a console +tab makes no HTTP request to the six routes. A value looser than the default is named by +`security_loosenings()`; [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md) has its row. ## Audit diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 6078f5964b..c1d32aa913 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1635,8 +1635,10 @@ async def refuse_from_new_address(request: Request) -> None: :meth:`AuthService.flag_new_client_ip` says. It is NOT in :func:`require` or :func:`require_monitoring_read`, deliberately: those gates carry - the monitoring polls, and an - operator whose address changes behind a NAT pool would be refused on every one until a step-up. + the JSON API's repeated monitoring reads, such as the test harness monitor's poll and a + ``/metrics`` scraper, and an operator whose address changes behind a NAT pool would be refused + on every one until a step-up. The web console's in-process reads go through ``require_ui`` and + reach neither gate. Costs one session read per request while ``[auth].admin_new_ip_step_up`` is on, and one more on a refusal, to pick its wording. The gate has @@ -1992,14 +1994,18 @@ def require_monitoring_read(*permissions: Permission) -> Callable[[Request], Awa #1191, ASVS 15.2.2). Five of them cost store or parse work per call: ``/graph/edges`` rebuilds the wiring graph, and ``/status``, ``/stats``, ``/metrics`` and ``/connections`` read aggregates whose cost grows with the store. ``/metrics/history`` copies an in-memory ring and reads no - store; it is paced by the Manager's ruling, because the console polls it beside - ``/graph/edges``. docs/SECURITY.md, *Monitoring-read pacing*, says the default's basis. + store; it is paced with them because the console's Flow and trends page reads it beside + ``/graph/edges``. The console itself is not charged: it calls these handlers in process + through ``require_ui`` (``messagefoundry_webconsole/_auth.py``), so this dependency never runs + for it. The six share one budget per account, per API process. docs/SECURITY.md, + *Monitoring-read pacing*, says the default's basis. Charged at ADMISSION, before the route does its work. A throttled read is logged (not silent), - answered 429 with the actor's ``Retry-After``, and recorded as an ``auth.gate_refused`` row with - reason ``throttled`` wherever :func:`_audited_permission` names one (on by default). It does not ask the new-address question: :func:`refuse_from_new_address` - says why the monitoring polls stay outside it. No pace on the embedding/no-auth path (there is - no per-actor identity to key on).""" + answered 429 with a ``Retry-After`` (:func:`enforce_monitoring_read_pacing` says its value), and + recorded as an ``auth.gate_refused`` row with reason ``throttled`` wherever + :func:`_audited_permission` names one (on by default). It does not ask the new-address + question: :func:`refuse_from_new_address` says why these reads stay outside it. No pace on the + embedding/no-auth path (there is no per-actor identity to key on).""" async def dependency(request: Request) -> Identity: auth, identity = await _admit(request, permissions, mfa_gate=True) diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 44e5902909..f1917e2b1c 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -4296,7 +4296,7 @@ def __init__( if settings.phi_read_rate_limit_enabled else None ) - # Per-actor pacing for the cost-bearing monitoring:read GETs (vault BACKLOG #1191, ASVS + # Per-actor pacing for six monitoring:read GETs (vault BACKLOG #1191, ASVS # 15.2.2), consulted by require_monitoring_read. Its own bucket, so dashboard polling never # spends the PHI-read budget. self._monitoring_read_limiter: SlidingWindowRateLimiter | None = ( @@ -4799,7 +4799,7 @@ def phi_read_retry_after(self, actor: str) -> int: return _retry_after_seconds(self._phi_read_limiter, actor) def allow_monitoring_read(self, actor: str) -> bool: - """Per-actor pacing for the cost-bearing monitoring:read GETs (vault BACKLOG #1191, ASVS + """Per-actor pacing for six monitoring:read GETs (vault BACKLOG #1191, ASVS 15.2.2). True = proceed; False = throttle. Always True when the limiter is disabled.""" if self._monitoring_read_limiter is None: return True diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index e86c823f36..1e13e67476 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -4029,7 +4029,7 @@ class AuthSettings(_Section): default=60.0, allow_inf_nan=False, le=_RATE_WINDOW_MAX_SECONDS ) - # Per-actor pacing on the cost-bearing monitoring:read GETs (vault BACKLOG #1191, ASVS 15.2.2): + # Per-actor pacing on six monitoring:read GETs (vault BACKLOG #1191, ASVS 15.2.2): # /graph/edges, /status, /stats, /metrics, /metrics/history and /connections, charged at # admission by require_monitoring_read. The default's measured basis and multiplier are written # once, in docs/SECURITY.md, "Monitoring-read pacing". In-process only, like the PHI-read @@ -9878,13 +9878,13 @@ def _window( ) # --- the monitoring-read limiter (vault BACKLOG #1191, ASVS 15.2.2): per actor, on the six - # cost-bearing monitoring:read GETs. Its window cannot be 0 or less (gt=0 at load), and the + # paced monitoring:read GETs. Its window cannot be 0 or less (gt=0 at load), and the # all-users count ships OFF (0), so neither has an off value to name. if not auth.monitoring_read_rate_limit_enabled: out.append( ( "monitoring_read_rate_limit_enabled", - "the cost-bearing monitoring reads (the wiring graph, status, stats, metrics and " + "the six paced monitoring reads (the wiring graph, status, stats, metrics and " "the connections dashboard) have NO pace -- one signed-in account may make the " "engine rebuild the graph and scan the store as fast as it answers", ) @@ -9901,7 +9901,7 @@ def _window( auth.monitoring_read_rate_limit_per_actor, what="the per-account monitoring-read limit", so=( - "one signed-in account may make that many cost-bearing monitoring reads per " + "one signed-in account may make that many paced monitoring reads per " "window before it is refused" ), off=( diff --git a/tests/test_monitoring_read_pacing.py b/tests/test_monitoring_read_pacing.py index 7cb5692566..686da1a14d 100644 --- a/tests/test_monitoring_read_pacing.py +++ b/tests/test_monitoring_read_pacing.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""Per-actor pacing on the cost-bearing monitoring:read GETs (vault BACKLOG #1191, ASVS 15.2.2). +"""Per-actor pacing on six monitoring:read GETs (vault BACKLOG #1191, ASVS 15.2.2). Driven through the real routes, so a route that drops back to plain ``require`` goes red here. The six paced routes, their key and the default's basis are stated in docs/SECURITY.md, @@ -170,3 +170,54 @@ async def test_disabled_knob_means_no_pacing(engine: Engine) -> None: h = await _bearer(c, "vw") for _ in range(5): assert (await c.get("/status", headers=h)).status_code == 200 + + +async def test_retry_after_is_the_whole_window_while_the_global_count_is_spent( + engine: Engine, monkeypatch: pytest.MonkeyPatch +) -> None: + """With the all-accounts count spent, the value is the whole window, not the refused actor's + own wait: that wait depends on other accounts' reads, which a caller must not read.""" + clock = [1000.0] + monkeypatch.setattr( + "messagefoundry.auth.ratelimit.time", SimpleNamespace(monotonic=lambda: clock[0]) + ) + service = await _service( + engine, + monitoring_read_rate_limit_per_actor=100, + monitoring_read_rate_limit_global=1, + monitoring_read_rate_limit_window_seconds=37.5, + ) + async with _client(engine, service) as c: + h_vw = await _bearer(c, "vw") + h_other = await _bearer(c, "other") + assert (await c.get("/stats", headers=h_vw)).status_code == 200 # t=1000, global full + clock[0] = 1020.0 + # "other" has no reads of its own; the global read leaves at 1037.5 (17.5 s away), but + # the header names the whole window. + refused = await c.get("/stats", headers=h_other) + assert (refused.status_code, refused.headers["Retry-After"]) == (429, "38") + + +async def test_the_web_console_reads_are_not_charged(engine: Engine) -> None: + """The console calls the paced handlers in process through ``require_ui``, so the route's own + dependency never runs and the account's budget is untouched (docs/SECURITY.md, *Monitoring-read + pacing*, *What it does not charge*).""" + service = await _service(engine, monitoring_read_rate_limit_per_actor=1) + transport = httpx.ASGITransport( + app=create_app(engine, auth=service, serve_ui=True), client=("127.0.0.1", 123) + ) + async with httpx.AsyncClient(transport=transport, base_url="http://t") as c: + r = await c.post( + "/ui/login", + data={"username": "vw", "password": PW}, + headers={"Sec-Fetch-Site": "same-origin"}, + ) + assert r.status_code in (200, 303), r.status_code + for path in ("/ui/nav-status", "/ui/connections", "/ui/monitoring/live"): + for _ in range(3): + assert (await c.get(path)).status_code == 200, path + # The same account's budget of 1 is still whole: one bearer read is admitted, the next + # is refused, so the pace itself is live. + h = await _bearer(c, "vw") + assert (await c.get("/status", headers=h)).status_code == 200 + assert (await c.get("/status", headers=h)).status_code == 429 From b8dc537b83ae1966e10247a87041cfd40eef4955 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:22:13 -0600 Subject: [PATCH 06/19] Monitoring-read pacing: repair the review round's false statements From code review round-319e02e744 on the hold fix: - the harness monitor's dead-letter read rides require_phi_read, so it is PHI-paced (120 a minute) and stops one account at three monitor windows; - /ws/stats runs the /stats aggregate every frame and the dashboard read only where the console is served; the uncharged surfaces now sit under "What it does not charge", with the console's own uncharged loop named; - the loosening row and the settings risk strings no longer say that turning the pace off is what exposes the work: they name the six JSON routes; - the new-address exemption no longer cites the harness monitor, whose dead-letter read takes the new-address refusal anyway; - /metrics/history: the console reason is kept as history, with the fact that its pace bounds only JSON clients; - the /connections reveal comment says the monitoring 429 comes before the scope check; the base-gate paragraph and its service.py twin name require_monitoring_read; - the changelog's uncharged list is "at least"; - the console test checks the session cookie and drops the nav-status leg, and _client() takes serve_ui. No behaviour change. Vault BACKLOG #1191. --- .../1191-monitoring-read-pace.security.md | 4 +- docs/SECURITY-LOOSENING.md | 6 ++- docs/SECURITY.md | 41 +++++++++++-------- messagefoundry/api/app.py | 4 +- messagefoundry/api/security.py | 7 ++-- messagefoundry/auth/service.py | 4 +- messagefoundry/config/settings.py | 11 ++--- tests/test_monitoring_read_pacing.py | 19 +++++---- 8 files changed, 56 insertions(+), 40 deletions(-) diff --git a/changelog.d/1191-monitoring-read-pace.security.md b/changelog.d/1191-monitoring-read-pace.security.md index e84065ba9e..24a9cdeebd 100644 --- a/changelog.d/1191-monitoring-read-pace.security.md +++ b/changelog.d/1191-monitoring-read-pace.security.md @@ -3,6 +3,6 @@ 60 s across the six, the shipped default of the new `[auth].monitoring_read_rate_limit_*` settings, a read is answered 429 with a `Retry-After`. The budget is per API process, so N engine shards multiply it by N; the all-accounts count ships off. The web console's in-process reads of - the same handlers are not charged, and neither are `/ws/stats`, `/events`, - `/connections/{name}/events` or `/config/provenance`. The key and the basis of the default are in + the same handlers are not charged, and neither are at least `/ws/stats`, `/events`, + `/connections/{name}/events` and `/config/provenance`. The key and the basis of the default are in [SECURITY.md](../docs/SECURITY.md), *Monitoring-read pacing*. (vault `BACKLOG #1191`) diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index d99b846087..d1489ac931 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -1175,9 +1175,11 @@ count is above `0` (vault BACKLOG #2613). > `0` or less (the load refuses it). With the limiter off, its parts are not named again. > `monitoring_read_rate_limit_global` ships **off** (`0`), so no value of it is looser than the > default and it is never named. -- **What you lose:** the per-account pace on six `monitoring:read` GETs +- **What you lose:** the per-account pace on six `monitoring:read` GETs of the JSON API ([SECURITY.md](SECURITY.md), *Monitoring-read pacing*, names them). One signed-in account can make - the engine rebuild the wiring graph and scan the store faster, up to as fast as it answers. + the engine rebuild the wiring graph and scan the store through those routes faster, up to as fast + as it answers. With the pace on, the same work stays reachable unpaced through the web console's + in-process reads and the `/ws/stats` socket; that section, *What it does not charge*, says how. - **When acceptable:** a monitoring tool on one known account that polls faster than the default allows, on a host no untrusted client can reach. Prefer a modest raise to turning it off. - **Compensating controls:** keep sessions short, and restrict who reaches the API with diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 845f715b14..a6d680d776 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -4702,7 +4702,8 @@ alone: belongs to a reverse proxy, declare that proxy in `[api].trusted_proxies`, so the engine compares the address the proxy forwards. Failing that, turning the signal off is the [named loosening](SECURITY-LOOSENING.md#authadmin_new_ip_step_up--false--a-new-client-address-mid-session-goes-unchallenged). - **The base gate (`require`) still never asks, deliberately.** The monitoring polls ride it, and + **The base gate (`require`) and `require_monitoring_read` still never ask, deliberately.** The + JSON monitoring reads ride them, and an operator whose address changes behind a NAT pool, or behind a proxy not listed in `[api].trusted_proxies`, would otherwise be refused on every poll until a step-up. So a token replayed from a new address still reads the non-PHI monitoring routes. It is @@ -7688,19 +7689,13 @@ Vault BACKLOG #1191 (ASVS 15.2.2). `require_monitoring_read` gates six `monitori `GET /graph/edges`, `/status`, `/stats`, `/metrics`, `/metrics/history` and `/connections`. Five of them cost work per call: `/graph/edges` rebuilds the wiring graph, and `/status`, `/stats`, `/metrics` and `/connections` read aggregates whose cost grows with the store. `/metrics/history` -copies the in-memory metrics ring and reads no store; it is paced with them because the console's -Flow and trends page reads it beside `/graph/edges`. The gate charges a per-actor sliding window at +copies the in-memory metrics ring and reads no store; it was put in the set because the console's +Flow and trends page reads it beside `/graph/edges`, but the console is not charged (below), so +its pace bounds only JSON clients. The gate charges a per-actor sliding window at admission, before the route's own work. The six routes share ONE budget per account: a read of any of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N (*Business-logic limits* above). -Other `monitoring:read` reads that cost work are **not** charged. At least `GET /events`, -`GET /connections/{name}/events` and `GET /config/provenance` stay on plain `require`, and the -`/ws/stats` socket runs the connections-dashboard read (`_dashboard_rows`, the work behind -`GET /connections`) once per frame, a frame a second, with no charge here. The socket cap of 64 is -per API process, not per account, so one account may hold all 64: about 3,840 such reads a minute, -with no 429. - **Key.** `identity.user_id` of the bearer session the request presents. A Prometheus-style scraper on `/metrics` authenticates the same way, so it draws the bucket of the account its token belongs to, shared with that account's reads of the other five paced routes. A verified mTLS client @@ -7712,7 +7707,9 @@ charged clients in this repository are at least: - the standalone test harness's monitor (`harness/monitor.py`), which reads `GET /stats` and `GET /connections` every 1.5 s (`_POLL_INTERVAL_MS`), at most 80 charged reads per minute per open - monitor window. Its dead-letter read is not paced; + monitor window. Its third read, `GET /dead-letters`, is not charged here: it rides + `require_phi_read`, so it spends the PHI-read budget (`phi_read_rate_limit_*`, 120 per 60 s by + default) at 40 a minute per window, and that budget binds first; - a scraper on `/metrics`, 4 per minute at a 15 s scrape; - the load harness's poller, 3 charged reads per sample as one account, 720 per minute at the 0.25 s interval two of its profiles use. The engines it spawns therefore run with the pace off @@ -7728,14 +7725,26 @@ it running); and the Flow and trends page's `/ui/monitoring/live` every 5 s call `GET /graph/edges` and `GET /metrics/history` handlers. The worst page is Flow and trends: 24 + 4 = 28 handler calls per minute per tab. Five tabs plus a 15 s `/metrics` scrape is 144 per minute; four times that is 576, and 600 is a round figure chosen above it. The tab count of five and the -margin of four are judgments, not measurements. Against the charged clients above, 600 per minute -admits seven harness monitor windows (560) on one account, plus a `/metrics` scrape. The global -count ships off, as `phi_read_rate_limit_global` does. +margin of four are judgments, not measurements. The count leaves out the Connections page's +`/ws/stats` socket, which this pace never charges and whose per-frame work is described below. Against +the charged clients above, 600 per minute admits seven harness monitor windows (560) on one account, +but the monitor's dead-letter read stops the account at three windows on the PHI-read default. The +global count ships off, as `phi_read_rate_limit_global` does. **What it does not charge.** The console calls these handlers in process, through `require_ui`, so the route's own dependency does not run and a console tab spends none of this budget; a console -tab makes no HTTP request to the six routes. A value looser than the default is named by -`security_loosenings()`; [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md) has its row. +tab makes no HTTP request to the six routes. So a signed-in console session that loops +`/ui/monitoring/live`, `/ui/connections` or `/ui/nav-status` drives the same work with no 429. + +Other `monitoring:read` reads that cost work are not charged either. At least `GET /events`, +`GET /connections/{name}/events` and `GET /config/provenance` stay on plain `require`, and the +`/ws/stats` socket, a frame a second, runs the `/stats` store aggregate on every frame and, where +the web console is served, the connections-dashboard read (`_dashboard_rows`, the work behind +`GET /connections`) too, with no charge here. The socket cap of 64 is per API process, not per +account, so one account may hold all 64: about 3,840 of each such read a minute, with no 429. + +A value looser than the default is named by `security_loosenings()`; +[SECURITY-LOOSENING.md](SECURITY-LOOSENING.md) has its row. ## Audit diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 5dc94978b6..a6ded3f3ea 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -5699,7 +5699,9 @@ async def list_connections( # Per-channel RBAC, as on GET /connections/{name}/events: a reveal naming a connection # outside the caller's scope is refused and audited as a channel denial. Checked BEFORE the # reveal is admitted, so a refused name spends no PHI-read budget and cannot be hidden - # behind a 429. A scoped caller's dashboard carries no outbound rows at all. + # behind the PHI-read 429. It can still be hidden behind the monitoring-read 429: that pace + # (require_monitoring_read) is charged in this route's dependency, before this check runs. + # A scoped caller's dashboard carries no outbound rows at all. if reveal is not None: await _control_guard(engine, identity, reveal, client_ip(request)) await _admit_reveal(request, identity, reveal) diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index c1d32aa913..e46ab10912 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1635,8 +1635,7 @@ async def refuse_from_new_address(request: Request) -> None: :meth:`AuthService.flag_new_client_ip` says. It is NOT in :func:`require` or :func:`require_monitoring_read`, deliberately: those gates carry - the JSON API's repeated monitoring reads, such as the test harness monitor's poll and a - ``/metrics`` scraper, and an operator whose address changes behind a NAT pool would be refused + the JSON API's repeated monitoring reads, such as a ``/metrics`` scraper, and an operator whose address changes behind a NAT pool would be refused on every one until a step-up. The web console's in-process reads go through ``require_ui`` and reach neither gate. @@ -1994,8 +1993,8 @@ def require_monitoring_read(*permissions: Permission) -> Callable[[Request], Awa #1191, ASVS 15.2.2). Five of them cost store or parse work per call: ``/graph/edges`` rebuilds the wiring graph, and ``/status``, ``/stats``, ``/metrics`` and ``/connections`` read aggregates whose cost grows with the store. ``/metrics/history`` copies an in-memory ring and reads no - store; it is paced with them because the console's Flow and trends page reads it beside - ``/graph/edges``. The console itself is not charged: it calls these handlers in process + store; it was put in the set because the console's Flow and trends page reads it beside + ``/graph/edges``, so its pace bounds only JSON clients, because the console is not charged: it calls these handlers in process through ``require_ui`` (``messagefoundry_webconsole/_auth.py``), so this dependency never runs for it. The six share one budget per account, per API process. docs/SECURITY.md, *Monitoring-read pacing*, says the default's basis. diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index f1917e2b1c..437861345f 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -16819,8 +16819,8 @@ async def flag_new_client_ip( reads, the console's ``phi=True`` arm) and the paced writes (``require_paced``, the console's write gate), which refuse on ``True``. Not every caller refuses: the console's reauth-only action gate records the signal on a request it is refusing for another reason. - The JSON plane's base gate (``require``) never calls it, so the monitoring polls are not - refused. The console's base gate (``require_ui``) calls it for a PHI read or a write, and, + The JSON plane's base gate (``require``) and its monitoring-read gate + (``require_monitoring_read``) never call it, so the JSON monitoring reads are not refused. The console's base gate (``require_ui``) calls it for a PHI read or a write, and, since BACKLOG #5646, on every request a step-up gate serves, GET included, because the step-up factories hand it their question; the console's plain monitoring polls ride none of those, so they are not refused either. diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 1e13e67476..ad55619f0d 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -9884,9 +9884,10 @@ def _window( out.append( ( "monitoring_read_rate_limit_enabled", - "the six paced monitoring reads (the wiring graph, status, stats, metrics and " - "the connections dashboard) have NO pace -- one signed-in account may make the " - "engine rebuild the graph and scan the store as fast as it answers", + "the six paced monitoring reads (the wiring graph, status, stats, metrics, " + "metrics history and the connections dashboard) have NO pace on the JSON API -- " + "one signed-in account may make the engine rebuild the graph and scan the store " + "through them as fast as it answers", ) ) elif _window( @@ -9906,8 +9907,8 @@ def _window( ), off=( "there is no per-account monitoring-read limit, so one signed-in account may " - "drive the graph rebuild and the store scans as fast as the engine answers (only " - "an all-users limit, if one is set, holds)" + "drive the graph rebuild and the store scans through the six JSON routes as fast " + "as the engine answers (only an all-users limit, if one is set, holds)" ), ) diff --git a/tests/test_monitoring_read_pacing.py b/tests/test_monitoring_read_pacing.py index 686da1a14d..6f50ff4a94 100644 --- a/tests/test_monitoring_read_pacing.py +++ b/tests/test_monitoring_read_pacing.py @@ -68,8 +68,10 @@ async def _service(engine: Engine, **overrides: object) -> AuthService: return service -def _client(engine: Engine, service: AuthService) -> httpx.AsyncClient: - transport = httpx.ASGITransport(app=create_app(engine, auth=service), client=("127.0.0.1", 123)) +def _client(engine: Engine, service: AuthService, *, serve_ui: bool = False) -> httpx.AsyncClient: + transport = httpx.ASGITransport( + app=create_app(engine, auth=service, serve_ui=serve_ui), client=("127.0.0.1", 123) + ) return httpx.AsyncClient(transport=transport, base_url="http://t") @@ -203,17 +205,18 @@ async def test_the_web_console_reads_are_not_charged(engine: Engine) -> None: dependency never runs and the account's budget is untouched (docs/SECURITY.md, *Monitoring-read pacing*, *What it does not charge*).""" service = await _service(engine, monitoring_read_rate_limit_per_actor=1) - transport = httpx.ASGITransport( - app=create_app(engine, auth=service, serve_ui=True), client=("127.0.0.1", 123) - ) - async with httpx.AsyncClient(transport=transport, base_url="http://t") as c: + async with _client(engine, service, serve_ui=True) as c: r = await c.post( "/ui/login", data={"username": "vw", "password": PW}, headers={"Sec-Fetch-Site": "same-origin"}, ) - assert r.status_code in (200, 303), r.status_code - for path in ("/ui/nav-status", "/ui/connections", "/ui/monitoring/live"): + # A failed sign-in also answers 303, so the session cookie is what proves it worked. + assert r.status_code == 303 and c.cookies.get("mf_session"), r.status_code + # Signed out, these pages answer 303; a 200 here means the signed-in handler ran. Each + # calls a paced handler (``/ui/connections`` the ``GET /connections`` one, + # ``/ui/monitoring/live`` the ``GET /graph/edges`` and ``/metrics/history`` ones). + for path in ("/ui/connections", "/ui/monitoring/live"): for _ in range(3): assert (await c.get(path)).status_code == 200, path # The same account's budget of 1 is still whole: one bearer read is admitted, the next From bfd5ee13e3defff4e385393f1d2e51e0593c3545 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:59:36 -0600 Subject: [PATCH 07/19] Monitoring-read pacing: repair review round 2's statements From code review round-04a5efb96b: - service.py and the new-address docstring say a monitoring reveal read does take the new-address refusal; the exemption's reason names a JSON client behind a NAT pool or an unlisted proxy, not the console; - the SECURITY.md limiter row and the CONFIGURATION.md admin_new_ip_step_up row name require_monitoring_read beside require; - "measured basis" is now "basis" in CONFIGURATION.md and settings.py, since the record says the tab count and margin are judgments; - the /metrics/history docstring sentence no longer reads as a causal claim; - the three-window harness monitor sentence says what happens past it; - the console-loop claim names only the two pages the test drives; - the edited docstring lines are wrapped to 100 columns. Text only. Vault BACKLOG #1191. --- docs/CONFIGURATION.md | 4 ++-- docs/SECURITY.md | 10 ++++++---- messagefoundry/api/security.py | 12 +++++++----- messagefoundry/auth/service.py | 4 +++- messagefoundry/config/settings.py | 2 +- 5 files changed, 19 insertions(+), 13 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 9e2df2fcd9..902ba53d6f 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -829,7 +829,7 @@ document ([SECURITY-DOCS-POLICY.md](SECURITY-DOCS-POLICY.md)). | `phi_read_rate_limit_per_actor` | int | 120 | max PHI reads per user per window (generous — clears console/human use; `0` disables this dimension) | | `phi_read_rate_limit_global` | int | 0 | max PHI reads across all users per window (`0` = off) | | `phi_read_rate_limit_window_seconds` | float | 60 | sliding-window length | -| `monitoring_read_rate_limit_enabled` | bool | `true` | per-actor pace on six `monitoring:read` GETs, one budget per account per API process (vault BACKLOG #1191, ASVS 15.2.2), charged at admission by `require_monitoring_read`; the routes, the key and the measured basis of the default are in [SECURITY.md](SECURITY.md), *Monitoring-read pacing* | +| `monitoring_read_rate_limit_enabled` | bool | `true` | per-actor pace on six `monitoring:read` GETs, one budget per account per API process (vault BACKLOG #1191, ASVS 15.2.2), charged at admission by `require_monitoring_read`; the routes, the key and the basis of the default are in [SECURITY.md](SECURITY.md), *Monitoring-read pacing* | | `monitoring_read_rate_limit_per_actor` | int | 600 | max monitoring reads per user per window (`0` disables this dimension) | | `monitoring_read_rate_limit_global` | int | 0 | max monitoring reads across all users per window (`0` = off) | | `monitoring_read_rate_limit_window_seconds` | float | 60 | sliding-window length; must be above `0` | @@ -843,7 +843,7 @@ document ([SECURITY-DOCS-POLICY.md](SECURITY-DOCS-POLICY.md)). | `totp_skew_steps` | int | `0` | TOTP clock-skew tolerance in 30 s steps applied at verify time (BACKLOG #187, ASVS 6.5.5). **Default `0` = STRICT: only the current 30 s step verifies** (tightest replay window — a captured code is valid at most for the rest of its own step). Set `1` (or `2`) — the documented opt-out — to restore RFC-6238 network-delay / clock-drift tolerance (`1` also accepts the immediately-prior and the fast-clock-clamped next step, i.e. the historical ±1 behaviour; the forward step is clamped to the current step so it never advances the single-use high-water mark). Range 0–2. | | `mfa_recovery_code_count` | int | 10 | single-use recovery codes minted at TOTP enrollment (the lost-authenticator escape hatch; `0` disables them, leaving an admin reset as the only recovery path). Range 0–50. | | `mfa_verify_min_elapsed_seconds` | float | 1.0 | the least time between sign-in and the second factor ([BACKLOG #2301](BACKLOG.md), ASVS 2.4.2). It covers a TOTP code, a recovery code and a passkey on an MFA-pending session. It also covers the two enrolment legs, `POST /me/mfa/confirm` and a passkey registration, when they would satisfy a pending session ([BACKLOG #2389](BACKLOG.md)). One that arrives sooner after the session was minted gets the leg's ordinary failure, such as `401 invalid code` on `POST /auth/mfa-verify` and `400 invalid code` on `POST /me/mfa/confirm`. The response says nothing about timing, though a caller that knows its proof is good, or resubmits it, can tell the floor fired. It is audited with `reason=too_early`, charges no lockout and spends no code or passkey challenge. On an enrolment it runs from sign-in, not from the enrolment's begin. [SECURITY.md](SECURITY.md), *Two second steps have a time floor too*, lists at least the legs' answers and the timing tells, kept or left open, with the reasons ([BACKLOG #3194](BACKLOG.md)). Under the default `require_action_step_up`, the confirm route has already spent its single-use password step-up, as it does for a wrong code. A session whose factor is already satisfied, or that owes none, is not floored. The default is a **provisional** human-timing floor from the keystroke-level model, derived in the comment on the setting. `0` turns it off | -| `admin_new_ip_step_up` | bool | `true` | admin-interface contextual-risk signal (WP-L3-13, ASVS 8.4.2): when on, a step-up (sensitive admin) request from a client IP the session has not verified from emits an `auth.new_address_reverify_required` audit + notice and **forces a fresh step-up** (a re-verify from that address clears it). Step-up-forcing only — never changes an RBAC decision. Since vault BACKLOG #2620 at least the PHI reads and the paced writes refuse a new address the same way, and the base gate never asks; [SECURITY.md](SECURITY.md#administrative-interface-defense-in-depth-wp-l3-13-asvs-842) names the gates. The audit + notice are debounced and capped per session in each engine process, as [SECURITY.md](SECURITY.md#administrative-interface-defense-in-depth-wp-l3-13-asvs-842) states. **On by default** since BACKLOG #288, and a no-op on loopback (`127.0.0.1` and `::1` are treated as one host). Setting it `false` is a **loosening** once auth is on — `security_loosenings()` names it; see [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md). See [SECURITY.md](SECURITY.md) "Administrative-interface defense-in-depth". | +| `admin_new_ip_step_up` | bool | `true` | admin-interface contextual-risk signal (WP-L3-13, ASVS 8.4.2): when on, a step-up (sensitive admin) request from a client IP the session has not verified from emits an `auth.new_address_reverify_required` audit + notice and **forces a fresh step-up** (a re-verify from that address clears it). Step-up-forcing only — never changes an RBAC decision. Since vault BACKLOG #2620 at least the PHI reads and the paced writes refuse a new address the same way, and the base gate (`require`) and `require_monitoring_read` never ask; [SECURITY.md](SECURITY.md#administrative-interface-defense-in-depth-wp-l3-13-asvs-842) names the gates. The audit + notice are debounced and capped per session in each engine process, as [SECURITY.md](SECURITY.md#administrative-interface-defense-in-depth-wp-l3-13-asvs-842) states. **On by default** since BACKLOG #288, and a no-op on loopback (`127.0.0.1` and `::1` are treated as one host). Setting it `false` is a **loosening** once auth is on — `security_loosenings()` names it; see [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md). See [SECURITY.md](SECURITY.md) "Administrative-interface defense-in-depth". | | `ad_enabled` | bool | `false` | **directory bind capability**: the engine binds to AD as the `ad_bind_dn` service account to resolve principals and their groups. Windows SSO (`kerberos_enabled`), OIDC (`oidc_enabled`) and the session reconciler each need it. It does **not** turn on a directory-password sign-in: that pathway is retired (BACKLOG #1137), and `POST /auth/login` with `provider=ad` is refused and audited. A bind **as the user** survives only as the step-up re-bind at `POST /me/reauth` and `POST /ui/reauth` | | `ad_server` | str | — | e.g. `ldaps://dc1.example.com:636` (required when `ad_enabled`) | | `ad_domain` | str | — | UPN suffix, e.g. `example.com` | diff --git a/docs/SECURITY.md b/docs/SECURITY.md index a6d680d776..611b43b69e 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5024,7 +5024,7 @@ slack. | Login attempt rate, per client IP **and** globally | `api.security.client_ip`, which returns the ASGI `scope["client"][0]` the *Client source network* row evaluates; an attempt with no address is counted under the literal `"unknown"` | > 10 attempts per IP (`login_rate_limit_per_ip`), or > 60 across all clients (`login_rate_limit_global`), in a rolling 60 s window (`login_rate_limit_window_seconds`); a refused attempt is not itself counted. How a paid passkey sign-in `POST /ui/login` is counted is stated once, under [WebAuthn passkeys](#webauthn-passkeys-wp-14b-adr-0068), *The combined passkey sign-in* | **THROTTLE** — 429 `too many attempts` with **no** `Retry-After` on the three JSON routes; 429 + a `Retry-After` of the whole sign-in window on `POST /ui/login` and on `POST /ui/login/passkey`, the passkey sign-in's begin leg; a **303** redirect to `/ui/login?e=rate_limited` (no 429, no `Retry-After`) on `GET /ui/sso`, `POST /ui/oidc/start` and `GET /ui/oidc/callback` (a sign-in return; a step-up return draws the ceremony budget, BACKLOG #3374), and on `GET /ui/oidc/start` only when its interstitial is skipped (see the [Route → limiter map](#route--limiter-map)). WARNING-logged, deliberately **not** audited | on, 10 / 60 / 60 s | `[auth].login_rate_limit_enabled` | | Credential-ceremony rate, per **actor** | `identity.user_id` (**not** an IP); on an IdP step-up's return, which has no session, the user id its staged flow names | > `login_rate_limit_per_ip` (10) ceremonies per actor per 60 s, on each of the actor's keys (the *Credential ceremonies* row of [Business-logic limits](#business-logic-limits-asvs-213) names them); **no** global dimension (`glob=0`, deliberately) | **THROTTLE** 429, logged | on with the row above | *gated by the same* `[auth].login_rate_limit_enabled` | | Consecutive credential failures on one account | the account's two failure counters (ADR 0197): the **sign-in** counter and the **second-step** counter | ≥ 5 consecutive failures on one counter locks for 15 minutes, with one exception: while the credential in force is engine-generated (set by an administrator's account creation, `POST /users`, and by both resets), sign-in failures are counted and audited but arm no sign-in lock (`lockout_arms`, ADR 0197 Amendment A); a lapsed window restarts the counter; the second-step lock on a local account, and the sign-in lock on a local account holding a discoverable passkey under the configured relying party (BACKLOG #3937), and the sign-in lock on a local account with a TOTP enrolled, unless the engine KNOWS this release refuses that enrolment (a TOTP it cannot judge still escalates, and a known-refused one escalates too in the races listed under [WebAuthn passkeys](#webauthn-passkeys-wp-14b-adr-0068), BACKLOG #3422), double per cycle up to 24 hours | **DENY** before any verify on the password and second-factor legs, plus an audit row whose name is leg-specific — on the password path the uniform `auth.login_failed` (`bad_credentials`) row every refused sign-in that reaches the engine writes and then `auth.login_locked`, which only `users:manage` reads ([Audit](#audit)), `auth.mfa_failed` / `auth.webauthn_failed` with `reason=locked` on at least the TOTP/recovery and assertion legs, and on a directory account's two enrolment legs (the sign-in password path still runs a dummy argon2 verify to keep timing flat). The second-step lock refuses every one of those legs. The sign-in lock has **two** exceptions: it does **not** refuse a combined sign-in, either the password and a TOTP code in one request on a local account with TOTP enrolled, or the password and a passkey assertion in one request on a local account holding a discoverable passkey under the request's relying party ([WebAuthn passkeys](#webauthn-passkeys-wp-14b-adr-0068), ADR 0197 Amendment A wave 2); and it refuses **no** second-factor leg. The Kerberos and OIDC sign-ins also refuse a row under either lock, but only **after** the ticket or token has verified, audited `auth.directory_login_locked` with `reason=locked` (`_directory_login_refusal`, BACKLOG #1638, its own action since #3726); neither leg feeds the counter. The password legs of the post-session re-proofs, `POST /me/reauth` and `POST /me/password` and their console twins `POST /ui/reauth` and `POST /ui/account/password`, **feed** the sign-in counter but are **not** refused by either lock; the IdP step-up of an `oidc` session checks no engine credential and feeds neither counter; each **session** may fail `lockout_threshold` re-proofs (5 by default), and the failure that reaches it revokes that session, audited as `auth.reauth` with `session_revoked=true` or `auth.password_change_failed` with `reason=session_revoked`. A password or code the console refuses at the JSON models' length bounds, at least at `POST /ui/reauth`, `POST /ui/mfa` and the TOTP enrolment confirm `POST /ui/account/mfa/verify`, reaches the service on no leg, so it is not audited and feeds neither counter nor the session's re-proof count, as the JSON route's 422 feeds none (BACKLOG #5398, #5399). Each of those routes measures its code with surrounding space stripped, by length only, and sends that stripped code, so a correct code padded with space still reaches the service | 5 / 15 min | `[auth].lockout_threshold`, `lockout_minutes`, `lockout_max_minutes` | -| New client IP during a session | this request's address vs `session.client` | knob on **and** a session exists, is unrevoked, has an anchor, and the two are not the same host (as [Administrative-interface defense-in-depth](#administrative-interface-defense-in-depth-wp-l3-13-asvs-842) defines it) | **CHALLENGE** — force a fresh step-up on a step-up route, a PHI read (`require_phi_read`, a monitoring `reveal`, the console's `phi=True` pages) or a paced write (`require_paced`, the console's writes), since vault BACKLOG #2620 for the last two; the base gate never asks, so the monitoring polls are not refused. A first sighting also writes `auth.new_address_reverify_required` + an out-of-band notice, debounced and capped per session as that section states; repeats WARNING-log only. **Never** an RBAC deny | **on**; `false` is a named loosening | `[auth].admin_new_ip_step_up` | +| New client IP during a session | this request's address vs `session.client` | knob on **and** a session exists, is unrevoked, has an anchor, and the two are not the same host (as [Administrative-interface defense-in-depth](#administrative-interface-defense-in-depth-wp-l3-13-asvs-842) defines it) | **CHALLENGE** — force a fresh step-up on a step-up route, a PHI read (`require_phi_read`, a monitoring `reveal`, the console's `phi=True` pages) or a paced write (`require_paced`, the console's writes), since vault BACKLOG #2620 for the last two; the base gate (`require`) and `require_monitoring_read` never ask, so the JSON monitoring polls are not refused. A first sighting also writes `auth.new_address_reverify_required` + an out-of-band notice, debounced and capped per session as that section states; repeats WARNING-log only. **Never** an RBAC deny | **on**; `false` is a named loosening | `[auth].admin_new_ip_step_up` | | First-seen sign-in address — sign-in owes no second factor (local leg) | the sign-in's client address vs the account's known-address record (the `known_login_addresses` table, vault BACKLOG #2145): one row per host from which the account finished a sign-in, passed a step-up, or confirmed a factor enrolment, keyed on the account id and deleted with the account. An administrator's password reset or MFA reset, or a `provision-admin` takeover, deletes every address in it (vault BACKLOG #2946, #3849). In the same transaction it writes one marker row stamped at the epoch. No lookback read returns that row, it still counts as a row of any age, and no prune deletes it. Revoking every session clears nothing. These events write a row: a local sign-in that owed no factor, from a known address or with no baseline yet; a directory sign-in that owes nothing more, whatever the verdict except a failed read, so a first-seen address and an account's first sign-in both write (no directory session is seeded, so there is no challenge to skip); a combined sign-in; a second factor proved (a TOTP or recovery code at the MFA gate, or a passkey assertion), whether it finishes a sign-in or is a step-up on a session that has already met its factor; a factor enrolment confirmed, TOTP or passkey, first or later, from a known address or by an account with no baseline yet (not from a first-seen address, because a holder of the password alone may enrol an authenticator, ADR 0197 Amendment A; this only delays such a holder until a code from that authenticator is proved, and the enrolment sends its own notice); and a step-up, by password or at the IdP, by an account that owes no second factor. That test is asked of the account, not of this session. Under `require_mfa` every directory account owes a factor, so no directory step-up by password or at the IdP writes, even one that re-proved the MFA claim. At the sign-in itself a failed record read writes nothing, on either leg. A combined sign-in is the exception, because it proved its second factor from that address. A factor proved afterwards still writes. Nothing is written for a request with no client address. A host compares as one key: an IPv4-mapped form is its IPv4 address, and every loopback form is one host. Only a row seen within the lookback (`_LOGIN_ADDRESS_LOOKBACK_SECONDS` in `auth/service.py`, 90 days) counts as a match, and each write prunes the account's older rows. The no-baseline test reads rows of any age, so an account whose only row came from an enrolment and has aged out is still judged, not failed open. Read through the record's primary key at session mint on the local, Kerberos and OIDC legs, after the first credential verified | no known address seen within the lookback is the same host **and** the account has a baseline: it has finished a sign-in before, or holds a row of any age. With neither, no client address, or a failed read, the signal fails open and writes `auth.login_address_unevaluated` with `reason` `no_baseline`, `unknown_address` or `read_failed` | **CHALLENGE** — `auth.login_new_ip` + an out-of-band `login_new_ip` notice (at most one per account and address per 15 minutes; the audit row is written every time), and the session is minted **without** step-up freshness (`seed_reauth=False`), except a combined sign-in (password and a TOTP code or a passkey assertion in one request, under the conditions of [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753); ADR 0197 and its Amendment A), which proved the second factor in the same request and is seeded as `verify_mfa` seeds it. **Never** refuses the login. The challenged sign-in does not make its address known, so a second sign-in from it is challenged again; a step-up from that address passes the challenge and records it (vault BACKLOG #2145) | on | (no knob) | | First-seen sign-in address — sign-in owes a second factor, or any directory sign-in | as the row above | as the row above | **LOG** — the same audit row and notice. A directory sign-in that owes nothing more also records the address, so the next one from it is not reported again; nothing else changes. **Under the shipped `require_mfa` a Kerberos sign-in always owes a factor**, and so does an OIDC one while `oidc_require_mfa_claim` is off. Such a sign-in records nothing; the factor leg that finishes it records the address instead: a TOTP or recovery code, a passkey, or a factor enrolment, under the conditions in the row above. So on this leg, as on the local one, every sign-in is unjudged (`no_baseline`) until one finishes, and a sign-in abandoned at the factor prompt records nothing. Under the same default no directory step-up records an address (see the row above). Such a session is born without step-up freshness anyway. A later proof stamps the window, for example a TOTP or recovery code, a user-verified passkey, or a step-up. On an OIDC session only the IdP step-up does (BACKLOG #2142). A Kerberos or password session steps up with the account password; an `oidc` session steps up at the IdP. Under the shipped `require_mfa` scope (`every_local_account`) this is the path every password-only local sign-in takes. A combined sign-in (password and a TOTP code or a passkey assertion in one request) owes nothing more, so it takes the row above instead and is seeded from any address. **Never** refuses the login (BACKLOG #288) | on | (no knob) | | Credential recency | age of `session.reauth_at` | `now − reauth_at > step_up_max_age_seconds`, or `reauth_at is None` | **DENY** 403 + `X-Step-Up-Required: 1` (console: 303 → `/ui/reauth`; an `oidc` session's JSON refusal names the IdP leg, see [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753)) | 300 s | `[auth].step_up_max_age_seconds` | @@ -7727,14 +7727,16 @@ it running); and the Flow and trends page's `/ui/monitoring/live` every 5 s call four times that is 576, and 600 is a round figure chosen above it. The tab count of five and the margin of four are judgments, not measurements. The count leaves out the Connections page's `/ws/stats` socket, which this pace never charges and whose per-frame work is described below. Against -the charged clients above, 600 per minute admits seven harness monitor windows (560) on one account, -but the monitor's dead-letter read stops the account at three windows on the PHI-read default. The +the charged clients above, 600 per minute admits seven harness monitor windows (560) on one account. +On the PHI-read default, three windows spend that whole budget with their dead-letter reads; past +that some dead-letter reads are refused, while each window's `/stats` and `/connections` reads keep +spending this budget. The global count ships off, as `phi_read_rate_limit_global` does. **What it does not charge.** The console calls these handlers in process, through `require_ui`, so the route's own dependency does not run and a console tab spends none of this budget; a console tab makes no HTTP request to the six routes. So a signed-in console session that loops -`/ui/monitoring/live`, `/ui/connections` or `/ui/nav-status` drives the same work with no 429. +`/ui/monitoring/live` or `/ui/connections` drives the same work with no 429. Other `monitoring:read` reads that cost work are not charged either. At least `GET /events`, `GET /connections/{name}/events` and `GET /config/provenance` stay on plain `require`, and the diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index e46ab10912..6c67f139f4 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1635,9 +1635,10 @@ async def refuse_from_new_address(request: Request) -> None: :meth:`AuthService.flag_new_client_ip` says. It is NOT in :func:`require` or :func:`require_monitoring_read`, deliberately: those gates carry - the JSON API's repeated monitoring reads, such as a ``/metrics`` scraper, and an operator whose address changes behind a NAT pool would be refused - on every one until a step-up. The web console's in-process reads go through ``require_ui`` and - reach neither gate. + the JSON API's repeated monitoring reads, and a JSON client whose address changes behind a NAT + pool, or behind a proxy not listed in ``[api].trusted_proxies``, would be refused on every one + until a step-up. The web console's in-process reads go through ``require_ui`` and reach neither + gate. A monitoring ``reveal`` read does ask, through ``_admit_reveal`` in ``api/app.py``. Costs one session read per request while ``[auth].admin_new_ip_step_up`` is on, and one more on a refusal, to pick its wording. The gate has @@ -1994,9 +1995,10 @@ def require_monitoring_read(*permissions: Permission) -> Callable[[Request], Awa the wiring graph, and ``/status``, ``/stats``, ``/metrics`` and ``/connections`` read aggregates whose cost grows with the store. ``/metrics/history`` copies an in-memory ring and reads no store; it was put in the set because the console's Flow and trends page reads it beside - ``/graph/edges``, so its pace bounds only JSON clients, because the console is not charged: it calls these handlers in process + ``/graph/edges``. The console is not charged, though: it calls these handlers in process through ``require_ui`` (``messagefoundry_webconsole/_auth.py``), so this dependency never runs - for it. The six share one budget per account, per API process. docs/SECURITY.md, + for it, and the pace on all six bounds JSON clients only. The six share one budget per + account, per API process. docs/SECURITY.md, *Monitoring-read pacing*, says the default's basis. Charged at ADMISSION, before the route does its work. A throttled read is logged (not silent), diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 437861345f..c75779e254 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -16820,7 +16820,9 @@ async def flag_new_client_ip( console's write gate), which refuse on ``True``. Not every caller refuses: the console's reauth-only action gate records the signal on a request it is refusing for another reason. The JSON plane's base gate (``require``) and its monitoring-read gate - (``require_monitoring_read``) never call it, so the JSON monitoring reads are not refused. The console's base gate (``require_ui``) calls it for a PHI read or a write, and, + (``require_monitoring_read``) never call it, so the JSON monitoring polls are not refused; + a monitoring ``reveal`` read is, through the HTTP reveal path above. The console's base + gate (``require_ui``) calls it for a PHI read or a write, and, since BACKLOG #5646, on every request a step-up gate serves, GET included, because the step-up factories hand it their question; the console's plain monitoring polls ride none of those, so they are not refused either. diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index ad55619f0d..16035dd82b 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -4031,7 +4031,7 @@ class AuthSettings(_Section): # Per-actor pacing on six monitoring:read GETs (vault BACKLOG #1191, ASVS 15.2.2): # /graph/edges, /status, /stats, /metrics, /metrics/history and /connections, charged at - # admission by require_monitoring_read. The default's measured basis and multiplier are written + # admission by require_monitoring_read. The default's basis and multiplier are written # once, in docs/SECURITY.md, "Monitoring-read pacing". In-process only, like the PHI-read # throttle. 0 disables that dimension. monitoring_read_rate_limit_enabled: bool = True From 8c3cf7ff8939ef1bce760f640134cff2e78badf4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:13:35 -0600 Subject: [PATCH 08/19] Monitoring-read pacing: an out-of-scope reveal is denied before the pace On origin/main, GET /connections?reveal= ran its channel-scope check, and wrote auth.channel_denied, before any 429. The pace moved a monitoring 429 ahead of that check, so an account with a spent budget could probe out-of-scope names with no channel-denial row. require_monitoring_read takes defer_when_query; /connections defers on reveal, and the route charges through charge_deferred_monitoring_read after _control_guard and before _admit_reveal. A deferred refusal still writes auth.gate_refused (throttled). A request without reveal, and the console's in-process call, are charged as before (the console not at all). Test, red on bfd5ee13e3d (429 where 403 was due): an out-of-scope reveal with the budget spent gets 403 and an auth.channel_denied row; an in-scope one gets 429 and a throttled row. The console test also pins /ui/nav-status as uncharged. The app.py comment and SECURITY.md say so. Vault BACKLOG #1191. --- docs/SECURITY.md | 4 ++- messagefoundry/api/app.py | 12 ++++--- messagefoundry/api/security.py | 47 ++++++++++++++++++++++++++-- tests/test_monitoring_read_pacing.py | 42 +++++++++++++++++++++++-- 4 files changed, 95 insertions(+), 10 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 611b43b69e..2619f8d709 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7692,7 +7692,9 @@ them cost work per call: `/graph/edges` rebuilds the wiring graph, and `/status` copies the in-memory metrics ring and reads no store; it was put in the set because the console's Flow and trends page reads it beside `/graph/edges`, but the console is not charged (below), so its pace bounds only JSON clients. The gate charges a per-actor sliding window at -admission, before the route's own work. The six routes share ONE budget per account: a read of any +admission, before the route's own work. One exception: on `GET /connections?reveal=`, the charge +waits until the route has run its channel-scope check, so a reveal naming a connection outside the +caller's scope is still denied and audited as `auth.channel_denied` when the budget is spent. The six routes share ONE budget per account: a read of any of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N (*Business-logic limits* above). diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index a6ded3f3ea..52c35a0e68 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -258,6 +258,7 @@ authorize_ws, authorizes_in_body, bearer_token, + charge_deferred_monitoring_read, client_ip, deadline_utc, enforce_phi_read_hop, @@ -5681,7 +5682,9 @@ async def list_channels( async def list_connections( request: Request, engine: Engine = Depends(_get_engine), - identity: Identity = Depends(require_monitoring_read(Permission.MONITORING_READ)), + identity: Identity = Depends( + require_monitoring_read(Permission.MONITORING_READ, defer_when_query="reveal") + ), # Annotated rather than ``= Query(None)``, for the reason get_message gives: the web console # calls this handler in-process, and a call that leaves it out must get None. reveal: Annotated[ConnectionName | None, Query()] = None, @@ -5699,11 +5702,12 @@ async def list_connections( # Per-channel RBAC, as on GET /connections/{name}/events: a reveal naming a connection # outside the caller's scope is refused and audited as a channel denial. Checked BEFORE the # reveal is admitted, so a refused name spends no PHI-read budget and cannot be hidden - # behind the PHI-read 429. It can still be hidden behind the monitoring-read 429: that pace - # (require_monitoring_read) is charged in this route's dependency, before this check runs. - # A scoped caller's dashboard carries no outbound rows at all. + # behind a 429. The gate defers its monitoring-read charge on a reveal for that reason, and + # it is charged here, after this check (vault BACKLOG #1191). A scoped caller's dashboard + # carries no outbound rows at all. if reveal is not None: await _control_guard(engine, identity, reveal, client_ip(request)) + await charge_deferred_monitoring_read(request) await _admit_reveal(request, identity, reveal) out = await _dashboard_rows(engine, identity, reveal=reveal) if reveal is not None: diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 6c67f139f4..19ece0bc75 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1989,7 +1989,9 @@ async def dependency(request: Request) -> Identity: return _gate(dependency, before_body) -def require_monitoring_read(*permissions: Permission) -> Callable[[Request], Awaitable[Identity]]: +def require_monitoring_read( + *permissions: Permission, defer_when_query: str | None = None +) -> Callable[[Request], Awaitable[Identity]]: """Like :func:`require`, plus a **per-actor pace** on six ``monitoring:read`` GETs (vault BACKLOG #1191, ASVS 15.2.2). Five of them cost store or parse work per call: ``/graph/edges`` rebuilds the wiring graph, and ``/status``, ``/stats``, ``/metrics`` and ``/connections`` read aggregates @@ -2006,18 +2008,57 @@ def require_monitoring_read(*permissions: Permission) -> Callable[[Request], Awa recorded as an ``auth.gate_refused`` row with reason ``throttled`` wherever :func:`_audited_permission` names one (on by default). It does not ask the new-address question: :func:`refuse_from_new_address` says why these reads stay outside it. No pace on the - embedding/no-auth path (there is no per-actor identity to key on).""" + embedding/no-auth path (there is no per-actor identity to key on). + + ``defer_when_query`` names a query parameter that moves the charge into the route body: when + the request carries it, the gate admits without charging and the route calls + :func:`charge_deferred_monitoring_read` itself, after its own checks. ``GET /connections`` + defers on ``reveal``, so a reveal naming a connection outside the caller's scope is denied and + audited as a channel denial before the pace can answer 429 (vault BACKLOG #1191).""" async def dependency(request: Request) -> Identity: auth, identity = await _admit(request, permissions, mfa_gate=True) if auth is not None: + deferred = defer_when_query is not None and defer_when_query in request.query_params async with _recorded_decision(request, auth, identity, permissions): - enforce_monitoring_read_pacing(request, auth, identity) + if deferred: + setattr( + request.state, + _DEFERRED_MONITORING_READ_ATTR, + _AdmittedDecision(auth, identity, permissions), + ) + else: + enforce_monitoring_read_pacing(request, auth, identity) return identity return _gate(dependency, _authenticate_session_before_body) +#: The ``request.state`` attribute :func:`require_monitoring_read` leaves its decision on when it +#: defers the charge to the route body. +_DEFERRED_MONITORING_READ_ATTR = "mefor_deferred_monitoring_read" + + +async def charge_deferred_monitoring_read(request: Request) -> None: + """Charge the monitoring-read pace a :func:`require_monitoring_read` gate deferred to the route + body, raising its 429 when the budget is spent. The refusal writes ``auth.gate_refused`` with + reason ``throttled`` through the writer the gate's own refusals use, after the gate's grant row. + A no-op where no gate deferred on this request: the no-auth path, a request without the + deferring parameter (the gate charged it already), and the web console's in-process call, + whose own request carries no deferred decision.""" + admitted = getattr(request.state, _DEFERRED_MONITORING_READ_ATTR, None) + if not isinstance(admitted, _AdmittedDecision): + return + delattr(request.state, _DEFERRED_MONITORING_READ_ATTR) + try: + enforce_monitoring_read_pacing(request, admitted.auth, admitted.identity) + except _GateRefusal as refusal: + await _record_gate_refusal( + request, admitted.auth, admitted.identity, admitted.permissions, refusal + ) + raise + + def enforce_monitoring_read_pacing(request: Request, auth: AuthService, identity: Identity) -> None: """Charge the per-actor monitoring-read budget (vault BACKLOG #1191), raising 429 when it is spent. Logged, not silent. Its Retry-After is the actor's own wait, in whole seconds, or the diff --git a/tests/test_monitoring_read_pacing.py b/tests/test_monitoring_read_pacing.py index 6f50ff4a94..7c90f79cae 100644 --- a/tests/test_monitoring_read_pacing.py +++ b/tests/test_monitoring_read_pacing.py @@ -200,6 +200,42 @@ async def test_retry_after_is_the_whole_window_while_the_global_count_is_spent( assert (refused.status_code, refused.headers["Retry-After"]) == (429, "38") +async def test_an_out_of_scope_reveal_is_denied_and_audited_with_the_budget_spent( + engine: Engine, +) -> None: + """As on main, the scope check and its ``auth.channel_denied`` row come before the monitoring + pace: an account whose budget is spent still gets the channel denial for an out-of-scope + reveal, not a 429 that hides the probe.""" + service = await _service(engine, monitoring_read_rate_limit_per_actor=1) + scoped = await service.store.get_user_by_username("vw") + assert scoped is not None + await service.set_channel_scope(scoped.id, ["IB_MINE"], actor="test") + async with _client(engine, service) as c: + h = await _bearer(c, "vw") + assert (await c.get("/status", headers=h)).status_code == 200 + assert (await c.get("/status", headers=h)).status_code == 429 # the budget is spent + denied = await c.get("/connections", params={"reveal": "IB_THEIRS"}, headers=h) + assert denied.status_code == 403, denied.text + # An in-scope reveal past the budget is still paced. + paced = await c.get("/connections", params={"reveal": "IB_MINE"}, headers=h) + assert paced.status_code == 429 + assert int(paced.headers["Retry-After"]) >= 1 + rows = await engine.store.list_audit(limit=1000) + denials = [ + json.loads(str(row["detail"] or "{}")) + for row in rows + if row["action"] == "auth.channel_denied" + ] + assert any("IB_THEIRS" in json.dumps(d) for d in denials), denials + # The in-scope reveal's 429, charged in the route body, still writes its throttled row. + refused = [ + json.loads(str(row["detail"] or "{}")) + for row in rows + if row["action"] == "auth.gate_refused" + ] + assert any(d.get("path") == "/connections" and d.get("reason") == "throttled" for d in refused) + + async def test_the_web_console_reads_are_not_charged(engine: Engine) -> None: """The console calls the paced handlers in process through ``require_ui``, so the route's own dependency never runs and the account's budget is untouched (docs/SECURITY.md, *Monitoring-read @@ -215,8 +251,10 @@ async def test_the_web_console_reads_are_not_charged(engine: Engine) -> None: assert r.status_code == 303 and c.cookies.get("mf_session"), r.status_code # Signed out, these pages answer 303; a 200 here means the signed-in handler ran. Each # calls a paced handler (``/ui/connections`` the ``GET /connections`` one, - # ``/ui/monitoring/live`` the ``GET /graph/edges`` and ``/metrics/history`` ones). - for path in ("/ui/connections", "/ui/monitoring/live"): + # ``/ui/monitoring/live`` the ``GET /graph/edges`` and ``/metrics/history`` ones, + # ``/ui/nav-status`` the ``GET /status`` one, though it answers 200 even if that call + # fails). The bearer reads below are what prove none of them spent the budget. + for path in ("/ui/connections", "/ui/monitoring/live", "/ui/nav-status"): for _ in range(3): assert (await c.get(path)).status_code == 200, path # The same account's budget of 1 is still whole: one bearer read is admitted, the next From 3983f5588b9ceb4dfdf203d179015cd4661cd8b2 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:41:51 -0600 Subject: [PATCH 09/19] Monitoring-read pacing: hold the reveal's 429, not its charge Review round-76fca5fc37 found that deferring the charge on /connections?reveal= left an out-of-scope or invalid reveal unpaced and wrote a grant row before a later refusal (the BACKLOG #1197 shape). The gate now charges every request at admission. On a reveal it holds a 429 on the request instead of raising it, writes no grant row for it, and /connections raises it through raise_deferred_monitoring_refusal after _control_guard, writing auth.gate_refused then. An out-of-scope reveal is still denied and audited as auth.channel_denied first, as on main, and spends a read; a 422 reveal spends one too. Tests: an out-of-scope reveal with the budget spent gets 403 and the channel-denial row; the in-scope one gets 429 with one gate_refused row and no grant row; a denied and an invalid reveal each spend the budget; an in-scope reveal under the budget is charged once. The _recorded_decision docstring and SECURITY.md say where this refusal's row is written. Vault BACKLOG #1191. --- docs/SECURITY.md | 15 +-- messagefoundry/api/app.py | 10 +- messagefoundry/api/security.py | 135 ++++++++++++++++----------- tests/test_monitoring_read_pacing.py | 72 +++++++++++--- 4 files changed, 153 insertions(+), 79 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 2619f8d709..3769b6ac35 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5345,8 +5345,11 @@ flowchart TB row writes no refusal row either. A refused second factor writes `auth.mfa_denied`, as the base gate's does. For the step-up refusals of `spend_step_up_action` and `refuse_unless_step_up_window_live`, which a route body makes after its gate has passed, - `_record_route_refusal` in `messagefoundry/api/security.py` says what it records. Other refusals - a route body makes after its gate has passed write no `auth.gate_refused` row. + `_record_route_refusal` in `messagefoundry/api/security.py` says what it records. The + monitoring-read 429 that `require_monitoring_read` holds on a `GET /connections` reveal is raised + by the route body after its scope check; its gate wrote no grant row, and + `raise_deferred_monitoring_refusal` writes the `auth.gate_refused` row the gate would have. Other + refusals a route body makes after its gate has passed write no `auth.gate_refused` row. - Routes that act on a Connection also check the identity's connection scope. That scope starts empty for every role except Administrator. - Sensitive routes add a step-up re-check on top of this flow. See @@ -7692,10 +7695,10 @@ them cost work per call: `/graph/edges` rebuilds the wiring graph, and `/status` copies the in-memory metrics ring and reads no store; it was put in the set because the console's Flow and trends page reads it beside `/graph/edges`, but the console is not charged (below), so its pace bounds only JSON clients. The gate charges a per-actor sliding window at -admission, before the route's own work. One exception: on `GET /connections?reveal=`, the charge -waits until the route has run its channel-scope check, so a reveal naming a connection outside the -caller's scope is still denied and audited as `auth.channel_denied` when the budget is spent. The six routes share ONE budget per account: a read of any -of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N +admission, before the route's own work. On `GET /connections?reveal=` the read is still charged +at admission, but a 429 is held until the route has run its channel-scope check, so a reveal naming +a connection outside the caller's scope is still denied and audited as `auth.channel_denied` when +the budget is spent. The six routes share ONE budget per account: a read of any of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N (*Business-logic limits* above). **Key.** `identity.user_id` of the bearer session the request presents. A Prometheus-style scraper diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 52c35a0e68..12eb94ce1a 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -258,7 +258,6 @@ authorize_ws, authorizes_in_body, bearer_token, - charge_deferred_monitoring_read, client_ip, deadline_utc, enforce_phi_read_hop, @@ -269,6 +268,7 @@ pending_credential_deadline, public_route, quiet_deliberate_export_stops, + raise_deferred_monitoring_refusal, recheck_standing, recheck_standing_or_refusal, refuse_from_new_address, @@ -5702,12 +5702,12 @@ async def list_connections( # Per-channel RBAC, as on GET /connections/{name}/events: a reveal naming a connection # outside the caller's scope is refused and audited as a channel denial. Checked BEFORE the # reveal is admitted, so a refused name spends no PHI-read budget and cannot be hidden - # behind a 429. The gate defers its monitoring-read charge on a reveal for that reason, and - # it is charged here, after this check (vault BACKLOG #1191). A scoped caller's dashboard - # carries no outbound rows at all. + # behind a 429. For that reason the gate holds its monitoring-read 429 on a reveal, and it + # is raised here, after this check; the read was charged at admission either way (vault + # BACKLOG #1191). A scoped caller's dashboard carries no outbound rows at all. if reveal is not None: await _control_guard(engine, identity, reveal, client_ip(request)) - await charge_deferred_monitoring_read(request) + await raise_deferred_monitoring_refusal(request) await _admit_reveal(request, identity, reveal) out = await _dashboard_rows(engine, identity, reveal=reveal) if reveal is not None: diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 19ece0bc75..61f729dade 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1484,8 +1484,10 @@ async def _recorded_decision( The audit chain has no drain (BACKLOG #1421); a refused route-body request writes at most two decision rows. For the step-up refusals of :func:`spend_step_up_action` and :func:`refuse_unless_step_up_window_live`, made in a route body after its gate admitted the - request, see :func:`_record_route_refusal`. Other refusals a route body makes after its gate - admitted the request write no ``auth.gate_refused`` row. The reason comes from the + request, see :func:`_record_route_refusal`. For the monitoring-read 429 a gate holds for its + route body, with no grant row written, see :func:`raise_deferred_monitoring_refusal`. Other + refusals a route body makes after its gate admitted the request write no ``auth.gate_refused`` + row. The reason comes from the :class:`_GateRefusal` the check raised. Any other exception leaves the block with no decision row from it, which is right for the :func:`_mfa_refusal` 403: it wrote its own ``auth.mfa_denied`` row where it was raised. A failed refusal-row write raises in place of the @@ -1519,7 +1521,8 @@ async def _record_gate_refusal( @dataclass(frozen=True) class _AdmittedDecision: - """What a ``proof_in_route`` gate admitted, kept for the refusal row its route body may owe.""" + """What a ``proof_in_route`` gate admitted, kept for the refusal row its route body may owe. + :func:`require_monitoring_read` keeps one beside a 429 it holds for its route body.""" auth: AuthService identity: Identity @@ -2010,71 +2013,95 @@ def require_monitoring_read( question: :func:`refuse_from_new_address` says why these reads stay outside it. No pace on the embedding/no-auth path (there is no per-actor identity to key on). - ``defer_when_query`` names a query parameter that moves the charge into the route body: when - the request carries it, the gate admits without charging and the route calls - :func:`charge_deferred_monitoring_read` itself, after its own checks. ``GET /connections`` - defers on ``reveal``, so a reveal naming a connection outside the caller's scope is denied and - audited as a channel denial before the pace can answer 429 (vault BACKLOG #1191).""" + ``defer_when_query`` names a query parameter that delays the REFUSAL, not the charge: when the + request carries it, the gate still charges the budget at admission, but a 429 it would answer + is held on the request, with no decision row yet, until the route body calls + :func:`raise_deferred_monitoring_refusal` after its own scope check. ``GET /connections`` + defers on ``reveal`` (vault BACKLOG #1191); docs/SECURITY.md, *Monitoring-read pacing*, says + why.""" async def dependency(request: Request) -> Identity: auth, identity = await _admit(request, permissions, mfa_gate=True) - if auth is not None: - deferred = defer_when_query is not None and defer_when_query in request.query_params - async with _recorded_decision(request, auth, identity, permissions): - if deferred: - setattr( - request.state, - _DEFERRED_MONITORING_READ_ATTR, - _AdmittedDecision(auth, identity, permissions), - ) - else: - enforce_monitoring_read_pacing(request, auth, identity) + if auth is None: + return identity + if defer_when_query is not None and defer_when_query in request.query_params: + refusal = _monitoring_read_refusal(request, auth, identity) + if refusal is None: + await _record_grant(request, auth, identity, permissions) + else: + setattr( + request.state, + _DEFERRED_MONITORING_REFUSAL_ATTR, + _DeferredRefusal(_AdmittedDecision(auth, identity, permissions), refusal), + ) + return identity + async with _recorded_decision(request, auth, identity, permissions): + enforce_monitoring_read_pacing(request, auth, identity) return identity return _gate(dependency, _authenticate_session_before_body) -#: The ``request.state`` attribute :func:`require_monitoring_read` leaves its decision on when it -#: defers the charge to the route body. -_DEFERRED_MONITORING_READ_ATTR = "mefor_deferred_monitoring_read" +@dataclass(frozen=True) +class _DeferredRefusal: + """A refusal a gate decided at admission and left for its route body to raise.""" + + decision: _AdmittedDecision + refusal: _GateRefusal -async def charge_deferred_monitoring_read(request: Request) -> None: - """Charge the monitoring-read pace a :func:`require_monitoring_read` gate deferred to the route - body, raising its 429 when the budget is spent. The refusal writes ``auth.gate_refused`` with - reason ``throttled`` through the writer the gate's own refusals use, after the gate's grant row. - A no-op where no gate deferred on this request: the no-auth path, a request without the - deferring parameter (the gate charged it already), and the web console's in-process call, - whose own request carries no deferred decision.""" - admitted = getattr(request.state, _DEFERRED_MONITORING_READ_ATTR, None) - if not isinstance(admitted, _AdmittedDecision): +#: The ``request.state`` attribute :func:`require_monitoring_read` leaves a held refusal on. +_DEFERRED_MONITORING_REFUSAL_ATTR = "mefor_deferred_monitoring_refusal" + + +async def raise_deferred_monitoring_refusal(request: Request) -> None: + """Raise the monitoring-read 429 a :func:`require_monitoring_read` gate held for this request, + writing its ``auth.gate_refused`` row (reason ``throttled``) where :func:`_audited_permission` + names one, as the gate itself would have. The gate wrote no grant row for such a request. + + A no-op where nothing is held: the budget had room (the gate wrote its grant row), the no-auth + path, a request without the deferring parameter, and the web console's in-process call, whose + own request carries nothing held. A route that defers must call this on every path that does + the paced work; ``tests/test_monitoring_read_pacing.py`` pins the one route that does.""" + held = getattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR, None) + if not isinstance(held, _DeferredRefusal): return - delattr(request.state, _DEFERRED_MONITORING_READ_ATTR) - try: - enforce_monitoring_read_pacing(request, admitted.auth, admitted.identity) - except _GateRefusal as refusal: - await _record_gate_refusal( - request, admitted.auth, admitted.identity, admitted.permissions, refusal - ) - raise + delattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR) + decision = held.decision + await _record_gate_refusal( + request, decision.auth, decision.identity, decision.permissions, held.refusal + ) + raise held.refusal + + +def _monitoring_read_refusal( + request: Request, auth: AuthService, identity: Identity +) -> _GateRefusal | None: + """Charge the per-actor monitoring-read budget (vault BACKLOG #1191) and return the 429 to + answer when it is spent, or None. Logged, not silent. Its Retry-After is the actor's own wait, + in whole seconds, or the whole window while the all-accounts count is spent + (:meth:`AuthService.monitoring_read_retry_after`).""" + if auth.allow_monitoring_read(identity.user_id): + return None + log.warning( + "monitoring-read throttled (anti-automation): actor=%s path=%s", + identity.username, + request.url.path, + ) + return _GateRefusal( + status.HTTP_429_TOO_MANY_REQUESTS, + "too many requests; please slow down", + reason="throttled", + headers={"Retry-After": str(auth.monitoring_read_retry_after(identity.user_id))}, + ) def enforce_monitoring_read_pacing(request: Request, auth: AuthService, identity: Identity) -> None: - """Charge the per-actor monitoring-read budget (vault BACKLOG #1191), raising 429 when it is - spent. Logged, not silent. Its Retry-After is the actor's own wait, in whole seconds, or the - whole window while the all-accounts count is spent (:meth:`AuthService.monitoring_read_retry_after`).""" - if not auth.allow_monitoring_read(identity.user_id): - log.warning( - "monitoring-read throttled (anti-automation): actor=%s path=%s", - identity.username, - request.url.path, - ) - raise _GateRefusal( - status.HTTP_429_TOO_MANY_REQUESTS, - "too many requests; please slow down", - reason="throttled", - headers={"Retry-After": str(auth.monitoring_read_retry_after(identity.user_id))}, - ) + """Charge the per-actor monitoring-read budget, raising the 429 of + :func:`_monitoring_read_refusal` when it is spent.""" + refusal = _monitoring_read_refusal(request, auth, identity) + if refusal is not None: + raise refusal def enforce_phi_read_pacing(request: Request, identity: Identity) -> None: diff --git a/tests/test_monitoring_read_pacing.py b/tests/test_monitoring_read_pacing.py index 7c90f79cae..04a900b552 100644 --- a/tests/test_monitoring_read_pacing.py +++ b/tests/test_monitoring_read_pacing.py @@ -10,7 +10,7 @@ from __future__ import annotations import json -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Sequence from pathlib import Path from types import SimpleNamespace @@ -23,6 +23,7 @@ from messagefoundry.auth.service import AuthService from messagefoundry.config.settings import AuthSettings, EgressSettings from messagefoundry.pipeline import Engine +from messagefoundry.store.base import Row from tests._admin_account import create_local_user_chosen PW = "a-strong-test-passphrase" @@ -200,23 +201,39 @@ async def test_retry_after_is_the_whole_window_while_the_global_count_is_spent( assert (refused.status_code, refused.headers["Retry-After"]) == (429, "38") +def _decisions_on(rows: Sequence[Row], path: str) -> list[tuple[str, dict[str, object]]]: + """The gate decision rows on ``path``, oldest first.""" + ordered = sorted(rows, key=lambda row: int(str(row["id"]))) + return [ + (str(row["action"]), json.loads(str(row["detail"] or "{}"))) + for row in ordered + if row["action"] in {"auth.permission_granted", "auth.gate_refused"} + and json.loads(str(row["detail"] or "{}")).get("path") == path + ] + + +async def _scoped_service(engine: Engine, **overrides: object) -> AuthService: + service = await _service(engine, **overrides) + scoped = await service.store.get_user_by_username("vw") + assert scoped is not None + await service.set_channel_scope(scoped.id, ["IB_MINE"], actor="test") + return service + + async def test_an_out_of_scope_reveal_is_denied_and_audited_with_the_budget_spent( engine: Engine, ) -> None: """As on main, the scope check and its ``auth.channel_denied`` row come before the monitoring pace: an account whose budget is spent still gets the channel denial for an out-of-scope - reveal, not a 429 that hides the probe.""" - service = await _service(engine, monitoring_read_rate_limit_per_actor=1) - scoped = await service.store.get_user_by_username("vw") - assert scoped is not None - await service.set_channel_scope(scoped.id, ["IB_MINE"], actor="test") + reveal, not a 429 that hides the probe. An in-scope reveal past the budget is still refused, + with one ``auth.gate_refused`` row and no grant row (BACKLOG #1197).""" + service = await _scoped_service(engine, monitoring_read_rate_limit_per_actor=1) async with _client(engine, service) as c: h = await _bearer(c, "vw") assert (await c.get("/status", headers=h)).status_code == 200 assert (await c.get("/status", headers=h)).status_code == 429 # the budget is spent denied = await c.get("/connections", params={"reveal": "IB_THEIRS"}, headers=h) assert denied.status_code == 403, denied.text - # An in-scope reveal past the budget is still paced. paced = await c.get("/connections", params={"reveal": "IB_MINE"}, headers=h) assert paced.status_code == 429 assert int(paced.headers["Retry-After"]) >= 1 @@ -227,13 +244,40 @@ async def test_an_out_of_scope_reveal_is_denied_and_audited_with_the_budget_spen if row["action"] == "auth.channel_denied" ] assert any("IB_THEIRS" in json.dumps(d) for d in denials), denials - # The in-scope reveal's 429, charged in the route body, still writes its throttled row. - refused = [ - json.loads(str(row["detail"] or "{}")) - for row in rows - if row["action"] == "auth.gate_refused" - ] - assert any(d.get("path") == "/connections" and d.get("reason") == "throttled" for d in refused) + on_path = _decisions_on(rows, "/connections") + # Only the in-scope reveal's refusal is written: the out-of-scope one was answered, and + # recorded, as a channel denial, and its held 429 was never raised. + assert [a for a, _ in on_path] == ["auth.gate_refused"], on_path + assert {d["reason"] for _, d in on_path} == {"throttled"} + + +async def test_a_refused_reveal_still_spends_the_budget(engine: Engine) -> None: + """The reveal's charge is taken at admission: a reveal the scope check denies, and one whose + value fails validation, each spend a read, so neither is an unpaced probe.""" + service = await _scoped_service(engine, monitoring_read_rate_limit_per_actor=1) + async with _client(engine, service) as c: + h = await _bearer(c, "vw") + denied = await c.get("/connections", params={"reveal": "IB_THEIRS"}, headers=h) + assert denied.status_code == 403 + assert (await c.get("/status", headers=h)).status_code == 429 + h_other = await _bearer(c, "other") + invalid = await c.get("/connections", params={"reveal": ""}, headers=h_other) + assert invalid.status_code == 422 + assert (await c.get("/status", headers=h_other)).status_code == 429 + + +async def test_an_in_scope_reveal_under_the_budget_is_charged_once(engine: Engine) -> None: + service = await _scoped_service(engine, monitoring_read_rate_limit_per_actor=2) + async with _client(engine, service) as c: + h = await _bearer(c, "vw") + # A Viewer passes the scope check and the pace, and is then refused by the reveal's own + # permission check, which runs after both. + passed = await c.get("/connections", params={"reveal": "IB_MINE"}, headers=h) + assert passed.status_code == 403 + assert passed.json()["detail"] == "a reveal needs messages:view_summary" + # One read of the budget of 2 is left. + assert (await c.get("/status", headers=h)).status_code == 200 + assert (await c.get("/status", headers=h)).status_code == 429 async def test_the_web_console_reads_are_not_charged(engine: Engine) -> None: From d50304f32f1ef07396374ee7a3d075ed12ac6332 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 12:04:16 -0600 Subject: [PATCH 10/19] Monitoring-read pacing: log a held 429 only when it is raised From code review round-37cfb9930b: - the throttled WARNING moved from the charge to the raise, so a reveal the scope check (403) or query validation (422) answers first is no longer logged as throttled; the charge is renamed _charge_monitoring_read; - the require_monitoring_read docstring and SECURITY.md say such a held 429 writes no throttled row or line; the Retry-After pointer names the function that states it; - raise_deferred_monitoring_refusal's no-op list says "at least", drops the grant-row claim, and no longer says a test pins the deferring routes; - the nav-status test comment is corrected; a test pins the over-budget invalid reveal (422, no throttled row). Vault BACKLOG #1191. --- docs/SECURITY.md | 4 +- messagefoundry/api/security.py | 56 ++++++++++++++++------------ tests/test_monitoring_read_pacing.py | 11 +++++- 3 files changed, 44 insertions(+), 27 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 3769b6ac35..293655a6b4 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7698,7 +7698,9 @@ its pace bounds only JSON clients. The gate charges a per-actor sliding window a admission, before the route's own work. On `GET /connections?reveal=` the read is still charged at admission, but a 429 is held until the route has run its channel-scope check, so a reveal naming a connection outside the caller's scope is still denied and audited as `auth.channel_denied` when -the budget is spent. The six routes share ONE budget per account: a read of any of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N +the budget is spent. A held 429 the route never raises, because the scope check or query +validation refused first, is answered by that refusal and writes no throttled row or log line. The +six routes share ONE budget per account: a read of any of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N (*Business-logic limits* above). **Key.** `identity.user_id` of the bearer session the request presents. A Prometheus-style scraper diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 61f729dade..290f5a21b2 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -2007,7 +2007,7 @@ def require_monitoring_read( *Monitoring-read pacing*, says the default's basis. Charged at ADMISSION, before the route does its work. A throttled read is logged (not silent), - answered 429 with a ``Retry-After`` (:func:`enforce_monitoring_read_pacing` says its value), and + answered 429 with a ``Retry-After`` (:func:`_charge_monitoring_read` says its value), and recorded as an ``auth.gate_refused`` row with reason ``throttled`` wherever :func:`_audited_permission` names one (on by default). It does not ask the new-address question: :func:`refuse_from_new_address` says why these reads stay outside it. No pace on the @@ -2016,16 +2016,17 @@ def require_monitoring_read( ``defer_when_query`` names a query parameter that delays the REFUSAL, not the charge: when the request carries it, the gate still charges the budget at admission, but a 429 it would answer is held on the request, with no decision row yet, until the route body calls - :func:`raise_deferred_monitoring_refusal` after its own scope check. ``GET /connections`` - defers on ``reveal`` (vault BACKLOG #1191); docs/SECURITY.md, *Monitoring-read pacing*, says - why.""" + :func:`raise_deferred_monitoring_refusal` after its own scope check. A held 429 the route + never raises, because the scope check or query validation refused the request first, is + answered by that refusal and writes no throttled row or line. ``GET /connections`` defers on + ``reveal`` (vault BACKLOG #1191); docs/SECURITY.md, *Monitoring-read pacing*, says why.""" async def dependency(request: Request) -> Identity: auth, identity = await _admit(request, permissions, mfa_gate=True) if auth is None: return identity if defer_when_query is not None and defer_when_query in request.query_params: - refusal = _monitoring_read_refusal(request, auth, identity) + refusal = _charge_monitoring_read(request, auth, identity) if refusal is None: await _record_grant(request, auth, identity, permissions) else: @@ -2056,38 +2057,35 @@ class _DeferredRefusal: async def raise_deferred_monitoring_refusal(request: Request) -> None: """Raise the monitoring-read 429 a :func:`require_monitoring_read` gate held for this request, - writing its ``auth.gate_refused`` row (reason ``throttled``) where :func:`_audited_permission` - names one, as the gate itself would have. The gate wrote no grant row for such a request. - - A no-op where nothing is held: the budget had room (the gate wrote its grant row), the no-auth - path, a request without the deferring parameter, and the web console's in-process call, whose - own request carries nothing held. A route that defers must call this on every path that does - the paced work; ``tests/test_monitoring_read_pacing.py`` pins the one route that does.""" + logging it and writing its ``auth.gate_refused`` row (reason ``throttled``) where + :func:`_audited_permission` names one, as the gate itself would have. The gate wrote no grant + row for such a request. + + A no-op where nothing is held, at least: the budget had room, the no-auth path, a request + without the deferring parameter, and the web console's in-process call, whose own request + carries nothing held. A route that defers must call this on every path that does the paced + work; nothing checks that it does, so a missed call serves a throttled caller.""" held = getattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR, None) if not isinstance(held, _DeferredRefusal): return delattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR) decision = held.decision + _log_monitoring_throttle(request, decision.identity) await _record_gate_refusal( request, decision.auth, decision.identity, decision.permissions, held.refusal ) raise held.refusal -def _monitoring_read_refusal( +def _charge_monitoring_read( request: Request, auth: AuthService, identity: Identity ) -> _GateRefusal | None: """Charge the per-actor monitoring-read budget (vault BACKLOG #1191) and return the 429 to - answer when it is spent, or None. Logged, not silent. Its Retry-After is the actor's own wait, - in whole seconds, or the whole window while the all-accounts count is spent - (:meth:`AuthService.monitoring_read_retry_after`).""" + answer when it is spent, or None. Its caller logs the refusal when it raises it. Its + Retry-After is the actor's own wait, in whole seconds, or the whole window while the + all-accounts count is spent (:meth:`AuthService.monitoring_read_retry_after`).""" if auth.allow_monitoring_read(identity.user_id): return None - log.warning( - "monitoring-read throttled (anti-automation): actor=%s path=%s", - identity.username, - request.url.path, - ) return _GateRefusal( status.HTTP_429_TOO_MANY_REQUESTS, "too many requests; please slow down", @@ -2096,11 +2094,21 @@ def _monitoring_read_refusal( ) +def _log_monitoring_throttle(request: Request, identity: Identity) -> None: + """The WARNING line a raised monitoring-read 429 writes (logged, not silent).""" + log.warning( + "monitoring-read throttled (anti-automation): actor=%s path=%s", + identity.username, + request.url.path, + ) + + def enforce_monitoring_read_pacing(request: Request, auth: AuthService, identity: Identity) -> None: - """Charge the per-actor monitoring-read budget, raising the 429 of - :func:`_monitoring_read_refusal` when it is spent.""" - refusal = _monitoring_read_refusal(request, auth, identity) + """Charge the per-actor monitoring-read budget, logging and raising the 429 of + :func:`_charge_monitoring_read` when it is spent.""" + refusal = _charge_monitoring_read(request, auth, identity) if refusal is not None: + _log_monitoring_throttle(request, identity) raise refusal diff --git a/tests/test_monitoring_read_pacing.py b/tests/test_monitoring_read_pacing.py index 04a900b552..ebbdf1b654 100644 --- a/tests/test_monitoring_read_pacing.py +++ b/tests/test_monitoring_read_pacing.py @@ -264,6 +264,12 @@ async def test_a_refused_reveal_still_spends_the_budget(engine: Engine) -> None: invalid = await c.get("/connections", params={"reveal": ""}, headers=h_other) assert invalid.status_code == 422 assert (await c.get("/status", headers=h_other)).status_code == 429 + # Over the budget, an invalid reveal is still answered by its validation 422: the held 429 + # is never raised, so it writes no throttled row on the path. + again = await c.get("/connections", params={"reveal": ""}, headers=h_other) + assert again.status_code == 422 + rows = await engine.store.list_audit(limit=1000) + assert [a for a, _ in _decisions_on(rows, "/connections") if a == "auth.gate_refused"] == [] async def test_an_in_scope_reveal_under_the_budget_is_charged_once(engine: Engine) -> None: @@ -296,8 +302,9 @@ async def test_the_web_console_reads_are_not_charged(engine: Engine) -> None: # Signed out, these pages answer 303; a 200 here means the signed-in handler ran. Each # calls a paced handler (``/ui/connections`` the ``GET /connections`` one, # ``/ui/monitoring/live`` the ``GET /graph/edges`` and ``/metrics/history`` ones, - # ``/ui/nav-status`` the ``GET /status`` one, though it answers 200 even if that call - # fails). The bearer reads below are what prove none of them spent the budget. + # ``/ui/nav-status`` the ``GET /status`` one; it swallows that call's other failures but + # re-raises an HTTPException, so a charged 429 would show here). The bearer reads below + # prove none of them spent the budget. for path in ("/ui/connections", "/ui/monitoring/live", "/ui/nav-status"): for _ in range(3): assert (await c.get(path)).status_code == 200, path From 5a0ad1907c718623e4b78d83011c75e1c0306fa9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 12:41:32 -0600 Subject: [PATCH 11/19] Monitoring-read pacing: a reveal's permission denial and an invalid reveal keep main's rows From code review round-a8c1ee45d9, two regressions against main: - the held 429 was raised before the reveal's messages:view_summary check, so a Viewer over budget got 429 instead of main's 403 and auth.permission_denied row. list_connections now runs that check (_refuse_reveal_without_view_summary, split out of _admit_reveal) before raise_deferred_monitoring_refusal; - an over-budget reveal that fails validation (422) wrote no decision row. require_monitoring_read takes defer_value_valid, and /connections defers only a valid ConnectionName, so an invalid one is refused 429 at the gate with its auth.gate_refused row. Tests, both red on d50304f32f1 (429 for 403; 422 for 429). The "spends a read" and "as on main" test text, the SECURITY.md pacing text and the test_derived_gate_decision_audit docstring are corrected. Vault BACKLOG #1191. --- docs/SECURITY.md | 17 ++-- messagefoundry/api/app.py | 57 ++++++++---- messagefoundry/api/security.py | 19 ++-- tests/test_derived_gate_decision_audit.py | 6 +- tests/test_monitoring_read_pacing.py | 104 +++++++++++++++------- 5 files changed, 144 insertions(+), 59 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 293655a6b4..03df1300dd 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5347,7 +5347,7 @@ flowchart TB `refuse_unless_step_up_window_live`, which a route body makes after its gate has passed, `_record_route_refusal` in `messagefoundry/api/security.py` says what it records. The monitoring-read 429 that `require_monitoring_read` holds on a `GET /connections` reveal is raised - by the route body after its scope check; its gate wrote no grant row, and + by the route body after its scope and permission checks; its gate wrote no grant row, and `raise_deferred_monitoring_refusal` writes the `auth.gate_refused` row the gate would have. Other refusals a route body makes after its gate has passed write no `auth.gate_refused` row. - Routes that act on a Connection also check the identity's connection scope. That scope starts @@ -7695,12 +7695,15 @@ them cost work per call: `/graph/edges` rebuilds the wiring graph, and `/status` copies the in-memory metrics ring and reads no store; it was put in the set because the console's Flow and trends page reads it beside `/graph/edges`, but the console is not charged (below), so its pace bounds only JSON clients. The gate charges a per-actor sliding window at -admission, before the route's own work. On `GET /connections?reveal=` the read is still charged -at admission, but a 429 is held until the route has run its channel-scope check, so a reveal naming -a connection outside the caller's scope is still denied and audited as `auth.channel_denied` when -the budget is spent. A held 429 the route never raises, because the scope check or query -validation refused first, is answered by that refusal and writes no throttled row or log line. The -six routes share ONE budget per account: a read of any of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N +admission, before the route's own work. On `GET /connections` with a valid `reveal` value, a +429 is held until the route has run its channel-scope check and the reveal's +`messages:view_summary` check, so with the budget spent those refusals still answer 403 and write +their `auth.channel_denied` or `auth.permission_denied` row, as on main. A held 429 the route never +raises, at least because one of those checks refused first, writes no throttled row or log line. A +reveal value that will fail validation is charged and refused at the gate like any other read. +The limiter records no refused attempt, so once the budget is spent a reveal those checks refuse +spends nothing more. The six routes share ONE budget per account: a read of any of them spends +it. The budget is in-process, per API process, so N engine shards multiply it by N (*Business-logic limits* above). **Key.** `identity.user_id` of the bearer session the request presents. A Prometheus-style scraper diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 12eb94ce1a..1ea25d9e54 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -67,7 +67,7 @@ from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse, StreamingResponse from fastapi.telemetry import TelemetryConfig -from pydantic import PrivateAttr +from pydantic import PrivateAttr, TypeAdapter, ValidationError from starlette.datastructures import MutableHeaders from starlette.types import ASGIApp, Message, Receive, Scope, Send @@ -620,6 +620,22 @@ _CONNECTION_TEST_TIMEOUT = 35.0 # overall cap for a POST /connections/{name}/test probe (seconds) _MAX_WS_CONNECTIONS = 64 # cap concurrent /ws/stats sockets (API-WS) _WS_FRAME_SECONDS = 1.0 # one /ws/stats frame this often; the caller is re-resolved before each + + +_CONNECTION_NAME_ADAPTER: TypeAdapter[str] = TypeAdapter(ConnectionName) + + +def _valid_connection_name(value: str) -> bool: + """Whether ``value`` passes the ``ConnectionName`` rule the ``reveal`` query is validated by. + ``GET /connections`` defers its monitoring-read 429 only for a valid reveal, so a request that + will fail validation is refused, and recorded, at the gate (vault BACKLOG #1191).""" + try: + _CONNECTION_NAME_ADAPTER.validate_python(value) + except ValidationError: + return False + return True + + #: Path prefixes whose JSON responses are served ``Cache-Control: no-store`` (ASVS 14.2.2). These are #: the PHI-read route families — every route gated by ``require_phi_read`` and every step-up GET that #: charges the PHI-read hop/pacing budget lives under one of them, so a browser, a proxy or any other @@ -5683,7 +5699,11 @@ async def list_connections( request: Request, engine: Engine = Depends(_get_engine), identity: Identity = Depends( - require_monitoring_read(Permission.MONITORING_READ, defer_when_query="reveal") + require_monitoring_read( + Permission.MONITORING_READ, + defer_when_query="reveal", + defer_value_valid=_valid_connection_name, + ) ), # Annotated rather than ``= Query(None)``, for the reason get_message gives: the web console # calls this handler in-process, and a call that leaves it out must get None. @@ -5702,11 +5722,13 @@ async def list_connections( # Per-channel RBAC, as on GET /connections/{name}/events: a reveal naming a connection # outside the caller's scope is refused and audited as a channel denial. Checked BEFORE the # reveal is admitted, so a refused name spends no PHI-read budget and cannot be hidden - # behind a 429. For that reason the gate holds its monitoring-read 429 on a reveal, and it - # is raised here, after this check; the read was charged at admission either way (vault - # BACKLOG #1191). A scoped caller's dashboard carries no outbound rows at all. + # behind a 429. For that reason the gate holds a monitoring-read 429 on a valid reveal, and + # it is raised here, after this check and the reveal's permission check, so both refusals + # are recorded as on main (vault BACKLOG #1191). A scoped caller's dashboard carries no + # outbound rows at all. if reveal is not None: await _control_guard(engine, identity, reveal, client_ip(request)) + await _refuse_reveal_without_view_summary(request, identity) await raise_deferred_monitoring_refusal(request) await _admit_reveal(request, identity, reveal) out = await _dashboard_rows(engine, identity, reveal=reveal) @@ -6745,6 +6767,20 @@ def _conn_event_info(e: Any) -> ConnectionEventInfo: reason=e.reason, ) + async def _refuse_reveal_without_view_summary(request: Request, identity: Identity) -> None: + """Refuse a reveal from a caller without ``messages:view_summary``, audited as + ``auth.permission_denied`` (the permission half of :func:`_admit_reveal`).""" + if not identity.has(Permission.MESSAGES_VIEW_SUMMARY): + auth = get_auth(request) + if auth is not None: + await auth.audit_permission_denied( + identity, + Permission.MESSAGES_VIEW_SUMMARY, + request.url.path, + client=client_ip(request), + ) + raise HTTPException(403, "a reveal needs messages:view_summary") + async def _admit_reveal(request: Request, identity: Identity, reveal: int | str | None) -> None: """The gate a ``reveal`` request adds on top of its list route's ``monitoring:*`` gate. @@ -6762,16 +6798,7 @@ async def _admit_reveal(request: Request, identity: Identity, reveal: int | str route, so a future ``/ui`` route passing ``reveal`` must carry ``phi=True`` itself.""" if reveal is None: return - if not identity.has(Permission.MESSAGES_VIEW_SUMMARY): - auth = get_auth(request) - if auth is not None: - await auth.audit_permission_denied( - identity, - Permission.MESSAGES_VIEW_SUMMARY, - request.url.path, - client=client_ip(request), - ) - raise HTTPException(403, "a reveal needs messages:view_summary") + await _refuse_reveal_without_view_summary(request, identity) if not (_matched_route_path(request) or "").startswith("/ui/"): enforce_phi_read_hop(request) # Vault BACKLOG #2620: a PHI read, so it refuses a new address as require_phi_read diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 290f5a21b2..3d8f48de9b 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1993,7 +1993,9 @@ async def dependency(request: Request) -> Identity: def require_monitoring_read( - *permissions: Permission, defer_when_query: str | None = None + *permissions: Permission, + defer_when_query: str | None = None, + defer_value_valid: Callable[[str], bool] | None = None, ) -> Callable[[Request], Awaitable[Identity]]: """Like :func:`require`, plus a **per-actor pace** on six ``monitoring:read`` GETs (vault BACKLOG #1191, ASVS 15.2.2). Five of them cost store or parse work per call: ``/graph/edges`` rebuilds @@ -2016,16 +2018,23 @@ def require_monitoring_read( ``defer_when_query`` names a query parameter that delays the REFUSAL, not the charge: when the request carries it, the gate still charges the budget at admission, but a 429 it would answer is held on the request, with no decision row yet, until the route body calls - :func:`raise_deferred_monitoring_refusal` after its own scope check. A held 429 the route - never raises, because the scope check or query validation refused the request first, is - answered by that refusal and writes no throttled row or line. ``GET /connections`` defers on + :func:`raise_deferred_monitoring_refusal` after its own checks. ``defer_value_valid``, when + given, defers only a value that will pass the route's validation, so an invalid one is charged + and refused here as any other read. A held 429 the route never raises, at least because one of + its own checks refused the request first, is answered by that refusal and writes no throttled + row or line. ``GET /connections`` defers on ``reveal`` (vault BACKLOG #1191); docs/SECURITY.md, *Monitoring-read pacing*, says why.""" async def dependency(request: Request) -> Identity: auth, identity = await _admit(request, permissions, mfa_gate=True) if auth is None: return identity - if defer_when_query is not None and defer_when_query in request.query_params: + deferred_value = ( + request.query_params.get(defer_when_query) if defer_when_query is not None else None + ) + if deferred_value is not None and ( + defer_value_valid is None or defer_value_valid(deferred_value) + ): refusal = _charge_monitoring_read(request, auth, identity) if refusal is None: await _record_grant(request, auth, identity, permissions) diff --git a/tests/test_derived_gate_decision_audit.py b/tests/test_derived_gate_decision_audit.py index f905f435a3..51e041f0d8 100644 --- a/tests/test_derived_gate_decision_audit.py +++ b/tests/test_derived_gate_decision_audit.py @@ -326,8 +326,10 @@ def _names_called(node: ast.AST) -> list[str]: def test_every_gate_that_runs_admit_decides_inside_its_decision_block() -> None: """RED when: a gate factory calls ``_admit`` with no ``_recorded_decision`` block, so it writes no grant row for the requests it admits, or makes one of its own checks outside that block, so - the grant row is written before that check decides. ``require`` is the one factory that writes - its grant directly. The counts are the positive control: the walk found the seven gates, and a + the grant row is written before that check decides. ``require`` writes its grant directly, and + so does ``require_monitoring_read`` on its deferred-``reveal`` branch, whose charge + (``_charge_monitoring_read``) is not in ``_GATE_CHECKS``, so this walk does not check that + branch's order. The counts are the positive control: the walk found the seven gates, and a check in each.""" from messagefoundry.api import security diff --git a/tests/test_monitoring_read_pacing.py b/tests/test_monitoring_read_pacing.py index ebbdf1b654..02ad3e3cd5 100644 --- a/tests/test_monitoring_read_pacing.py +++ b/tests/test_monitoring_read_pacing.py @@ -213,23 +213,44 @@ def _decisions_on(rows: Sequence[Row], path: str) -> list[tuple[str, dict[str, o async def _scoped_service(engine: Engine, **overrides: object) -> AuthService: + """``vw`` (Viewer) and ``op`` (Operator, so it holds ``messages:view_summary``), each scoped + to ``IB_MINE``.""" service = await _service(engine, **overrides) - scoped = await service.store.get_user_by_username("vw") - assert scoped is not None - await service.set_channel_scope(scoped.id, ["IB_MINE"], actor="test") + op_id = await create_local_user_chosen( + service, + username="op", + password=PW, + display_name=None, + email=None, + roles=[Role.OPERATOR.value], + actor="test", + ) + op = await service.store.get_user(op_id) + assert op is not None and op.password_hash is not None + await service.store.set_password( + op_id, password_hash=op.password_hash, must_change_password=False, password_generated=False + ) + for name in ("vw", "op"): + user = await service.store.get_user_by_username(name) + assert user is not None + await service.set_channel_scope(user.id, ["IB_MINE"], actor="test") return service +def _actions(rows: Sequence[Row], action: str) -> list[dict[str, object]]: + return [json.loads(str(row["detail"] or "{}")) for row in rows if row["action"] == action] + + async def test_an_out_of_scope_reveal_is_denied_and_audited_with_the_budget_spent( engine: Engine, ) -> None: - """As on main, the scope check and its ``auth.channel_denied`` row come before the monitoring - pace: an account whose budget is spent still gets the channel denial for an out-of-scope - reveal, not a 429 that hides the probe. An in-scope reveal past the budget is still refused, - with one ``auth.gate_refused`` row and no grant row (BACKLOG #1197).""" + """The scope check's 403 and ``auth.channel_denied`` row come before the monitoring 429, as + main's 403 and row came with no pace at all: an account whose budget is spent still gets the + channel denial, not a 429 that hides the probe. An in-scope reveal past the budget is refused + 429, with one ``auth.gate_refused`` row and no grant row (BACKLOG #1197).""" service = await _scoped_service(engine, monitoring_read_rate_limit_per_actor=1) async with _client(engine, service) as c: - h = await _bearer(c, "vw") + h = await _bearer(c, "op") assert (await c.get("/status", headers=h)).status_code == 200 assert (await c.get("/status", headers=h)).status_code == 429 # the budget is spent denied = await c.get("/connections", params={"reveal": "IB_THEIRS"}, headers=h) @@ -238,38 +259,61 @@ async def test_an_out_of_scope_reveal_is_denied_and_audited_with_the_budget_spen assert paced.status_code == 429 assert int(paced.headers["Retry-After"]) >= 1 rows = await engine.store.list_audit(limit=1000) - denials = [ - json.loads(str(row["detail"] or "{}")) - for row in rows - if row["action"] == "auth.channel_denied" - ] - assert any("IB_THEIRS" in json.dumps(d) for d in denials), denials + assert any("IB_THEIRS" in json.dumps(d) for d in _actions(rows, "auth.channel_denied")) on_path = _decisions_on(rows, "/connections") - # Only the in-scope reveal's refusal is written: the out-of-scope one was answered, and - # recorded, as a channel denial, and its held 429 was never raised. + # The out-of-scope reveal was answered, and recorded, as a channel denial; its held 429 was + # never raised. assert [a for a, _ in on_path] == ["auth.gate_refused"], on_path assert {d["reason"] for _, d in on_path} == {"throttled"} -async def test_a_refused_reveal_still_spends_the_budget(engine: Engine) -> None: - """The reveal's charge is taken at admission: a reveal the scope check denies, and one whose - value fails validation, each spend a read, so neither is an unpaced probe.""" +async def test_a_reveal_without_view_summary_is_denied_with_the_budget_spent( + engine: Engine, +) -> None: + """As on main, a reveal by a caller without ``messages:view_summary`` gets the 403 and its + ``auth.permission_denied`` row, not a monitoring 429, even with the budget spent.""" + service = await _scoped_service(engine, monitoring_read_rate_limit_per_actor=1) + async with _client(engine, service) as c: + h = await _bearer(c, "vw") + assert (await c.get("/status", headers=h)).status_code == 200 + refused = await c.get("/connections", params={"reveal": "IB_MINE"}, headers=h) + assert refused.status_code == 403, refused.text + assert refused.json()["detail"] == "a reveal needs messages:view_summary" + rows = await engine.store.list_audit(limit=1000) + assert any( + d.get("permission") == "messages:view_summary" + for d in _actions(rows, "auth.permission_denied") + ) + + +async def test_an_invalid_reveal_over_the_budget_writes_a_decision_row(engine: Engine) -> None: + """A reveal value that will fail validation is not deferred: over the budget it is refused 429 + at the gate with its ``auth.gate_refused`` row, so the request leaves a decision row, as main's + grant row did.""" + service = await _scoped_service(engine, monitoring_read_rate_limit_per_actor=1) + async with _client(engine, service) as c: + h = await _bearer(c, "vw") + invalid = await c.get("/connections", params={"reveal": ""}, headers=h) + assert invalid.status_code == 422 # under the budget: charged, granted, then invalid + again = await c.get("/connections", params={"reveal": ""}, headers=h) + assert again.status_code == 429 + rows = await engine.store.list_audit(limit=1000) + assert [a for a, _ in _decisions_on(rows, "/connections")] == [ + "auth.permission_granted", + "auth.gate_refused", + ] + + +async def test_an_out_of_scope_reveal_under_the_budget_spends_a_read(engine: Engine) -> None: + """While the budget has room, a reveal the scope check denies spends a read like any other. + Once it is spent, the limiter records no refused attempt, so such a reveal is answered by the + scope check's 403 with no further charge.""" service = await _scoped_service(engine, monitoring_read_rate_limit_per_actor=1) async with _client(engine, service) as c: h = await _bearer(c, "vw") denied = await c.get("/connections", params={"reveal": "IB_THEIRS"}, headers=h) assert denied.status_code == 403 assert (await c.get("/status", headers=h)).status_code == 429 - h_other = await _bearer(c, "other") - invalid = await c.get("/connections", params={"reveal": ""}, headers=h_other) - assert invalid.status_code == 422 - assert (await c.get("/status", headers=h_other)).status_code == 429 - # Over the budget, an invalid reveal is still answered by its validation 422: the held 429 - # is never raised, so it writes no throttled row on the path. - again = await c.get("/connections", params={"reveal": ""}, headers=h_other) - assert again.status_code == 422 - rows = await engine.store.list_audit(limit=1000) - assert [a for a, _ in _decisions_on(rows, "/connections") if a == "auth.gate_refused"] == [] async def test_an_in_scope_reveal_under_the_budget_is_charged_once(engine: Engine) -> None: @@ -277,7 +321,7 @@ async def test_an_in_scope_reveal_under_the_budget_is_charged_once(engine: Engin async with _client(engine, service) as c: h = await _bearer(c, "vw") # A Viewer passes the scope check and the pace, and is then refused by the reveal's own - # permission check, which runs after both. + # permission check. passed = await c.get("/connections", params={"reveal": "IB_MINE"}, headers=h) assert passed.status_code == 403 assert passed.json()["detail"] == "a reveal needs messages:view_summary" From 5f8eb473da467d8a5bb6e7a3350d98ecbd1d2ba6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 12:56:37 -0600 Subject: [PATCH 12/19] Monitoring-read pacing: correct the review round's text From code review round-b52be33f39, text only: - "as on main" is replaced: an over-budget refused reveal answers and records its denial as the pre-pacing route did, but writes no monitoring:read grant row, and that path is not paced (SECURITY.md); - the authorization-flow text says the 429 is held only for a valid reveal; - the _GATE_CHECKS comment says "at least" and why _charge_monitoring_read is left out; - a test docstring no longer claims an over-budget case it does not run. Vault BACKLOG #1191. --- docs/SECURITY.md | 8 +++++--- messagefoundry/api/app.py | 2 +- tests/test_derived_gate_decision_audit.py | 6 ++++-- tests/test_monitoring_read_pacing.py | 9 ++++----- 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 03df1300dd..df4b027712 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5346,7 +5346,8 @@ flowchart TB gate's does. For the step-up refusals of `spend_step_up_action` and `refuse_unless_step_up_window_live`, which a route body makes after its gate has passed, `_record_route_refusal` in `messagefoundry/api/security.py` says what it records. The - monitoring-read 429 that `require_monitoring_read` holds on a `GET /connections` reveal is raised + monitoring-read 429 that `require_monitoring_read` holds on a `GET /connections` reveal with a + valid value is raised by the route body after its scope and permission checks; its gate wrote no grant row, and `raise_deferred_monitoring_refusal` writes the `auth.gate_refused` row the gate would have. Other refusals a route body makes after its gate has passed write no `auth.gate_refused` row. @@ -7698,11 +7699,12 @@ its pace bounds only JSON clients. The gate charges a per-actor sliding window a admission, before the route's own work. On `GET /connections` with a valid `reveal` value, a 429 is held until the route has run its channel-scope check and the reveal's `messages:view_summary` check, so with the budget spent those refusals still answer 403 and write -their `auth.channel_denied` or `auth.permission_denied` row, as on main. A held 429 the route never +their `auth.channel_denied` or `auth.permission_denied` row, as the pre-pacing route did. Unlike +that route, they then write no `monitoring:read` grant row. A held 429 the route never raises, at least because one of those checks refused first, writes no throttled row or log line. A reveal value that will fail validation is charged and refused at the gate like any other read. The limiter records no refused attempt, so once the budget is spent a reveal those checks refuse -spends nothing more. The six routes share ONE budget per account: a read of any of them spends +spends nothing more, while each still writes its denial row: that path is not paced. The six routes share ONE budget per account: a read of any of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N (*Business-logic limits* above). diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 1ea25d9e54..6950b8f11b 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -5724,7 +5724,7 @@ async def list_connections( # reveal is admitted, so a refused name spends no PHI-read budget and cannot be hidden # behind a 429. For that reason the gate holds a monitoring-read 429 on a valid reveal, and # it is raised here, after this check and the reveal's permission check, so both refusals - # are recorded as on main (vault BACKLOG #1191). A scoped caller's dashboard carries no + # are answered and recorded as before pacing (vault BACKLOG #1191). A scoped caller's dashboard carries no # outbound rows at all. if reveal is not None: await _control_guard(engine, identity, reveal, client_ip(request)) diff --git a/tests/test_derived_gate_decision_audit.py b/tests/test_derived_gate_decision_audit.py index 51e041f0d8..129d845e57 100644 --- a/tests/test_derived_gate_decision_audit.py +++ b/tests/test_derived_gate_decision_audit.py @@ -300,8 +300,10 @@ async def test_require_step_up_action_records_its_throttle_too(engine: Engine) - assert reasons == [(_REFUSED, "step_up"), (_REFUSED, "throttled")] -#: The calls in a derived gate that can refuse a request or spend something on it. Each must run -#: inside the gate's ``_recorded_decision`` block, or the grant row is written before it decides. +#: At least the calls in a derived gate that can refuse a request or spend something on it. Each +#: must run inside the gate's ``_recorded_decision`` block, or the grant row is written before it +#: decides. ``_charge_monitoring_read`` is left out on purpose: it runs outside the block on +#: ``require_monitoring_read``'s deferred-``reveal`` branch (see the test below). _GATE_CHECKS = frozenset( { "_enforce_admin_write_pacing", diff --git a/tests/test_monitoring_read_pacing.py b/tests/test_monitoring_read_pacing.py index 02ad3e3cd5..a1beb16d7b 100644 --- a/tests/test_monitoring_read_pacing.py +++ b/tests/test_monitoring_read_pacing.py @@ -270,7 +270,7 @@ async def test_an_out_of_scope_reveal_is_denied_and_audited_with_the_budget_spen async def test_a_reveal_without_view_summary_is_denied_with_the_budget_spent( engine: Engine, ) -> None: - """As on main, a reveal by a caller without ``messages:view_summary`` gets the 403 and its + """As before pacing, a reveal by a caller without ``messages:view_summary`` gets the 403 and its ``auth.permission_denied`` row, not a monitoring 429, even with the budget spent.""" service = await _scoped_service(engine, monitoring_read_rate_limit_per_actor=1) async with _client(engine, service) as c: @@ -288,8 +288,8 @@ async def test_a_reveal_without_view_summary_is_denied_with_the_budget_spent( async def test_an_invalid_reveal_over_the_budget_writes_a_decision_row(engine: Engine) -> None: """A reveal value that will fail validation is not deferred: over the budget it is refused 429 - at the gate with its ``auth.gate_refused`` row, so the request leaves a decision row, as main's - grant row did.""" + at the gate with its ``auth.gate_refused`` row, so the request leaves a decision row, as the + pre-pacing grant row did.""" service = await _scoped_service(engine, monitoring_read_rate_limit_per_actor=1) async with _client(engine, service) as c: h = await _bearer(c, "vw") @@ -306,8 +306,7 @@ async def test_an_invalid_reveal_over_the_budget_writes_a_decision_row(engine: E async def test_an_out_of_scope_reveal_under_the_budget_spends_a_read(engine: Engine) -> None: """While the budget has room, a reveal the scope check denies spends a read like any other. - Once it is spent, the limiter records no refused attempt, so such a reveal is answered by the - scope check's 403 with no further charge.""" + The over-budget case is the out-of-scope test above.""" service = await _scoped_service(engine, monitoring_read_rate_limit_per_actor=1) async with _client(engine, service) as c: h = await _bearer(c, "vw") From c7c4959e269708b5a17b26c28001de0bedd1f06e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 15:27:37 -0600 Subject: [PATCH 13/19] Answer the 3167 hold: new-address refusal before the held 429, control text GET /connections with a reveal now runs the reveal's refusals (its messages:view_summary check, the PHI-read serve hop and the new-address refusal) before the held monitoring-read 429, then charges the PHI-read budget. Over budget, a token replayed from a new host gets the step-up 403 and its auth.new_address_reverify_required row, not a 429. _admit_reveal is split into _refuse_reveal and _charge_reveal; the other reveal routes keep the same order. Text: SECURITY-LOOSENING names the serve_ui condition; SECURITY.md says the /ws/stats frame runs store.stats() and names the new-address refusal in the deferral order; the raise_deferred_monitoring_refusal docstring names the test that pins the one deferring route; the list_connections comment states the owner ruling of 2026-11-23 (no grant row on a refused over-budget reveal). BACKLOG #1191 --- docs/SECURITY-LOOSENING.md | 5 +++-- docs/SECURITY.md | 15 +++++++++----- messagefoundry/api/app.py | 30 ++++++++++++++++++++++------ messagefoundry/api/security.py | 5 ++++- tests/test_monitoring_read_pacing.py | 28 ++++++++++++++++++++++++-- 5 files changed, 67 insertions(+), 16 deletions(-) diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index d1489ac931..fcf2019d59 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -1178,8 +1178,9 @@ count is above `0` (vault BACKLOG #2613). - **What you lose:** the per-account pace on six `monitoring:read` GETs of the JSON API ([SECURITY.md](SECURITY.md), *Monitoring-read pacing*, names them). One signed-in account can make the engine rebuild the wiring graph and scan the store through those routes faster, up to as fast - as it answers. With the pace on, the same work stays reachable unpaced through the web console's - in-process reads and the `/ws/stats` socket; that section, *What it does not charge*, says how. + as it answers. With the pace on, the same work stays reachable unpaced through the `/ws/stats` + socket and, where the web console is served (`[api].serve_ui` on), through its in-process reads; + that section, *What it does not charge*, says how. - **When acceptable:** a monitoring tool on one known account that polls faster than the default allows, on a host no untrusted client can reach. Prefer a modest raise to turning it off. - **Compensating controls:** keep sessions short, and restrict who reaches the API with diff --git a/docs/SECURITY.md b/docs/SECURITY.md index df4b027712..a2ce565a65 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5348,7 +5348,8 @@ flowchart TB `_record_route_refusal` in `messagefoundry/api/security.py` says what it records. The monitoring-read 429 that `require_monitoring_read` holds on a `GET /connections` reveal with a valid value is raised - by the route body after its scope and permission checks; its gate wrote no grant row, and + by the route body after its scope, permission, serve-hop and new-address checks; its gate wrote + no grant row, and `raise_deferred_monitoring_refusal` writes the `auth.gate_refused` row the gate would have. Other refusals a route body makes after its gate has passed write no `auth.gate_refused` row. - Routes that act on a Connection also check the identity's connection scope. That scope starts @@ -7697,9 +7698,12 @@ copies the in-memory metrics ring and reads no store; it was put in the set beca Flow and trends page reads it beside `/graph/edges`, but the console is not charged (below), so its pace bounds only JSON clients. The gate charges a per-actor sliding window at admission, before the route's own work. On `GET /connections` with a valid `reveal` value, a -429 is held until the route has run its channel-scope check and the reveal's -`messages:view_summary` check, so with the budget spent those refusals still answer 403 and write -their `auth.channel_denied` or `auth.permission_denied` row, as the pre-pacing route did. Unlike +429 is held until the route has run its channel-scope check and the reveal's own refusals: its +`messages:view_summary` check, the PHI-read serve-hop refusal and the new-address refusal (vault +BACKLOG #2620). So with the budget spent those refusals still answer with their own status and +record what the pre-pacing route recorded: an `auth.channel_denied` or `auth.permission_denied` +row, or the new-address refusal's deduped `auth.new_address_reverify_required` row; the serve-hop +refusal writes none. Unlike that route, they then write no `monitoring:read` grant row. A held 429 the route never raises, at least because one of those checks refused first, writes no throttled row or log line. A reveal value that will fail validation is charged and refused at the gate like any other read. @@ -7752,7 +7756,8 @@ tab makes no HTTP request to the six routes. So a signed-in console session that Other `monitoring:read` reads that cost work are not charged either. At least `GET /events`, `GET /connections/{name}/events` and `GET /config/provenance` stay on plain `require`, and the -`/ws/stats` socket, a frame a second, runs the `/stats` store aggregate on every frame and, where +`/ws/stats` socket, a frame a second, runs `store.stats()` (the outbox counts by status, not the +whole `/stats` aggregate) on every frame and, where the web console is served, the connections-dashboard read (`_dashboard_rows`, the work behind `GET /connections`) too, with no charge here. The socket cap of 64 is per API process, not per account, so one account may hold all 64: about 3,840 of each such read a minute, with no 429. diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 6950b8f11b..df7a2db865 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -5723,14 +5723,17 @@ async def list_connections( # outside the caller's scope is refused and audited as a channel denial. Checked BEFORE the # reveal is admitted, so a refused name spends no PHI-read budget and cannot be hidden # behind a 429. For that reason the gate holds a monitoring-read 429 on a valid reveal, and - # it is raised here, after this check and the reveal's permission check, so both refusals - # are answered and recorded as before pacing (vault BACKLOG #1191). A scoped caller's dashboard carries no - # outbound rows at all. + # it is raised here, after this check and the reveal's own refusals (its permission, the + # serve hop and the new address). Each of those is answered and recorded as before pacing + # (the hop refusal writes no row), except that with the budget spent no monitoring:read + # grant row is written (owner ruling 2026-11-23; vault BACKLOG #1191). A scoped caller's + # dashboard carries no outbound rows at all. if reveal is not None: await _control_guard(engine, identity, reveal, client_ip(request)) - await _refuse_reveal_without_view_summary(request, identity) + await _refuse_reveal(request, identity) await raise_deferred_monitoring_refusal(request) - await _admit_reveal(request, identity, reveal) + if reveal is not None: + _charge_reveal(request, identity) out = await _dashboard_rows(engine, identity, reveal=reveal) if reveal is not None: # The audit records what the response carried, not what was asked for: an in-scope @@ -6798,12 +6801,27 @@ async def _admit_reveal(request: Request, identity: Identity, reveal: int | str route, so a future ``/ui`` route passing ``reveal`` must carry ``phi=True`` itself.""" if reveal is None: return + await _refuse_reveal(request, identity) + _charge_reveal(request, identity) + + def _reveal_over_http(request: Request) -> bool: + """Whether a reveal came over HTTP rather than from a ``/ui`` route calling in process, + which took the hop, new-address and budget checks in ``require_ui(..., phi=True)``.""" + return not (_matched_route_path(request) or "").startswith("/ui/") + + async def _refuse_reveal(request: Request, identity: Identity) -> None: + """The refusals of :func:`_admit_reveal`, without its PHI-read charge, for a route that + must answer them before a held monitoring-read 429 (``GET /connections``).""" await _refuse_reveal_without_view_summary(request, identity) - if not (_matched_route_path(request) or "").startswith("/ui/"): + if _reveal_over_http(request): enforce_phi_read_hop(request) # Vault BACKLOG #2620: a PHI read, so it refuses a new address as require_phi_read # does, before the budget. The /ui twins asked in require_ui's phi=True arm. await refuse_from_new_address(request) + + def _charge_reveal(request: Request, identity: Identity) -> None: + """The PHI-read charge of :func:`_admit_reveal`, run after :func:`_refuse_reveal`.""" + if _reveal_over_http(request): enforce_phi_read_pacing(request, identity) async def _redact_reasons( diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 3d8f48de9b..30698f887e 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -2073,7 +2073,10 @@ async def raise_deferred_monitoring_refusal(request: Request) -> None: A no-op where nothing is held, at least: the budget had room, the no-auth path, a request without the deferring parameter, and the web console's in-process call, whose own request carries nothing held. A route that defers must call this on every path that does the paced - work; nothing checks that it does, so a missed call serves a throttled caller.""" + work, or it serves a throttled caller. No runtime check enforces that. For the one deferring + route, ``GET /connections``, a test in ``tests/test_monitoring_read_pacing.py`` pins the raise: + ``test_an_out_of_scope_reveal_is_denied_and_audited_with_the_budget_spent``. A new deferring + route needs its own such test.""" held = getattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR, None) if not isinstance(held, _DeferredRefusal): return diff --git a/tests/test_monitoring_read_pacing.py b/tests/test_monitoring_read_pacing.py index a1beb16d7b..0e5fd926d6 100644 --- a/tests/test_monitoring_read_pacing.py +++ b/tests/test_monitoring_read_pacing.py @@ -69,9 +69,11 @@ async def _service(engine: Engine, **overrides: object) -> AuthService: return service -def _client(engine: Engine, service: AuthService, *, serve_ui: bool = False) -> httpx.AsyncClient: +def _client( + engine: Engine, service: AuthService, *, serve_ui: bool = False, ip: str = "127.0.0.1" +) -> httpx.AsyncClient: transport = httpx.ASGITransport( - app=create_app(engine, auth=service, serve_ui=serve_ui), client=("127.0.0.1", 123) + app=create_app(engine, auth=service, serve_ui=serve_ui), client=(ip, 123) ) return httpx.AsyncClient(transport=transport, base_url="http://t") @@ -286,6 +288,28 @@ async def test_a_reveal_without_view_summary_is_denied_with_the_budget_spent( ) +async def test_a_reveal_from_a_new_address_is_refused_for_it_with_the_budget_spent( + engine: Engine, +) -> None: + """With the budget spent, an in-scope reveal on a token replayed from a host the session has + not verified from gets the new-address refusal (403 + ``X-Step-Up-Required``) and its + ``auth.new_address_reverify_required`` row, not a 429 that hides it (vault BACKLOG #2620).""" + service = await _scoped_service( + engine, monitoring_read_rate_limit_per_actor=1, admin_new_ip_step_up=True + ) + async with _client(engine, service, ip="10.0.0.1") as a: + h = await _bearer(a, "op") + assert (await a.get("/status", headers=h)).status_code == 200 + assert (await a.get("/status", headers=h)).status_code == 429 # the budget is spent + async with _client(engine, service, ip="10.9.9.9") as b: + r = await b.get("/connections", params={"reveal": "IB_MINE"}, headers=h) + assert (r.status_code, r.headers.get("X-Step-Up-Required")) == (403, "1"), r.text + rows = await engine.store.list_audit(limit=1000) + assert [d.get("seen_ip") for d in _actions(rows, "auth.new_address_reverify_required")] == [ + "10.9.9.9" + ] + + async def test_an_invalid_reveal_over_the_budget_writes_a_decision_row(engine: Engine) -> None: """A reveal value that will fail validation is not deferred: over the budget it is refused 429 at the gate with its ``auth.gate_refused`` row, so the request leaves a decision row, as the From e613264f57fe8d62dff75de0a4e0e83be83dc03b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 15:41:58 -0600 Subject: [PATCH 14/19] Fix the review round's text findings on the 3167 hold fix Text only. SECURITY-LOOSENING names [security].serve_web_console, not the refused [api].serve_ui, and says which /ws/stats work is unconditional. SECURITY.md no longer says each refused over-budget reveal writes its denial row: a serve-hop refusal, and a deduped new-address refusal, leave no row. The list_connections comment no longer extends the 2026-11-23 owner ruling to those zero-row cases. Docstrings that named _admit_reveal for GET /connections now name _refuse_reveal and _charge_reveal. Two closed enumerations now say "at least" or "any other route". BACKLOG #1191 --- docs/SECURITY-LOOSENING.md | 8 +++++--- docs/SECURITY.md | 8 +++++--- messagefoundry/api/app.py | 17 +++++++++++------ messagefoundry/api/security.py | 13 +++++++------ 4 files changed, 28 insertions(+), 18 deletions(-) diff --git a/docs/SECURITY-LOOSENING.md b/docs/SECURITY-LOOSENING.md index fcf2019d59..bf4fc30282 100644 --- a/docs/SECURITY-LOOSENING.md +++ b/docs/SECURITY-LOOSENING.md @@ -1178,9 +1178,11 @@ count is above `0` (vault BACKLOG #2613). - **What you lose:** the per-account pace on six `monitoring:read` GETs of the JSON API ([SECURITY.md](SECURITY.md), *Monitoring-read pacing*, names them). One signed-in account can make the engine rebuild the wiring graph and scan the store through those routes faster, up to as fast - as it answers. With the pace on, the same work stays reachable unpaced through the `/ws/stats` - socket and, where the web console is served (`[api].serve_ui` on), through its in-process reads; - that section, *What it does not charge*, says how. + as it answers. With the pace on, some of that work stays reachable unpaced: the `/ws/stats` + socket runs the outbox counts on every frame, and where the web console is served + (`[security].serve_web_console` on) that socket also runs the `GET /connections` dashboard read, + and the console's in-process reads reach the paced handlers uncharged. That section, *What it + does not charge*, says how. - **When acceptable:** a monitoring tool on one known account that polls faster than the default allows, on a host no untrusted client can reach. Prefer a modest raise to turning it off. - **Compensating controls:** keep sessions short, and restrict who reaches the API with diff --git a/docs/SECURITY.md b/docs/SECURITY.md index a2ce565a65..ac40952162 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5348,8 +5348,8 @@ flowchart TB `_record_route_refusal` in `messagefoundry/api/security.py` says what it records. The monitoring-read 429 that `require_monitoring_read` holds on a `GET /connections` reveal with a valid value is raised - by the route body after its scope, permission, serve-hop and new-address checks; its gate wrote - no grant row, and + by the route body after at least its scope, permission, serve-hop and new-address checks; its + gate wrote no grant row, and `raise_deferred_monitoring_refusal` writes the `auth.gate_refused` row the gate would have. Other refusals a route body makes after its gate has passed write no `auth.gate_refused` row. - Routes that act on a Connection also check the identity's connection scope. That scope starts @@ -7708,7 +7708,9 @@ that route, they then write no `monitoring:read` grant row. A held 429 the route raises, at least because one of those checks refused first, writes no throttled row or log line. A reveal value that will fail validation is charged and refused at the gate like any other read. The limiter records no refused attempt, so once the budget is spent a reveal those checks refuse -spends nothing more, while each still writes its denial row: that path is not paced. The six routes share ONE budget per account: a read of any of them spends +spends nothing more: that path is not paced. Most such refusals write their denial row, but a +serve-hop refusal, and a new-address refusal whose row was deduped, leave no row of any kind for +that request. The six routes share ONE budget per account: a read of any of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N (*Business-logic limits* above). diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index df7a2db865..6938c18bfc 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -5724,10 +5724,12 @@ async def list_connections( # reveal is admitted, so a refused name spends no PHI-read budget and cannot be hidden # behind a 429. For that reason the gate holds a monitoring-read 429 on a valid reveal, and # it is raised here, after this check and the reveal's own refusals (its permission, the - # serve hop and the new address). Each of those is answered and recorded as before pacing - # (the hop refusal writes no row), except that with the budget spent no monitoring:read - # grant row is written (owner ruling 2026-11-23; vault BACKLOG #1191). A scoped caller's - # dashboard carries no outbound rows at all. + # serve hop and the new address), and each is answered as before pacing. With the budget + # spent none of them writes the monitoring:read grant row main wrote: the scope and + # permission refusals write only their denial row (owner ruling 2026-11-23), and the hop + # refusal, or a new-address refusal whose row is deduped, writes no row at all, which no + # ruling covers (vault BACKLOG #1191). A scoped caller's dashboard carries no outbound + # rows at all. if reveal is not None: await _control_guard(engine, identity, reveal, client_ip(request)) await _refuse_reveal(request, identity) @@ -5789,7 +5791,8 @@ async def _dashboard_rows( ) -> list[ConnectionRow]: """The dashboard rows, channel-scoped, with ``error`` gated and masked on every row and lifted on the rows of the ONE connection ``reveal`` names (BACKLOG #2443). The caller has - already passed :func:`_admit_reveal` for any ``reveal``; the stats socket passes none.""" + already passed :func:`_refuse_reveal` and :func:`_charge_reveal` for any ``reveal``; the + stats socket passes none.""" rows = await _connection_rows(engine, identity) if reveal is None: # the stats socket, every second, and every bare load return [redact_unauthorized(r, identity) for r in rows] @@ -6791,7 +6794,9 @@ async def _admit_reveal(request: Request, identity: Identity, reveal: int | str A reveal hands out one reason or one connection's error whole, which is ``messages:view_summary`` data (BACKLOG #2443). ``reveal`` is an event or alert id, or a connection name on ``GET /connections`` and, for its ``reveal=true`` flag, on - ``GET /connections/{name}/metadata``. A caller without that permission is refused, + ``GET /connections/{name}/metadata``. ``GET /connections`` does not call this: it calls + :func:`_refuse_reveal`, then raises any held monitoring-read 429, then + :func:`_charge_reveal`. A caller without that permission is refused, and the refusal is audited as ``auth.permission_denied`` like every other one (ASVS 16.3.2). Over HTTP the reveal is also a PHI read: it takes the serve-hop refusal, the new-address refusal (vault BACKLOG diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 30698f887e..2603b2356a 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1630,7 +1630,8 @@ async def refuse_from_new_address(request: Request) -> None: The step-up gates already asked this. The PHI reads and the paced writes did not, so on a first deployment a bearer token replayed from a second address would have read message bodies and started or stopped connections with no signal. Callers: :func:`require_phi_read`, - :func:`require_paced` and the HTTP reveal path in ``api/app.py`` (``_admit_reveal``). It gives + :func:`require_paced` and the HTTP reveal path in ``api/app.py`` (``_refuse_reveal``, which + ``_admit_reveal`` and ``GET /connections`` call). It gives them the step-up gates' refusal: 403 + ``X-Step-Up-Required: 1``, cleared by a ``POST /me/reauth`` from the new address, which re-anchors the session. An ``oidc`` session is sent to the IdP step-up instead (:func:`_step_up_refusal`). A first sighting writes @@ -1641,7 +1642,7 @@ async def refuse_from_new_address(request: Request) -> None: the JSON API's repeated monitoring reads, and a JSON client whose address changes behind a NAT pool, or behind a proxy not listed in ``[api].trusted_proxies``, would be refused on every one until a step-up. The web console's in-process reads go through ``require_ui`` and reach neither - gate. A monitoring ``reveal`` read does ask, through ``_admit_reveal`` in ``api/app.py``. + gate. A monitoring ``reveal`` read does ask, through ``_refuse_reveal`` in ``api/app.py``. Costs one session read per request while ``[auth].admin_new_ip_step_up`` is on, and one more on a refusal, to pick its wording. The gate has @@ -2073,10 +2074,10 @@ async def raise_deferred_monitoring_refusal(request: Request) -> None: A no-op where nothing is held, at least: the budget had room, the no-auth path, a request without the deferring parameter, and the web console's in-process call, whose own request carries nothing held. A route that defers must call this on every path that does the paced - work, or it serves a throttled caller. No runtime check enforces that. For the one deferring - route, ``GET /connections``, a test in ``tests/test_monitoring_read_pacing.py`` pins the raise: - ``test_an_out_of_scope_reveal_is_denied_and_audited_with_the_budget_spent``. A new deferring - route needs its own such test.""" + work, or it serves a throttled caller. No runtime check enforces that. For ``GET /connections`` + a test in ``tests/test_monitoring_read_pacing.py`` pins the raise: + ``test_an_out_of_scope_reveal_is_denied_and_audited_with_the_budget_spent``. Any other route + that passes ``defer_when_query`` needs its own such test.""" held = getattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR, None) if not isinstance(held, _DeferredRefusal): return From 2bb1383c632a44eda485c9b6a8dc64dcc4193c63 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 15:48:10 -0600 Subject: [PATCH 15/19] Over-budget reveal refused at the hop or a new address writes the throttled row With the monitoring-read budget spent, GET /connections?reveal= refused by the serve-hop refusal (no row of its own) or by a repeated new-address refusal (row deduped) left no decision row. The route now writes the held 429's auth.gate_refused row (reason throttled), with no log line, before that refusal propagates (record_deferred_monitoring_refusal). The scope and view_summary refusals keep writing only their denial row, per the owner ruling of 2026-11-23. SECURITY.md and the route comment say so. BACKLOG #1191 --- docs/SECURITY.md | 11 +++++---- messagefoundry/api/app.py | 34 +++++++++++++++++++--------- messagefoundry/api/security.py | 24 +++++++++++++++++--- tests/test_monitoring_read_pacing.py | 31 +++++++++++++++++++++++-- 4 files changed, 79 insertions(+), 21 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index ac40952162..98e581b47d 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7703,14 +7703,15 @@ admission, before the route's own work. On `GET /connections` with a valid `reve BACKLOG #2620). So with the budget spent those refusals still answer with their own status and record what the pre-pacing route recorded: an `auth.channel_denied` or `auth.permission_denied` row, or the new-address refusal's deduped `auth.new_address_reverify_required` row; the serve-hop -refusal writes none. Unlike -that route, they then write no `monitoring:read` grant row. A held 429 the route never +refusal writes none of its own. Unlike +that route, they then write no `monitoring:read` grant row. The serve-hop and new-address refusals +also write the held 429's `auth.gate_refused` row (reason `throttled`) before they are answered, +with no log line, so each such request still leaves a decision row. A held 429 the route never raises, at least because one of those checks refused first, writes no throttled row or log line. A reveal value that will fail validation is charged and refused at the gate like any other read. The limiter records no refused attempt, so once the budget is spent a reveal those checks refuse -spends nothing more: that path is not paced. Most such refusals write their denial row, but a -serve-hop refusal, and a new-address refusal whose row was deduped, leave no row of any kind for -that request. The six routes share ONE budget per account: a read of any of them spends +spends nothing more: that path is not paced. Each such refusal leaves at least one row: its +denial row, or the throttled row above. The six routes share ONE budget per account: a read of any of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N (*Business-logic limits* above). diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 6938c18bfc..d9edc30319 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -271,6 +271,7 @@ raise_deferred_monitoring_refusal, recheck_standing, recheck_standing_or_refusal, + record_deferred_monitoring_refusal, refuse_from_new_address, refuse_undeclared_route, require, @@ -5726,13 +5727,19 @@ async def list_connections( # it is raised here, after this check and the reveal's own refusals (its permission, the # serve hop and the new address), and each is answered as before pacing. With the budget # spent none of them writes the monitoring:read grant row main wrote: the scope and - # permission refusals write only their denial row (owner ruling 2026-11-23), and the hop - # refusal, or a new-address refusal whose row is deduped, writes no row at all, which no - # ruling covers (vault BACKLOG #1191). A scoped caller's dashboard carries no outbound - # rows at all. + # permission refusals write only their denial row (owner ruling 2026-11-23). The hop and + # new-address refusals also write the held throttled row before they propagate, because + # the hop refusal writes no row of its own and a new-address row is deduped, so without + # it such a request would leave no decision row (vault BACKLOG #1191). A scoped caller's + # dashboard carries no outbound rows at all. if reveal is not None: await _control_guard(engine, identity, reveal, client_ip(request)) - await _refuse_reveal(request, identity) + await _refuse_reveal_without_view_summary(request, identity) + try: + await _refuse_reveal_phi_read(request) + except HTTPException: + await record_deferred_monitoring_refusal(request) + raise await raise_deferred_monitoring_refusal(request) if reveal is not None: _charge_reveal(request, identity) @@ -5791,8 +5798,8 @@ async def _dashboard_rows( ) -> list[ConnectionRow]: """The dashboard rows, channel-scoped, with ``error`` gated and masked on every row and lifted on the rows of the ONE connection ``reveal`` names (BACKLOG #2443). The caller has - already passed :func:`_refuse_reveal` and :func:`_charge_reveal` for any ``reveal``; the - stats socket passes none.""" + already passed the refusals of :func:`_refuse_reveal` and :func:`_charge_reveal` for any + ``reveal``; the stats socket passes none.""" rows = await _connection_rows(engine, identity) if reveal is None: # the stats socket, every second, and every bare load return [redact_unauthorized(r, identity) for r in rows] @@ -6795,8 +6802,8 @@ async def _admit_reveal(request: Request, identity: Identity, reveal: int | str ``messages:view_summary`` data (BACKLOG #2443). ``reveal`` is an event or alert id, or a connection name on ``GET /connections`` and, for its ``reveal=true`` flag, on ``GET /connections/{name}/metadata``. ``GET /connections`` does not call this: it calls - :func:`_refuse_reveal`, then raises any held monitoring-read 429, then - :func:`_charge_reveal`. A caller without that permission is refused, + the parts of :func:`_refuse_reveal` itself, then raises any held monitoring-read 429, + then :func:`_charge_reveal`. A caller without that permission is refused, and the refusal is audited as ``auth.permission_denied`` like every other one (ASVS 16.3.2). Over HTTP the reveal is also a PHI read: it takes the serve-hop refusal, the new-address refusal (vault BACKLOG @@ -6815,9 +6822,14 @@ def _reveal_over_http(request: Request) -> bool: return not (_matched_route_path(request) or "").startswith("/ui/") async def _refuse_reveal(request: Request, identity: Identity) -> None: - """The refusals of :func:`_admit_reveal`, without its PHI-read charge, for a route that - must answer them before a held monitoring-read 429 (``GET /connections``).""" + """The refusals of :func:`_admit_reveal`, without its PHI-read charge. ``GET + /connections`` calls its two parts itself, to answer them before a held + monitoring-read 429.""" await _refuse_reveal_without_view_summary(request, identity) + await _refuse_reveal_phi_read(request) + + async def _refuse_reveal_phi_read(request: Request) -> None: + """The PHI-read refusals of a reveal over HTTP: the serve hop and the new address.""" if _reveal_over_http(request): enforce_phi_read_hop(request) # Vault BACKLOG #2620: a PHI read, so it refuses a new address as require_phi_read diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 2603b2356a..b75e99d38e 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1630,8 +1630,8 @@ async def refuse_from_new_address(request: Request) -> None: The step-up gates already asked this. The PHI reads and the paced writes did not, so on a first deployment a bearer token replayed from a second address would have read message bodies and started or stopped connections with no signal. Callers: :func:`require_phi_read`, - :func:`require_paced` and the HTTP reveal path in ``api/app.py`` (``_refuse_reveal``, which - ``_admit_reveal`` and ``GET /connections`` call). It gives + :func:`require_paced` and the HTTP reveal path in ``api/app.py`` + (``_refuse_reveal_phi_read``, which ``_admit_reveal`` and ``GET /connections`` reach). It gives them the step-up gates' refusal: 403 + ``X-Step-Up-Required: 1``, cleared by a ``POST /me/reauth`` from the new address, which re-anchors the session. An ``oidc`` session is sent to the IdP step-up instead (:func:`_step_up_refusal`). A first sighting writes @@ -1642,7 +1642,8 @@ async def refuse_from_new_address(request: Request) -> None: the JSON API's repeated monitoring reads, and a JSON client whose address changes behind a NAT pool, or behind a proxy not listed in ``[api].trusted_proxies``, would be refused on every one until a step-up. The web console's in-process reads go through ``require_ui`` and reach neither - gate. A monitoring ``reveal`` read does ask, through ``_refuse_reveal`` in ``api/app.py``. + gate. A monitoring ``reveal`` read does ask, through ``_refuse_reveal_phi_read`` in + ``api/app.py``. Costs one session read per request while ``[auth].admin_new_ip_step_up`` is on, and one more on a refusal, to pick its wording. The gate has @@ -2090,6 +2091,23 @@ async def raise_deferred_monitoring_refusal(request: Request) -> None: raise held.refusal +async def record_deferred_monitoring_refusal(request: Request) -> None: + """Write the ``auth.gate_refused`` row (reason ``throttled``) of a monitoring-read 429 a + :func:`require_monitoring_read` gate held for this request, and drop the held refusal, without + raising it or logging it. For a route body whose own refusal is about to propagate in place of + the held 429 and writes no denial row of its own, at least the serve-hop refusal and a + new-address refusal whose row was deduped, so the request still leaves a decision row. A no-op + where nothing is held.""" + held = getattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR, None) + if not isinstance(held, _DeferredRefusal): + return + delattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR) + decision = held.decision + await _record_gate_refusal( + request, decision.auth, decision.identity, decision.permissions, held.refusal + ) + + def _charge_monitoring_read( request: Request, auth: AuthService, identity: Identity ) -> _GateRefusal | None: diff --git a/tests/test_monitoring_read_pacing.py b/tests/test_monitoring_read_pacing.py index 0e5fd926d6..15115c1141 100644 --- a/tests/test_monitoring_read_pacing.py +++ b/tests/test_monitoring_read_pacing.py @@ -22,6 +22,7 @@ from messagefoundry.auth.identity import ALL_CHANNELS from messagefoundry.auth.service import AuthService from messagefoundry.config.settings import AuthSettings, EgressSettings +from messagefoundry.config.tls_policy import HopDisposition from messagefoundry.pipeline import Engine from messagefoundry.store.base import Row from tests._admin_account import create_local_user_chosen @@ -302,12 +303,38 @@ async def test_a_reveal_from_a_new_address_is_refused_for_it_with_the_budget_spe assert (await a.get("/status", headers=h)).status_code == 200 assert (await a.get("/status", headers=h)).status_code == 429 # the budget is spent async with _client(engine, service, ip="10.9.9.9") as b: - r = await b.get("/connections", params={"reveal": "IB_MINE"}, headers=h) - assert (r.status_code, r.headers.get("X-Step-Up-Required")) == (403, "1"), r.text + # The second request from the same, already-flagged address gets no new-address row (it + # is deduped), so the throttled row is the only record it leaves. + for _ in range(2): + r = await b.get("/connections", params={"reveal": "IB_MINE"}, headers=h) + assert (r.status_code, r.headers.get("X-Step-Up-Required")) == (403, "1"), r.text rows = await engine.store.list_audit(limit=1000) assert [d.get("seen_ip") for d in _actions(rows, "auth.new_address_reverify_required")] == [ "10.9.9.9" ] + on_path = _decisions_on(rows, "/connections") + assert [(a, d.get("reason")) for a, d in on_path] == [ + ("auth.gate_refused", "throttled"), + ("auth.gate_refused", "throttled"), + ], on_path + + +async def test_a_serve_hop_refusal_over_the_budget_writes_a_throttled_row(engine: Engine) -> None: + """The serve-hop refusal writes no row of its own, so with the budget spent the held + decision's throttled row is written before the 403 propagates, and no grant row.""" + service = await _scoped_service(engine, monitoring_read_rate_limit_per_actor=1) + app = create_app(engine, auth=service) + app.state.phi_read_hop_disposition = HopDisposition.REFUSE + transport = httpx.ASGITransport(app=app, client=("127.0.0.1", 123)) + async with httpx.AsyncClient(transport=transport, base_url="http://t") as c: + h = await _bearer(c, "op") + assert (await c.get("/status", headers=h)).status_code == 200 + refused = await c.get("/connections", params={"reveal": "IB_MINE"}, headers=h) + assert refused.status_code == 403, refused.text + assert "PHI read refused" in refused.json()["detail"] + rows = await engine.store.list_audit(limit=1000) + on_path = _decisions_on(rows, "/connections") + assert [(a, d.get("reason")) for a, d in on_path] == [("auth.gate_refused", "throttled")] async def test_an_invalid_reveal_over_the_budget_writes_a_decision_row(engine: Engine) -> None: From a2a1adda6f5375ba04e85db6e501ed97f6b47a19 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 15:59:03 -0600 Subject: [PATCH 16/19] Fix the review round's text findings on the throttled-row fix Text only. SECURITY.md and the require_monitoring_read and _recorded_decision docstrings no longer say an unraised held 429 never writes a throttled row, and name record_deferred_monitoring_refusal. The "leaves at least one row" claims now say the row follows [security].audit_all_authorization_decisions, like every gate decision row. The list_connections comment says the row is written on every hop or new-address refusal, not only a deduped one. BACKLOG #1191 --- docs/SECURITY.md | 19 +++++++++++-------- messagefoundry/api/app.py | 10 +++++----- messagefoundry/api/security.py | 20 +++++++++++--------- 3 files changed, 27 insertions(+), 22 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 98e581b47d..1f3ce19d34 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5350,8 +5350,10 @@ flowchart TB valid value is raised by the route body after at least its scope, permission, serve-hop and new-address checks; its gate wrote no grant row, and - `raise_deferred_monitoring_refusal` writes the `auth.gate_refused` row the gate would have. Other - refusals a route body makes after its gate has passed write no `auth.gate_refused` row. + `raise_deferred_monitoring_refusal` writes the `auth.gate_refused` row the gate would have. On + that route, a serve-hop or new-address refusal that comes first also writes that throttled row, + through `record_deferred_monitoring_refusal`. Other refusals a route body makes after its gate + has passed write no `auth.gate_refused` row. - Routes that act on a Connection also check the identity's connection scope. That scope starts empty for every role except Administrator. - Sensitive routes add a step-up re-check on top of this flow. See @@ -7704,14 +7706,15 @@ BACKLOG #2620). So with the budget spent those refusals still answer with their record what the pre-pacing route recorded: an `auth.channel_denied` or `auth.permission_denied` row, or the new-address refusal's deduped `auth.new_address_reverify_required` row; the serve-hop refusal writes none of its own. Unlike -that route, they then write no `monitoring:read` grant row. The serve-hop and new-address refusals -also write the held 429's `auth.gate_refused` row (reason `throttled`) before they are answered, -with no log line, so each such request still leaves a decision row. A held 429 the route never -raises, at least because one of those checks refused first, writes no throttled row or log line. A +that route, they then write no `monitoring:read` grant row. A held 429 the route never raises, +because one of those checks refused first, writes no log line. The scope and permission refusals +write no throttled row either. The serve-hop and new-address refusals do write the held 429's +`auth.gate_refused` row (reason `throttled`) before they are answered, so such a request leaves a +decision row even when the refusal writes none of its own. Like every gate decision row, it is not +written for a GET while `[security].audit_all_authorization_decisions` is off. A reveal value that will fail validation is charged and refused at the gate like any other read. The limiter records no refused attempt, so once the budget is spent a reveal those checks refuse -spends nothing more: that path is not paced. Each such refusal leaves at least one row: its -denial row, or the throttled row above. The six routes share ONE budget per account: a read of any of them spends +spends nothing more: that path is not paced. The six routes share ONE budget per account: a read of any of them spends it. The budget is in-process, per API process, so N engine shards multiply it by N (*Business-logic limits* above). diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index d9edc30319..3f735acc24 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -5727,11 +5727,11 @@ async def list_connections( # it is raised here, after this check and the reveal's own refusals (its permission, the # serve hop and the new address), and each is answered as before pacing. With the budget # spent none of them writes the monitoring:read grant row main wrote: the scope and - # permission refusals write only their denial row (owner ruling 2026-11-23). The hop and - # new-address refusals also write the held throttled row before they propagate, because - # the hop refusal writes no row of its own and a new-address row is deduped, so without - # it such a request would leave no decision row (vault BACKLOG #1191). A scoped caller's - # dashboard carries no outbound rows at all. + # permission refusals write only their denial row (owner ruling 2026-11-23). Every hop or + # new-address refusal also writes the held throttled row before it propagates, where the + # gate records decisions: the hop refusal writes no row of its own and a repeated + # new-address row is deduped, so without it such a request would leave no decision row + # (vault BACKLOG #1191). A scoped caller's dashboard carries no outbound rows at all. if reveal is not None: await _control_guard(engine, identity, reveal, client_ip(request)) await _refuse_reveal_without_view_summary(request, identity) diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index b75e99d38e..3710a4fd65 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1485,9 +1485,9 @@ async def _recorded_decision( decision rows. For the step-up refusals of :func:`spend_step_up_action` and :func:`refuse_unless_step_up_window_live`, made in a route body after its gate admitted the request, see :func:`_record_route_refusal`. For the monitoring-read 429 a gate holds for its - route body, with no grant row written, see :func:`raise_deferred_monitoring_refusal`. Other - refusals a route body makes after its gate admitted the request write no ``auth.gate_refused`` - row. The reason comes from the + route body, with no grant row written, see :func:`raise_deferred_monitoring_refusal` and + :func:`record_deferred_monitoring_refusal`. Other refusals a route body makes after its gate + admitted the request write no ``auth.gate_refused`` row. The reason comes from the :class:`_GateRefusal` the check raised. Any other exception leaves the block with no decision row from it, which is right for the :func:`_mfa_refusal` 403: it wrote its own ``auth.mfa_denied`` row where it was raised. A failed refusal-row write raises in place of the @@ -2022,9 +2022,10 @@ def require_monitoring_read( is held on the request, with no decision row yet, until the route body calls :func:`raise_deferred_monitoring_refusal` after its own checks. ``defer_value_valid``, when given, defers only a value that will pass the route's validation, so an invalid one is charged - and refused here as any other read. A held 429 the route never raises, at least because one of - its own checks refused the request first, is answered by that refusal and writes no throttled - row or line. ``GET /connections`` defers on + and refused here as any other read. A held 429 the route never raises, because one of its own + checks refused the request first, is answered by that refusal and writes no log line. It writes + its throttled row only where the route calls :func:`record_deferred_monitoring_refusal` for + that refusal. ``GET /connections`` defers on ``reveal`` (vault BACKLOG #1191); docs/SECURITY.md, *Monitoring-read pacing*, says why.""" async def dependency(request: Request) -> Identity: @@ -2095,9 +2096,10 @@ async def record_deferred_monitoring_refusal(request: Request) -> None: """Write the ``auth.gate_refused`` row (reason ``throttled``) of a monitoring-read 429 a :func:`require_monitoring_read` gate held for this request, and drop the held refusal, without raising it or logging it. For a route body whose own refusal is about to propagate in place of - the held 429 and writes no denial row of its own, at least the serve-hop refusal and a - new-address refusal whose row was deduped, so the request still leaves a decision row. A no-op - where nothing is held.""" + the held 429 and may write no denial row of its own, at least the serve-hop refusal and a + new-address refusal whose row was deduped. The row is written only where + :func:`_audited_permission` names one, as on the gate's own refusals. A no-op where nothing is + held.""" held = getattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR, None) if not isinstance(held, _DeferredRefusal): return From 957684828454b0e8a51eaa7c0ead15e2d70264d3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:06:25 -0600 Subject: [PATCH 17/19] The deferred throttled row records the 403 and the reason it answered Over budget, a GET /connections reveal refused at the serve hop or a new address writes the held 429's auth.gate_refused row (reason throttled). That row now also carries answered_status (403) and answered_reason (serve_hop, or the new-address refusal's step_up), so it no longer reads as a request answered 429. Row counts are unchanged. audit_gate_refused takes the two optional fields; record_deferred_monitoring_refusal takes the refusal it stands beside. The recording moves into _refuse_reveal_phi_read, a no-op where nothing is held, so GET /connections calls _refuse_reveal again. BACKLOG #1191 --- docs/SECURITY.md | 4 ++- messagefoundry/api/app.py | 51 ++++++++++++++++------------ messagefoundry/api/security.py | 29 ++++++++++++---- messagefoundry/auth/service.py | 15 +++++++- tests/test_monitoring_read_pacing.py | 13 ++++--- 5 files changed, 79 insertions(+), 33 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 1f3ce19d34..0811f194c8 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7710,7 +7710,9 @@ that route, they then write no `monitoring:read` grant row. A held 429 the route because one of those checks refused first, writes no log line. The scope and permission refusals write no throttled row either. The serve-hop and new-address refusals do write the held 429's `auth.gate_refused` row (reason `throttled`) before they are answered, so such a request leaves a -decision row even when the refusal writes none of its own. Like every gate decision row, it is not +decision row even when the refusal writes none of its own. That row also records what the caller +was answered: `answered_status` (403) and `answered_reason` (`serve_hop`, or the new-address +refusal's `step_up`). Like every gate decision row, it is not written for a GET while `[security].audit_all_authorization_decisions` is off. A reveal value that will fail validation is charged and refused at the gate like any other read. The limiter records no refused attempt, so once the budget is spent a reveal those checks refuse diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 3f735acc24..d13da55bc5 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -5728,18 +5728,14 @@ async def list_connections( # serve hop and the new address), and each is answered as before pacing. With the budget # spent none of them writes the monitoring:read grant row main wrote: the scope and # permission refusals write only their denial row (owner ruling 2026-11-23). Every hop or - # new-address refusal also writes the held throttled row before it propagates, where the - # gate records decisions: the hop refusal writes no row of its own and a repeated - # new-address row is deduped, so without it such a request would leave no decision row - # (vault BACKLOG #1191). A scoped caller's dashboard carries no outbound rows at all. + # new-address refusal also writes the held throttled row, naming the 403 and the reason it + # answered with, before it propagates, where the gate records decisions: the hop refusal + # writes no row of its own and a repeated new-address row is deduped, so without it such + # a request would leave no decision row (vault BACKLOG #1191). A scoped caller's dashboard + # carries no outbound rows at all. if reveal is not None: await _control_guard(engine, identity, reveal, client_ip(request)) - await _refuse_reveal_without_view_summary(request, identity) - try: - await _refuse_reveal_phi_read(request) - except HTTPException: - await record_deferred_monitoring_refusal(request) - raise + await _refuse_reveal(request, identity) await raise_deferred_monitoring_refusal(request) if reveal is not None: _charge_reveal(request, identity) @@ -5798,8 +5794,8 @@ async def _dashboard_rows( ) -> list[ConnectionRow]: """The dashboard rows, channel-scoped, with ``error`` gated and masked on every row and lifted on the rows of the ONE connection ``reveal`` names (BACKLOG #2443). The caller has - already passed the refusals of :func:`_refuse_reveal` and :func:`_charge_reveal` for any - ``reveal``; the stats socket passes none.""" + already passed :func:`_refuse_reveal` and :func:`_charge_reveal` for any ``reveal``; the + stats socket passes none.""" rows = await _connection_rows(engine, identity) if reveal is None: # the stats socket, every second, and every bare load return [redact_unauthorized(r, identity) for r in rows] @@ -6802,8 +6798,8 @@ async def _admit_reveal(request: Request, identity: Identity, reveal: int | str ``messages:view_summary`` data (BACKLOG #2443). ``reveal`` is an event or alert id, or a connection name on ``GET /connections`` and, for its ``reveal=true`` flag, on ``GET /connections/{name}/metadata``. ``GET /connections`` does not call this: it calls - the parts of :func:`_refuse_reveal` itself, then raises any held monitoring-read 429, - then :func:`_charge_reveal`. A caller without that permission is refused, + :func:`_refuse_reveal`, then raises any held monitoring-read 429, then + :func:`_charge_reveal`. A caller without that permission is refused, and the refusal is audited as ``auth.permission_denied`` like every other one (ASVS 16.3.2). Over HTTP the reveal is also a PHI read: it takes the serve-hop refusal, the new-address refusal (vault BACKLOG @@ -6822,19 +6818,32 @@ def _reveal_over_http(request: Request) -> bool: return not (_matched_route_path(request) or "").startswith("/ui/") async def _refuse_reveal(request: Request, identity: Identity) -> None: - """The refusals of :func:`_admit_reveal`, without its PHI-read charge. ``GET - /connections`` calls its two parts itself, to answer them before a held - monitoring-read 429.""" + """The refusals of :func:`_admit_reveal`, without its PHI-read charge, so ``GET + /connections`` can answer them before a held monitoring-read 429.""" await _refuse_reveal_without_view_summary(request, identity) await _refuse_reveal_phi_read(request) async def _refuse_reveal_phi_read(request: Request) -> None: - """The PHI-read refusals of a reveal over HTTP: the serve hop and the new address.""" - if _reveal_over_http(request): + """The PHI-read refusals of a reveal over HTTP: the serve hop and the new address. + + Where a monitoring-read 429 is held for the request (``GET /connections``), each refusal + writes that held decision's throttled row, recording the 403 it answers and its own + reason, before it propagates (:func:`record_deferred_monitoring_refusal`); elsewhere + that call is a no-op.""" + if not _reveal_over_http(request): + return + try: enforce_phi_read_hop(request) - # Vault BACKLOG #2620: a PHI read, so it refuses a new address as require_phi_read - # does, before the budget. The /ui twins asked in require_ui's phi=True arm. + except HTTPException as refused: + await record_deferred_monitoring_refusal(request, refused, answered_reason="serve_hop") + raise + # Vault BACKLOG #2620: a PHI read, so it refuses a new address as require_phi_read + # does, before the budget. The /ui twins asked in require_ui's phi=True arm. + try: await refuse_from_new_address(request) + except HTTPException as refused: + await record_deferred_monitoring_refusal(request, refused) + raise def _charge_reveal(request: Request, identity: Identity) -> None: """The PHI-read charge of :func:`_admit_reveal`, run after :func:`_refuse_reveal`.""" diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 3710a4fd65..0aff4cee90 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -2092,12 +2092,18 @@ async def raise_deferred_monitoring_refusal(request: Request) -> None: raise held.refusal -async def record_deferred_monitoring_refusal(request: Request) -> None: +async def record_deferred_monitoring_refusal( + request: Request, answered: HTTPException, *, answered_reason: str | None = None +) -> None: """Write the ``auth.gate_refused`` row (reason ``throttled``) of a monitoring-read 429 a :func:`require_monitoring_read` gate held for this request, and drop the held refusal, without - raising it or logging it. For a route body whose own refusal is about to propagate in place of - the held 429 and may write no denial row of its own, at least the serve-hop refusal and a - new-address refusal whose row was deduped. The row is written only where + raising it or logging it. For a route body whose own refusal ``answered`` is about to + propagate in place of the held 429 and may write no denial row of its own, at least the + serve-hop refusal and a new-address refusal whose row was deduped. + + The row keeps the throttle fact and also records what the caller was answered: + ``answered_status`` is ``answered``'s status, and ``answered_reason`` is ``answered_reason`` + where given, else the reason a :class:`_GateRefusal` carries. It is written only where :func:`_audited_permission` names one, as on the gate's own refusals. A no-op where nothing is held.""" held = getattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR, None) @@ -2105,8 +2111,19 @@ async def record_deferred_monitoring_refusal(request: Request) -> None: return delattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR) decision = held.decision - await _record_gate_refusal( - request, decision.auth, decision.identity, decision.permissions, held.refusal + audited = _audited_permission(request, decision.permissions) + if audited is None: + return + if answered_reason is None and isinstance(answered, _GateRefusal): + answered_reason = answered.reason + await decision.auth.audit_gate_refused( + decision.identity, + audited, + request.url.path, + reason=held.refusal.reason, + client=client_ip(request), + answered_status=answered.status_code, + answered_reason=answered_reason, ) diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index c75779e254..7107b10dbd 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -22158,11 +22158,17 @@ async def audit_gate_refused( *, reason: str, client: str | None, + answered_status: int | None = None, + answered_reason: str | None = None, ) -> None: """Audit a request refused by a check its gate makes AFTER the permission check passed (BACKLOG #1197, ASVS 16.3.2), such as a stale step-up (``reason`` ``step_up``) or the per-actor pacing (``throttled``). + ``answered_status`` and ``answered_reason``, when given, record a different refusal the + caller was actually answered with, as when a held monitoring-read 429 is recorded but a + route's own refusal is returned in its place (vault BACKLOG #1191). + The caller holds ``permission``, so this is not :meth:`audit_permission_denied`: that row says the permission was missing, and the denial-burst detector counts it. ``_recorded_decision`` in ``api/security.py`` decides when this row is written for a gate's @@ -22171,7 +22177,14 @@ async def audit_gate_refused( await self._audit( "auth.gate_refused", actor=identity.username, - detail=_json({"permission": permission.value, "path": path, "reason": reason}), + detail=_json( + {"permission": permission.value, "path": path, "reason": reason} + | ( + {} + if answered_status is None + else {"answered_status": answered_status, "answered_reason": answered_reason} + ) + ), client=client, ) diff --git a/tests/test_monitoring_read_pacing.py b/tests/test_monitoring_read_pacing.py index 15115c1141..27cf1865c5 100644 --- a/tests/test_monitoring_read_pacing.py +++ b/tests/test_monitoring_read_pacing.py @@ -313,9 +313,12 @@ async def test_a_reveal_from_a_new_address_is_refused_for_it_with_the_budget_spe "10.9.9.9" ] on_path = _decisions_on(rows, "/connections") - assert [(a, d.get("reason")) for a, d in on_path] == [ - ("auth.gate_refused", "throttled"), - ("auth.gate_refused", "throttled"), + # Each row keeps the throttle fact, and records what the caller was actually answered. + assert [ + (a, d.get("reason"), d.get("answered_status"), d.get("answered_reason")) for a, d in on_path + ] == [ + ("auth.gate_refused", "throttled", 403, "step_up"), + ("auth.gate_refused", "throttled", 403, "step_up"), ], on_path @@ -334,7 +337,9 @@ async def test_a_serve_hop_refusal_over_the_budget_writes_a_throttled_row(engine assert "PHI read refused" in refused.json()["detail"] rows = await engine.store.list_audit(limit=1000) on_path = _decisions_on(rows, "/connections") - assert [(a, d.get("reason")) for a, d in on_path] == [("auth.gate_refused", "throttled")] + assert [ + (a, d.get("reason"), d.get("answered_status"), d.get("answered_reason")) for a, d in on_path + ] == [("auth.gate_refused", "throttled", 403, "serve_hop")], on_path async def test_an_invalid_reveal_over_the_budget_writes_a_decision_row(engine: Engine) -> None: From 2786d8b40c428a0999b1a98b6c1bdf6672f019ab Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:17:08 -0600 Subject: [PATCH 18/19] Fix the review round's text findings on the answered-status row Text only. record_deferred_monitoring_refusal's docstring says the row follows [security].audit_all_authorization_decisions, that answered_reason may be null, and that a failed write raises in place of the refusal; the other places point at it rather than restate it. audit_gate_refused lists its writers with "at least" and says how the two answered fields are keyed. SECURITY.md says step_up there means the new-address refusal. BACKLOG #1191 --- docs/SECURITY.md | 6 ++++-- messagefoundry/api/app.py | 16 +++++++--------- messagefoundry/api/security.py | 7 ++++--- messagefoundry/auth/service.py | 15 +++++++++------ 4 files changed, 24 insertions(+), 20 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 0811f194c8..e4b25e0ed9 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7711,8 +7711,10 @@ because one of those checks refused first, writes no log line. The scope and per write no throttled row either. The serve-hop and new-address refusals do write the held 429's `auth.gate_refused` row (reason `throttled`) before they are answered, so such a request leaves a decision row even when the refusal writes none of its own. That row also records what the caller -was answered: `answered_status` (403) and `answered_reason` (`serve_hop`, or the new-address -refusal's `step_up`). Like every gate decision row, it is not +was answered, as `answered_status` and `answered_reason`: for those two refusals, 403 with +`serve_hop`, or 403 with `step_up`, which on this route is the new-address refusal and not a stale +step-up window. `record_deferred_monitoring_refusal` in `messagefoundry/api/security.py` says how +the fields are filled. Like every gate decision row, it is not written for a GET while `[security].audit_all_authorization_decisions` is off. A reveal value that will fail validation is charged and refused at the gate like any other read. The limiter records no refused attempt, so once the budget is spent a reveal those checks refuse diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index d13da55bc5..56138c1dbe 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -5727,12 +5727,11 @@ async def list_connections( # it is raised here, after this check and the reveal's own refusals (its permission, the # serve hop and the new address), and each is answered as before pacing. With the budget # spent none of them writes the monitoring:read grant row main wrote: the scope and - # permission refusals write only their denial row (owner ruling 2026-11-23). Every hop or - # new-address refusal also writes the held throttled row, naming the 403 and the reason it - # answered with, before it propagates, where the gate records decisions: the hop refusal - # writes no row of its own and a repeated new-address row is deduped, so without it such - # a request would leave no decision row (vault BACKLOG #1191). A scoped caller's dashboard - # carries no outbound rows at all. + # permission refusals write only their denial row (owner ruling 2026-11-23). The hop and + # new-address refusals also record the held decision, through _refuse_reveal_phi_read, + # because the hop refusal writes no row of its own and a repeated new-address row is + # deduped (vault BACKLOG #1191). A scoped caller's dashboard carries no outbound rows at + # all. if reveal is not None: await _control_guard(engine, identity, reveal, client_ip(request)) await _refuse_reveal(request, identity) @@ -6827,9 +6826,8 @@ async def _refuse_reveal_phi_read(request: Request) -> None: """The PHI-read refusals of a reveal over HTTP: the serve hop and the new address. Where a monitoring-read 429 is held for the request (``GET /connections``), each refusal - writes that held decision's throttled row, recording the 403 it answers and its own - reason, before it propagates (:func:`record_deferred_monitoring_refusal`); elsewhere - that call is a no-op.""" + calls :func:`record_deferred_monitoring_refusal` before it propagates; that function says + what it records and when. Elsewhere the call is a no-op.""" if not _reveal_over_http(request): return try: diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 0aff4cee90..e49d2ea4d7 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -2103,9 +2103,10 @@ async def record_deferred_monitoring_refusal( The row keeps the throttle fact and also records what the caller was answered: ``answered_status`` is ``answered``'s status, and ``answered_reason`` is ``answered_reason`` - where given, else the reason a :class:`_GateRefusal` carries. It is written only where - :func:`_audited_permission` names one, as on the gate's own refusals. A no-op where nothing is - held.""" + where given, else the reason a :class:`_GateRefusal` carries, else null. It is written only + where :func:`_audited_permission` names one, as on the gate's own refusals, so with + ``[security].audit_all_authorization_decisions`` off no row is written for a GET. A failed + write raises in place of ``answered``. A no-op where nothing is held.""" held = getattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR, None) if not isinstance(held, _DeferredRefusal): return diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 7107b10dbd..8446b90204 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -22165,15 +22165,18 @@ async def audit_gate_refused( (BACKLOG #1197, ASVS 16.3.2), such as a stale step-up (``reason`` ``step_up``) or the per-actor pacing (``throttled``). - ``answered_status`` and ``answered_reason``, when given, record a different refusal the - caller was actually answered with, as when a held monitoring-read 429 is recorded but a - route's own refusal is returned in its place (vault BACKLOG #1191). + Where ``answered_status`` is given, the row also records it and ``answered_reason`` (null + if that is not given): a different refusal the caller was actually answered with, as when + a held monitoring-read 429 is recorded but a route's own refusal is returned in its place + (vault BACKLOG #1191). Without ``answered_status``, ``answered_reason`` is not recorded. The caller holds ``permission``, so this is not :meth:`audit_permission_denied`: that row says the permission was missing, and the denial-burst detector counts it. - ``_recorded_decision`` in ``api/security.py`` decides when this row is written for a gate's - own refusals, and ``_record_route_refusal`` for the step-up refusals a ``proof_in_route`` - route body makes. ``client`` is required, as for :meth:`audit_self_target_refused`.""" + Its writers in ``api/security.py`` include at least ``_recorded_decision`` for a gate's own + refusals, ``_record_route_refusal`` for the step-up refusals a ``proof_in_route`` route + body makes, and ``raise_deferred_monitoring_refusal`` and + ``record_deferred_monitoring_refusal`` for a monitoring-read 429 a gate held for its + route body. ``client`` is required, as for :meth:`audit_self_target_refused`.""" await self._audit( "auth.gate_refused", actor=identity.username, From a452e58f8fc773fe5951ea8a9836eab35ae9a58e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 11:52:24 -0600 Subject: [PATCH 19/19] Answer the restated hold on PR 3167: restore "at least", scope the row claim to HTTP refusals Text only. docs/SECURITY.md, Monitoring-read pacing, and the require_monitoring_read docstring in messagefoundry/api/security.py again say a held 429 goes unraised "at least" because a check refused first, since a store fault or a cancelled request also leaves it unraised. SECURITY.md now scopes the decision-row claim to the serve-hop and new-address refusals answering with an HTTP refusal, and says any other exception those checks raise, such as a store fault, writes no throttled row. No behaviour change; the owner-accepted denial-row-only behaviour of 2026-11-23 is unchanged. BACKLOG #1191 --- docs/SECURITY.md | 11 ++++++----- messagefoundry/api/security.py | 8 ++++---- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index ef4f308e47..e3d16fdecd 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7718,11 +7718,12 @@ record what the pre-pacing route recorded: an `auth.channel_denied` or `auth.per row, or the new-address refusal's deduped `auth.new_address_reverify_required` row; the serve-hop refusal writes none of its own. Unlike that route, they then write no `monitoring:read` grant row. A held 429 the route never raises, -because one of those checks refused first, writes no log line. The scope and permission refusals -write no throttled row either. The serve-hop and new-address refusals do write the held 429's -`auth.gate_refused` row (reason `throttled`) before they are answered, so such a request leaves a -decision row even when the refusal writes none of its own. That row also records what the caller -was answered, as `answered_status` and `answered_reason`: for those two refusals, 403 with +at least because one of those checks refused first, writes no log line. The scope and permission +refusals write no throttled row either. When the serve-hop or new-address refusal answers with an +HTTP refusal, it writes the held 429's `auth.gate_refused` row (reason `throttled`) before that +refusal is answered, so such a request leaves a decision row even when the refusal writes none of +its own. Any other exception those checks raise, such as a store fault, writes no throttled row. +That row, where written, also records what the caller was answered, as `answered_status` and `answered_reason`: for those two refusals, 403 with `serve_hop`, or 403 with `step_up`, which on this route is the new-address refusal and not a stale step-up window. `record_deferred_monitoring_refusal` in `messagefoundry/api/security.py` says how the fields are filled. Like every gate decision row, it is not diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index e49d2ea4d7..c4ac54f3d4 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -2022,10 +2022,10 @@ def require_monitoring_read( is held on the request, with no decision row yet, until the route body calls :func:`raise_deferred_monitoring_refusal` after its own checks. ``defer_value_valid``, when given, defers only a value that will pass the route's validation, so an invalid one is charged - and refused here as any other read. A held 429 the route never raises, because one of its own - checks refused the request first, is answered by that refusal and writes no log line. It writes - its throttled row only where the route calls :func:`record_deferred_monitoring_refusal` for - that refusal. ``GET /connections`` defers on + and refused here as any other read. A held 429 the route never raises, at least because one of + its own checks refused the request first, writes no log line. Where a check refused it, that + refusal answers the request, and the throttled row is written only where the route calls + :func:`record_deferred_monitoring_refusal` for that refusal. ``GET /connections`` defers on ``reveal`` (vault BACKLOG #1191); docs/SECURITY.md, *Monitoring-read pacing*, says why.""" async def dependency(request: Request) -> Identity: