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..24a9cdeebd --- /dev/null +++ b/changelog.d/1191-monitoring-read-pace.security.md @@ -0,0 +1,8 @@ +- **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 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/CONFIGURATION.md b/docs/CONFIGURATION.md index 5a4db31b9c..1439021127 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -830,6 +830,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 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` | | `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 | @@ -840,7 +844,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-LOOSENING.md b/docs/SECURITY-LOOSENING.md index 3a39767cc8..365d7dfbf4 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,27 @@ 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 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, 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 + `[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 7bec8504a5..e3d16fdecd 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`) | @@ -1768,17 +1769,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` | @@ -4708,7 +4709,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 @@ -5029,7 +5031,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 (at least a marker it refuses, a key under 160 bits, BACKLOG #5340, or no secret; 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` | @@ -5048,6 +5050,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` | @@ -5349,8 +5352,15 @@ 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 with a + 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. 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 @@ -7586,8 +7596,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 @@ -7608,6 +7618,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` 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 | @@ -7625,9 +7636,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` (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 @@ -7636,11 +7649,11 @@ 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 -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 @@ -7688,6 +7701,92 @@ 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). `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 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` with a valid `reveal` value, a +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 of its own. 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 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 +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. 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 +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 +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 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 + (`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. 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. +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` 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 +`/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. + +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/harness/load/failover.py b/harness/load/failover.py index 78eab9c821..50f0a3dfba 100644 --- a/harness/load/failover.py +++ b/harness/load/failover.py @@ -183,6 +183,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/api/app.py b/messagefoundry/api/app.py index b4bff70fae..563efaaf2c 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.requests import ClientDisconnect from starlette.types import ASGIApp, Message, Receive, Scope, Send @@ -269,11 +269,14 @@ pending_credential_deadline, public_route, quiet_deliberate_export_stops, + raise_deferred_monitoring_refusal, recheck_standing, recheck_standing_or_refusal, + record_deferred_monitoring_refusal, refuse_from_new_address, refuse_undeclared_route, require, + require_monitoring_read, require_paced, require_phi_read, require_service_cert, @@ -619,6 +622,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 @@ -5798,7 +5817,13 @@ 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, + 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. reveal: Annotated[ConnectionName | None, Query()] = None, @@ -5816,10 +5841,21 @@ 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 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), 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 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 _admit_reveal(request, identity, reveal) + await _refuse_reveal(request, identity) + await raise_deferred_monitoring_refusal(request) + 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 @@ -5875,7 +5911,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] @@ -6856,6 +6893,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. @@ -6863,7 +6914,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 @@ -6873,21 +6926,44 @@ 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") - if not (_matched_route_path(request) or "").startswith("/ui/"): + 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, 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. + + Where a monitoring-read 429 is held for the request (``GET /connections``), each refusal + 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: 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`.""" + if _reveal_over_http(request): enforce_phi_read_pacing(request, identity) async def _redact_reasons( @@ -10509,7 +10585,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). @@ -10547,7 +10623,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 @@ -10557,7 +10633,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 @@ -10577,7 +10653,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 → @@ -10842,7 +10918,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..c4ac54f3d4 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1484,7 +1484,9 @@ 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 + 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` 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 @@ -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 @@ -1627,15 +1630,20 @@ 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_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 ``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 - operator whose address changes behind a NAT pool would be refused on every one until a step-up. + It is NOT in :func:`require` or :func:`require_monitoring_read`, deliberately: those gates carry + 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_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 @@ -1986,6 +1994,175 @@ async def dependency(request: Request) -> Identity: return _gate(dependency, before_body) +def require_monitoring_read( + *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 + 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``. 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, 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), + 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 + embedding/no-auth path (there is no per-actor identity to key on). + + ``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 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, 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: + auth, identity = await _admit(request, permissions, mfa_gate=True) + if auth is None: + return identity + 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) + 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) + + +@dataclass(frozen=True) +class _DeferredRefusal: + """A refusal a gate decided at admission and left for its route body to raise.""" + + decision: _AdmittedDecision + refusal: _GateRefusal + + +#: 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, + 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, 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 + 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 + + +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 ``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, 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 + delattr(request.state, _DEFERRED_MONITORING_REFUSAL_ATTR) + decision = held.decision + 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, + ) + + +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. 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 + 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 _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, 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 + + 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 692c4e0fc4..f652721354 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -4411,6 +4411,18 @@ def __init__( if settings.phi_read_rate_limit_enabled else None ) + # 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 = ( + 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 @@ -4908,6 +4920,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 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 + 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). @@ -17096,8 +17120,10 @@ 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 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. @@ -22436,20 +22462,36 @@ 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``). + 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, - 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/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index a32b989ade..3e964a8c72 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -4060,6 +4060,19 @@ class AuthSettings(_Section): default=60.0, allow_inf_nan=False, le=_RATE_WINDOW_MAX_SECONDS ) + # 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 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 @@ -9574,7 +9587,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 @@ -9585,11 +9599,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 (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. @@ -9895,6 +9911,41 @@ def _window( ), ) + # --- the monitoring-read limiter (vault BACKLOG #1191, ASVS 15.2.2): per actor, on the six + # 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 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( + "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 paced 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 through the six JSON routes 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/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" diff --git a/tests/test_derived_gate_decision_audit.py b/tests/test_derived_gate_decision_audit.py index e99abd1580..129d845e57 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( @@ -295,12 +300,15 @@ 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", "enforce_phi_read_pacing", + "enforce_monitoring_read_pacing", "refuse_from_new_address", "_step_up_refusal", "_mfa_refusal", @@ -320,8 +328,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 six 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 @@ -333,7 +343,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 5a9f28f2ef..7d1b55f1e7 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..27cf1865c5 --- /dev/null +++ b/tests/test_monitoring_read_pacing.py @@ -0,0 +1,414 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""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, +*Monitoring-read pacing*. +""" + +from __future__ import annotations + +import json +from collections.abc import AsyncIterator, Sequence +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.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 + +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, *, 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=(ip, 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 + + +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") + + +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: + """``vw`` (Viewer) and ``op`` (Operator, so it holds ``messages:view_summary``), each scoped + to ``IB_MINE``.""" + service = await _service(engine, **overrides) + 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: + """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, "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) + assert denied.status_code == 403, denied.text + 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) + assert any("IB_THEIRS" in json.dumps(d) for d in _actions(rows, "auth.channel_denied")) + on_path = _decisions_on(rows, "/connections") + # 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_reveal_without_view_summary_is_denied_with_the_budget_spent( + engine: Engine, +) -> None: + """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: + 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_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: + # 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") + # 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 + + +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"), 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: + """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 + 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") + 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. + 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") + 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 + + +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. + 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: + """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) + 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"}, + ) + # 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, + # ``/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 + # 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 diff --git a/tests/test_security_doc_drift.py b/tests/test_security_doc_drift.py index f47ee410a0..b9f0f2956e 100644 --- a/tests/test_security_doc_drift.py +++ b/tests/test_security_doc_drift.py @@ -683,8 +683,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 @@ -1384,6 +1385,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", @@ -2319,9 +2321,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", }