Skip to main content

areev_server/
lib.rs

1//! areev-server — the opt-in thin HTTP surface and
2//! the local test console (`areev ui`).
3//!
4//! Deliberately minimal: std-only HTTP/1.1 on 127.0.0.1, one request per
5//! connection, JSON API + one embedded HTML page. This is a *local
6//! inspection console*, not a service — no auth, binds loopback only.
7
8use std::io::{BufRead, BufReader, Read, Write};
9use std::net::{TcpListener, TcpStream};
10use std::time::Duration;
11
12use areev_cal::{CalExecutor, CalExecutorConfig, CalStoreFacade, AreevFacade};
13use areev_loop_adapter::{now_ms, BorrowedSubstrate};
14use serde_json::{json, Value};
15use areev_loop::{Decision, Engine, RecStatus, RunOptions};
16
17/// Native OIDC (A3) — the second recorded dependency-policy exception, behind
18/// the non-default `oidc` feature. See the module docs for why a proxy
19/// cannot cover the case this exists for.
20#[cfg(feature = "oidc")]
21pub mod oidc;
22
23const CONSOLE_HTML: &str = include_str!("console.html");
24
25/// Per-connection read/write timeout — bounds slow-client (slowloris) attacks.
26const READ_TIMEOUT_SECS: u64 = 15;
27/// Hard ceiling on bytes read from one connection (1 MiB body cap + headroom
28/// for the request line and headers). Bounds memory against oversized requests.
29const MAX_CONN_BYTES: u64 = (1 << 20) + (128 << 10);
30/// Cap on total header bytes and header count per request.
31const MAX_HEADER_BYTES: usize = 64 * 1024;
32const MAX_HEADERS: usize = 100;
33/// Total wall-clock deadline for reading + handling one request. A per-read
34/// timeout cannot bound a slow-drip client (each byte resets it), so a watchdog
35/// shuts the socket down at this deadline.
36const REQUEST_DEADLINE_SECS: u64 = 30;
37/// Issue #126: an auth-failure streak from one source IP idle longer than
38/// this is treated as reset rather than accumulated against forever.
39const AUTH_FAILURE_IDLE_SECS: u64 = 15 * 60;
40/// Cap on distinct source IPs tracked for auth-failure throttling — the key
41/// space is attacker-controlled, so this bounds the memory an attacker can
42/// force the map to hold.
43const MAX_AUTH_FAILURE_IPS: usize = 4096;
44/// Longest accepted proxy-asserted identity. Principals are names, not
45/// documents; anything longer is a malformed or hostile header, and the
46/// string ends up in audit grains that replicate.
47const MAX_SSO_IDENTITY_BYTES: usize = 128;
48/// Principal names an SSO header may never assert.
49///
50/// `anonymous` is the restricted baseline and `user:console` is the owner
51/// default the per-request binding restores on drop — an identity header
52/// naming either would make audit records ambiguous between "a person the
53/// proxy vouched for" and "the console's own unauthenticated floor/ceiling".
54/// Neither is currently an escalation (`bind_principal` always builds a
55/// *restricted* set from the file's grants), but a name that reads as a
56/// system principal in an immutable, replicating audit trail is a defect
57/// whether or not it is exploitable today.
58const RESERVED_PRINCIPALS: [&str; 2] = ["anonymous", "user:console"];
59
60/// Consecutive failed authentications from one source IP after which further
61/// credential-bearing requests are refused with `429` until the streak goes
62/// idle (`AUTH_FAILURE_IDLE_SECS`).
63///
64/// Set high enough that a human fat-fingering a pasted token a few times is
65/// never locked out, and low enough that an online guessing attack gets a few
66/// attempts per quarter-hour instead of thousands per second. It is a brake
67/// on rate, not a replacement for token entropy — which is why `areev auth
68/// mint` (256-bit tokens) is the real control and this is the backstop.
69const MAX_CONSECUTIVE_AUTH_FAILURES: u32 = 10;
70
71
72/// One accepted connection: plaintext, or TLS when the server was built
73/// with the `tls` feature and configured with a certificate. The raw
74/// socket handle stays available for timeouts and the watchdog shutdown;
75/// all request/response bytes flow through this wrapper. A plaintext
76/// client hitting a TLS listener fails the handshake — there is no
77/// downgrade path by construction.
78enum Conn {
79    Plain(TcpStream),
80    #[cfg(feature = "tls")]
81    Tls(Box<rustls::StreamOwned<rustls::ServerConnection, TcpStream>>),
82}
83
84impl Read for Conn {
85    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
86        match self {
87            Conn::Plain(s) => s.read(buf),
88            #[cfg(feature = "tls")]
89            Conn::Tls(s) => s.read(buf),
90        }
91    }
92}
93
94impl Write for Conn {
95    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
96        match self {
97            Conn::Plain(s) => s.write(buf),
98            #[cfg(feature = "tls")]
99            Conn::Tls(s) => s.write(buf),
100        }
101    }
102    fn flush(&mut self) -> std::io::Result<()> {
103        match self {
104            Conn::Plain(s) => s.flush(),
105            #[cfg(feature = "tls")]
106            Conn::Tls(s) => s.flush(),
107        }
108    }
109}
110
111pub struct UiServer {
112    facade: std::sync::Arc<AreevFacade>,
113    executor: CalExecutor,
114    db_label: String,
115    /// `db_label`, redacted for DISPLAY (issue #124): every response body,
116    /// the served HTML, and any startup log line must use this, never the
117    /// raw label — on the Postgres backend `db_label` is a DSN with an
118    /// inline password. Computed once in `UiServer::new` via `redact_dsn`.
119    /// The raw `db_label` is kept only for the `resolve_for_memory` call
120    /// sites below, which must keep comparing against the exact `--db`
121    /// value a credential map's `memories` entry is written as.
122    db_label_display: String,
123    /// Shared secret required for access when set. It guards mutating
124    /// endpoints (`Bearer`); in console-auth mode (`auth_all`) it guards
125    /// every request via `Bearer` **or** HTTP `Basic` (password = token).
126    token: Option<String>,
127    /// When true, *every* request requires the token — the console page, all
128    /// reads, and all writes — and a `401` carries `WWW-Authenticate: Basic` so
129    /// browsers prompt. Set by [`UiServer::with_auth`].
130    auth_all: bool,
131    /// When false (the default), reject any request whose `Host` header is not
132    /// loopback — the standard DNS-rebinding defense for a localhost service.
133    /// Set true only when the operator intentionally serves to other hosts
134    /// (CLI `--allow-remote`), where a non-loopback `Host` is expected.
135    allow_remote: bool,
136    /// Origins (issue #125), normalized, whose cross-origin **POST**s are
137    /// accepted even though they are not loopback. The Origin drive-by
138    /// check is NOT lifted by `allow_remote` — HTTP Basic is browser-cached
139    /// and re-attached cross-site, so Origin is the only thing telling the
140    /// console's own page apart from an attacker's page riding a viewer's
141    /// cached credential. This is the exact-match allowlist an operator
142    /// populates instead (CLI `--allow-origin`), one entry per
143    /// [`allow_origin`](Self::allow_origin) call. No wildcards, no
144    /// suffix/subdomain matching.
145    allowed_origins: Vec<String>,
146    /// Host loop policy (§6.2) applied to the `/api/loop/*` engine — the
147    /// same `loop-policy.json` the CLI takes (`areev ui --policy`). Absent →
148    /// the closed default: nothing auto-applies, nothing is denied. Host
149    /// config, never persisted in the memory file.
150    loop_policy: Option<areev_loop::Policy>,
151    /// Multi-principal mode (`areev ui --auth areev-auth.json`): a credential
152    /// map resolving bearer/Basic tokens to principal names. Rights come
153    /// from the FILE's own grant grains — the map holds no policy and no
154    /// raw secrets. Unauthenticated requests run as `anonymous`
155    /// (read-only unless the file grants more). It changes *who* a request
156    /// is, never *whether* the shared `--token-env` secret is required: when
157    /// both are configured the secret keeps its contract (implied admin, and
158    /// still demanded on the requests it guards).
159    credentials: Option<areev_core::authz::CredentialMap>,
160    /// Whether destructive CAL is permitted, kept alongside the executor so
161    /// every builder can rebuild it without clobbering the others' settings.
162    allow_destructive_ops: bool,
163    /// Native TLS (the recorded dependency exception; `tls` cargo feature).
164    /// None = plaintext — the documented default is a TLS-terminating proxy.
165    #[cfg(feature = "tls")]
166    tls_config: Option<std::sync::Arc<rustls::ServerConfig>>,
167    /// SSO v0 — trusted-header auth (`areev ui --sso-header X-Forwarded-User
168    /// --sso-secret-env VAR`): an authenticating proxy does OIDC/SAML and
169    /// forwards the identity in this header. Honored ONLY when the request
170    /// also carries the proxy shared secret in `x-areev-proxy-secret` —
171    /// otherwise identity headers are attacker-controlled input and are
172    /// ignored entirely. Rights still come from the FILE's grant grains.
173    sso_header: Option<String>,
174    /// The proxy shared secrets this instance accepts, newest first.
175    ///
176    /// A list rather than a value so the secret can be **rotated without a
177    /// zero-overlap cutover** (#79). It is an impersonation-grade credential:
178    /// whoever holds it can present any identity header, approval-capable
179    /// principals included. Rotating one of those atomically across a proxy
180    /// fleet and a console is not achievable in practice, so the honest
181    /// choices were a brief outage or a window where the wrong secret is live
182    /// — and an operator facing either under suspected-compromise pressure
183    /// will defer the rotation, which is the outcome that actually costs.
184    ///
185    /// Two at a time, deliberately: enough for old-and-new, not enough to
186    /// accumulate a drawer of forgotten live credentials. Both are checked in
187    /// constant time and the comparison never short-circuits on the first
188    /// mismatch, so timing cannot reveal which one matched or how many are
189    /// configured.
190    sso_secrets: Vec<String>,
191    /// Optional groups header (A2, `--sso-groups-header X-Forwarded-Groups`):
192    /// a comma-separated list of IdP groups, honored under the same proxy
193    /// secret as `sso_header`. Resolved through the credential map's `groups`
194    /// table, and only when the asserted identity has no grants of its own —
195    /// see `resolve_sso_principal` for the precedence and why.
196    sso_groups_header: Option<String>,
197    /// Prefix stamped onto every proxy-asserted principal
198    /// (`--sso-principal-prefix`). Lets an operator keep IdP-sourced
199    /// identities visibly distinct from credential-map ones in grant grains
200    /// and audit records, so `GRANT` can target one population without
201    /// depending on IdP naming conventions never colliding with local ones.
202    sso_principal_prefix: Option<String>,
203    /// Native OIDC (A3, `oidc` feature). When configured, the console serves
204    /// its own login: `/auth/login` → the IdP → `/auth/callback` → an
205    /// `HttpOnly` session cookie. Unlike the trusted-header path, the
206    /// identity is proven by a signature over an issuer-published key set,
207    /// which is why an OIDC principal MAY approve by default — that
208    /// difference is the entire reason the feature exists.
209    #[cfg(feature = "oidc")]
210    oidc: Option<std::sync::Arc<oidc::OidcProvider>>,
211    /// Whether a proxy-asserted SSO identity may answer a HITL approval
212    /// (`POST /api/run/respond`). **Default false — deny.**
213    ///
214    /// `run.respond` already refuses shared-token and anonymous callers
215    /// because the approver's identity IS the audit record. An SSO identity
216    /// arrives in a header, trusted because the request also carried
217    /// `sso_secrets` — a static, shared, impersonation-grade value. Whoever
218    /// holds it can assert *any* identity, approval-capable principals
219    /// included, and the resulting audit grain is indistinguishable from a
220    /// genuine approval: a well-formed answer by a granted principal. The
221    /// blast radius of that one secret is the integrity of the whole HITL
222    /// trail — which is the control the governance story rests on.
223    ///
224    /// A credential-map principal is materially stronger (it holds a
225    /// per-principal secret, not a fleet-wide one) and is unaffected by this.
226    /// So the default fails closed and an operator who accepts the trade-off
227    /// opts in explicitly with `areev ui --sso-approvals allow`.
228    sso_approvals: bool,
229    /// Auth-failure counter (issue #126), keyed by source IP — the port is
230    /// deliberately excluded, since a NAT'd or proxied attacker's source
231    /// port varies per connection while the IP does not. Each entry is
232    /// `(consecutive failures, last-failure time)`; see
233    /// `note_auth_failure`/`reset_auth_failures`. The map is
234    /// attacker-controlled key space (one entry per source IP that ever
235    /// fails once) and is bounded at `MAX_AUTH_FAILURE_IPS` for exactly that
236    /// reason. The lock is held only for the map bookkeeping itself, never
237    /// across a response write.
238    ///
239    /// This counts and logs — it does **not** delay or lock out. See
240    /// `note_auth_failure` for why: `serve` is a strictly serial accept
241    /// loop, so any per-request sleep here would be a lever an
242    /// unauthenticated caller pulls to stall the console for everyone, not
243    /// just themselves.
244    auth_failures: std::sync::Mutex<std::collections::HashMap<std::net::IpAddr, (u32, std::time::Instant)>>,
245}
246
247/// A login-flow error, rendered as text rather than JSON: the audience is a
248/// browser mid-redirect, not a script. The message is ours, never the IdP's
249/// raw response body.
250#[cfg(feature = "oidc")]
251fn auth_error(msg: &str) -> (String, String, String) {
252    (
253        "400 Bad Request".into(),
254        "Content-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\n".into(),
255        format!("login failed: {msg}\n\nStart again at /auth/login\n"),
256    )
257}
258
259#[cfg(feature = "oidc")]
260fn not_found_auth() -> (String, String, String) {
261    (
262        "404 Not Found".into(),
263        "Content-Type: text/plain; charset=utf-8\r\n".into(),
264        "no such auth endpoint\n".into(),
265    )
266}
267
268/// One cookie's value out of a `Cookie:` header, or `None`.
269///
270/// Deliberately exact on the name: a `Cookie` header is attacker-influenced
271/// (any script on any same-site origin can set cookies), so a prefix match
272/// would let `areev_session_decoy=...` shadow the real one.
273#[cfg(feature = "oidc")]
274fn cookie_value(header: &str, name: &str) -> Option<String> {
275    header.split(';').find_map(|pair| {
276        let (k, v) = pair.split_once('=')?;
277        (k.trim() == name).then(|| v.trim().to_string())
278    })
279}
280
281/// Validate a proxy-asserted identity before it becomes a principal.
282///
283/// The proxy secret decides *who may assert*; it says nothing about whether
284/// what was asserted is well-formed. An identity flows into audit grains that
285/// are immutable and replicate, so a control character here is a log-injection
286/// that outlives the request — and a name colliding with a system principal is
287/// an ambiguity no later reader can resolve.
288///
289/// Returns `None` for anything rejected, which the caller treats exactly like
290/// an absent header: the request proceeds as whatever its other credentials
291/// make it. Refusing the *request* would let a misconfigured proxy take the
292/// console down; refusing the *identity* fails closed on rights instead.
293fn sanitize_sso_identity(raw: &str) -> Option<String> {
294    let id = raw.trim();
295    if id.is_empty() || id.len() > MAX_SSO_IDENTITY_BYTES {
296        return None;
297    }
298    // No control characters (CR/LF above all — header smuggling into logs),
299    // and no internal whitespace: a principal is one token, and " user:a"
300    // vs "user:a" must not be two audit identities for one person.
301    if id.chars().any(|c| c.is_control() || c.is_whitespace()) {
302        return None;
303    }
304    if RESERVED_PRINCIPALS.contains(&id) {
305        return None;
306    }
307    Some(id.to_string())
308}
309
310/// Per-request principal binding. The server handles one request at a
311/// time, so rebinding the shared facade for the request's duration is
312/// race-free; the guard restores the owner default on drop — including on
313/// panic — so a failed handler can never leak a stray principal into the
314/// next request.
315struct RequestBinding<'a> {
316    facade: &'a AreevFacade,
317}
318
319impl<'a> RequestBinding<'a> {
320    fn bind(
321        facade: &'a AreevFacade,
322        map: &areev_core::authz::CredentialMap,
323        bearer: Option<&str>,
324        memory: &str,
325    ) -> Self {
326        // Memory-scoped resolution: a credential whose `memories` list
327        // excludes THIS memory is indistinguishable from an unknown token.
328        let principal =
329            bearer.and_then(|t| map.resolve_for_memory(t, memory).ok().map(str::to_string));
330        match principal {
331            Some(p) => {
332                if facade.bind_principal(&p).is_err() {
333                    // A store failure reading grants fails toward LESS
334                    // privilege, never more.
335                    Self::bind_anonymous(facade);
336                }
337            }
338            None => Self::bind_anonymous(facade),
339        }
340        RequestBinding { facade }
341    }
342
343    /// `anonymous` = a read-only baseline plus whatever the file explicitly
344    /// grants the `anonymous` principal — the formalized version of the old
345    /// token-less read-only console.
346    /// Bind a proxy-proven SSO identity directly (no credential map row
347    /// needed — the IdP said who this is; the FILE says what they may do).
348    fn bind_identity(facade: &'a AreevFacade, principal: &str) -> Self {
349        if facade.bind_principal(principal).is_err() {
350            Self::bind_anonymous(facade);
351        }
352        RequestBinding { facade }
353    }
354
355    fn bind_anonymous(facade: &AreevFacade) {
356        use areev_core::authz::{AuthzSet, Grant, Verb};
357        let mut grants = facade
358            .with_store(|m| m.authz_grants("anonymous"))
359            .unwrap_or_default();
360        grants.push(Grant { verbs: vec![Verb::Read], namespaces: vec!["*".to_string()] });
361        facade.bind(AuthzSet::restricted("anonymous", grants));
362    }
363}
364
365impl Drop for RequestBinding<'_> {
366    fn drop(&mut self) {
367        self.facade
368            .bind(areev_core::authz::AuthzSet::owner("user:console"));
369    }
370}
371
372impl UiServer {
373    pub fn new(facade: AreevFacade, db_label: String) -> Self {
374        let db_label_display = redact_dsn(&db_label);
375        UiServer {
376            facade: std::sync::Arc::new(facade),
377            executor: CalExecutor::new(CalExecutorConfig::default())
378                .with_governance(std::sync::Arc::new(areev_loop_adapter::LoopGovernance::new())),
379            db_label,
380            db_label_display,
381            token: None,
382            auth_all: false,
383            allow_remote: false,
384            allowed_origins: Vec::new(),
385            loop_policy: None,
386            credentials: None,
387            allow_destructive_ops: CalExecutorConfig::default().allow_destructive_ops,
388            #[cfg(feature = "tls")]
389            tls_config: None,
390            sso_header: None,
391            sso_secrets: Vec::new(),
392            sso_groups_header: None,
393            sso_principal_prefix: None,
394            #[cfg(feature = "oidc")]
395            oidc: None,
396            sso_approvals: false,
397            auth_failures: std::sync::Mutex::new(std::collections::HashMap::new()),
398        }
399    }
400
401    /// Enable trusted-header SSO (v0). `header` names the identity header
402    /// the authenticating proxy forwards; `secret` is the proxy's shared
403    /// secret, demanded in `x-areev-proxy-secret` on every SSO request.
404    pub fn with_sso(self, header: impl Into<String>, secret: impl Into<String>) -> Self {
405        self.with_sso_rotating(header, secret, None::<String>)
406    }
407
408    /// [`with_sso`](Self::with_sso) with a second secret accepted during a
409    /// rotation window (#79).
410    ///
411    /// `next` is the incoming secret; `secret` stays the one already deployed.
412    /// While both are configured either proves the proxy, so the fleet can be
413    /// moved over one node at a time and the old secret retired afterwards —
414    /// the way a TLS key is rotated. Order carries no privilege: they are
415    /// equally valid until one is removed, which is what makes the window
416    /// safe to run in both directions (roll forward, or roll back).
417    ///
418    /// The window is meant to be short. Nothing here enforces that — a
419    /// deadline the server could enforce would have to live in the file or a
420    /// clock it does not own — so retiring the old secret is the operator's
421    /// step, and `docs/runbooks/sso-secret-rotation.md` is the procedure.
422    pub fn with_sso_rotating(
423        mut self,
424        header: impl Into<String>,
425        secret: impl Into<String>,
426        next: Option<impl Into<String>>,
427    ) -> Self {
428        let header = header.into();
429        let secret = secret.into();
430        let next = next.map(Into::into).filter(|s| !s.trim().is_empty());
431        // An empty proxy secret would let `x-areev-proxy-secret:` (empty)
432        // prove any identity — refuse loudly at the library boundary too,
433        // not just in the CLI.
434        assert!(
435            !header.trim().is_empty() && !secret.trim().is_empty(),
436            "with_sso requires a non-empty header name and proxy secret"
437        );
438        // A rotation that deploys the same value twice is a rotation that did
439        // not happen, and it would read as "both live" in every log and
440        // status line. Refuse rather than silently accept the no-op.
441        assert!(
442            next.as_deref() != Some(secret.as_str()),
443            "the rotating proxy secret must differ from the current one"
444        );
445        self.sso_header = Some(header.to_ascii_lowercase());
446        self.sso_secrets = match next {
447            Some(n) => vec![secret, n],
448            None => vec![secret],
449        };
450        self
451    }
452
453    /// Serve native OIDC login for the console (A3).
454    #[cfg(feature = "oidc")]
455    pub fn with_oidc(mut self, provider: oidc::OidcProvider) -> Self {
456        self.oidc = Some(std::sync::Arc::new(provider));
457        self
458    }
459
460    /// The principal for this request's session cookie, if any.
461    #[cfg(feature = "oidc")]
462    fn oidc_principal(&self, cookie_header: Option<&str>) -> Option<String> {
463        let provider = self.oidc.as_ref()?;
464        let sid = cookie_value(cookie_header?, oidc::SESSION_COOKIE)?;
465        provider.principal_for_session(&sid)
466    }
467
468    /// The `/auth/*` endpoints (A3). Returns `(status, extra headers, body)`.
469    ///
470    /// These are the only routes that set headers of their own, which is why
471    /// they bypass `route_full`'s (status, content-type, body) contract.
472    #[cfg(feature = "oidc")]
473    fn oidc_route(
474        &self,
475        method: &str,
476        path: &str,
477        cookie_header: Option<&str>,
478    ) -> (String, String, String) {
479        let provider = match &self.oidc {
480            Some(p) => p,
481            None => return not_found_auth(),
482        };
483        let (base, query) = match path.split_once('?') {
484            Some((p, q)) => (p, q),
485            None => (path, ""),
486        };
487        let q = |key: &str| -> Option<String> {
488            query.split('&').find_map(|kv| {
489                let (k, v) = kv.split_once('=')?;
490                (k == key).then(|| urldecode(v))
491            })
492        };
493        // `Secure` only when the redirect URI is https: a loopback console
494        // over plain http must still be able to log in, and a `Secure` cookie
495        // the browser refuses to send would look like a broken login rather
496        // than a policy.
497        let secure = if provider.is_secure() { "; Secure" } else { "" };
498
499        match (method, base) {
500            ("GET", "/auth/login") => match provider.authorize_url() {
501                Ok(url) => (
502                    "302 Found".into(),
503                    format!("Location: {url}\r\nCache-Control: no-store\r\n"),
504                    String::new(),
505                ),
506                Err(e) => auth_error(&e.to_string()),
507            },
508            ("GET", "/auth/callback") => {
509                let (Some(code), Some(state)) = (q("code"), q("state")) else {
510                    // An IdP-side failure comes back as ?error=...; surface
511                    // it rather than a bare "missing code".
512                    return auth_error(&match q("error") {
513                        Some(e) => format!("the identity provider refused the login: {e}"),
514                        None => "callback missing `code` or `state`".to_string(),
515                    });
516                };
517                match provider.complete_login(&code, &state) {
518                    Ok(sid) => (
519                        "302 Found".into(),
520                        format!(
521                            "Location: /\r\nCache-Control: no-store\r\n\
522                             Set-Cookie: {}={sid}; HttpOnly; SameSite=Strict; Path=/{secure}\r\n",
523                            oidc::SESSION_COOKIE
524                        ),
525                        String::new(),
526                    ),
527                    Err(e) => auth_error(&e.to_string()),
528                }
529            }
530            // Logout accepts POST (the console's button, Origin-checked like
531            // every other mutation) and GET (a bookmarkable escape hatch —
532            // and a GET logout is not a CSRF worth defending: forcing someone
533            // to log out grants an attacker nothing).
534            ("POST", "/auth/logout") | ("GET", "/auth/logout") => {
535                if let Some(sid) = cookie_header.and_then(|c| cookie_value(c, oidc::SESSION_COOKIE))
536                {
537                    // Invalidate SERVER-side too. Clearing only the browser's
538                    // copy would leave a cookie captured beforehand alive.
539                    provider.logout(&sid);
540                }
541                (
542                    "302 Found".into(),
543                    format!(
544                        "Location: /\r\nCache-Control: no-store\r\n\
545                         Set-Cookie: {}=; HttpOnly; SameSite=Strict; Path=/{secure}; Max-Age=0\r\n",
546                        oidc::SESSION_COOKIE
547                    ),
548                    String::new(),
549                )
550            }
551            _ => not_found_auth(),
552        }
553    }
554
555    /// Honor an IdP groups header (A2) under the same proxy secret as the
556    /// identity header. Groups resolve through the credential map's `groups`
557    /// table; without a map, this does nothing.
558    pub fn with_sso_groups_header(mut self, header: impl Into<String>) -> Self {
559        let header = header.into();
560        assert!(
561            !header.trim().is_empty(),
562            "with_sso_groups_header requires a non-empty header name"
563        );
564        self.sso_groups_header = Some(header.to_ascii_lowercase());
565        self
566    }
567
568    /// Stamp `prefix` onto every proxy-asserted principal, so IdP-sourced
569    /// identities are visibly distinct from credential-map ones everywhere
570    /// they land — grants, logs, audit grains.
571    pub fn with_sso_principal_prefix(mut self, prefix: impl Into<String>) -> Self {
572        let prefix = prefix.into();
573        assert!(
574            !prefix.trim().is_empty(),
575            "with_sso_principal_prefix requires a non-empty prefix"
576        );
577        self.sso_principal_prefix = Some(prefix);
578        self
579    }
580
581    /// Resolve a proxy-proven request to its principal (A2).
582    ///
583    /// Precedence, most specific first:
584    /// 1. the asserted **identity**, when the file grants it anything;
585    /// 2. the first **group** (in header order) the credential map maps to a
586    ///    principal;
587    /// 3. nothing — the request falls through to `anonymous`.
588    ///
589    /// Identity-before-group is what makes an individual grant able to
590    /// override a role, which is the direction an operator expects (and the
591    /// direction that lets someone be *removed* from an exception without
592    /// editing the group). Groups are consulted only when the identity is
593    /// ungranted, so adding a groups header can never *narrow* a person who
594    /// already had rights.
595    ///
596    /// Returns `(principal, from_group)`. `from_group` matters downstream: a
597    /// role is not a person, so a group-derived principal can never answer an
598    /// approval — "someone in engineering approved this" is not an audit
599    /// record, whatever `--sso-approvals` says.
600    fn resolve_sso_principal(
601        &self,
602        identity: &str,
603        groups_raw: Option<&str>,
604    ) -> Option<(String, bool)> {
605        let stamp = |p: &str| match &self.sso_principal_prefix {
606            Some(prefix) if !p.starts_with(prefix.as_str()) => format!("{prefix}{p}"),
607            _ => p.to_string(),
608        };
609        let identity = stamp(identity);
610
611        // "Has grants of its own" is asked of the FILE, which is the only
612        // authority on rights. A store error answers "no" — falling toward
613        // the group (and ultimately anonymous) rather than assuming rights
614        // we could not read.
615        let identity_granted = self
616            .facade
617            .with_store(|m| m.authz_grants(&identity))
618            .map(|g| !g.is_empty())
619            .unwrap_or(false);
620        if identity_granted {
621            return Some((identity, false));
622        }
623
624        if let (Some(map), Some(raw)) = (&self.credentials, groups_raw) {
625            for group in raw.split(',') {
626                if let Some(principal) = map.principal_for_group(group) {
627                    return Some((principal.to_string(), true));
628                }
629            }
630        }
631
632        // No grants either way: still bind the identity. It is who the proxy
633        // says this is, `bind_principal` resolves it to the same empty grant
634        // set anonymous would get, and an audit line naming the person beats
635        // one naming "anonymous".
636        Some((identity, false))
637    }
638
639    /// Permit proxy-asserted SSO identities to answer HITL approvals
640    /// (`POST /api/run/respond`). **Off by default**: the identity header's
641    /// only proof is the shared, fleet-wide proxy secret, so whoever holds it
642    /// could approve as anyone — including the approver the audit record then
643    /// names.
644    ///
645    /// Turning this on is a deliberate statement that the proxy shared secret
646    /// is held to the same standard as an approver's own credential. That is
647    /// achievable (a proxy on a Unix socket, or mTLS between proxy and
648    /// console, with the secret never leaving the host) — it is just not
649    /// something the console can verify, so it cannot be the default.
650    pub fn with_sso_approvals(mut self, allow: bool) -> Self {
651        self.sso_approvals = allow;
652        self
653    }
654
655    /// Rebuild the executor from the current gate settings. Every builder
656    /// that touches the CAL surface goes through here so `--no-destructive-ops`
657    /// and `--policy` compose instead of clobbering each other's config —
658    /// and the governance host survives every rebuild. (Same shape as
659    /// `areev-mcp`'s; building `CalExecutorConfig::default()` in one builder
660    /// silently re-enabled destruction configured off by another.)
661    fn rebuild_executor(&mut self) {
662        self.executor = CalExecutor::new(CalExecutorConfig {
663            allow_destructive_ops: self.allow_destructive_ops,
664            ..CalExecutorConfig::default()
665        })
666        .with_governance(std::sync::Arc::new(match &self.loop_policy {
667            Some(p) => areev_loop_adapter::LoopGovernance::with_policy(p.clone()),
668            None => areev_loop_adapter::LoopGovernance::new(),
669        }));
670    }
671
672    /// Multi-principal mode: attach the credential map (`areev-auth.json`).
673    /// Tokens resolve to principal names; rights come from the memory
674    /// file's own grant grains; unauthenticated requests run as
675    /// `anonymous`. See `docs/cal-reference.md` §9.
676    pub fn with_credentials(mut self, map: areev_core::authz::CredentialMap) -> Self {
677        self.credentials = Some(map);
678        self
679    }
680
681    /// Attach a host loop policy to the console's loop routes, so a
682    /// console-triggered run honors the same auto-apply grants, denies, and
683    /// severity floors as `areev loop run --policy`.
684    pub fn with_loop_policy(mut self, policy: areev_loop::Policy) -> Self {
685        self.loop_policy = Some(policy);
686        // The CAL surface's governance host honors the same policy.
687        self.rebuild_executor();
688        self
689    }
690
691    /// The loop engine for a request: builtins + the host policy when one
692    /// was attached.
693    fn engine(&self) -> Engine {
694        match &self.loop_policy {
695            Some(p) => Engine::with_builtins().with_policy(p.clone()),
696            None => Engine::with_builtins(),
697        }
698    }
699
700    /// Accept requests whose `Host` header is non-loopback. Off by default so
701    /// the loopback console is protected against DNS-rebinding reads even when
702    /// unauthenticated; the CLI enables it under `--allow-remote`.
703    pub fn allow_remote(mut self, yes: bool) -> Self {
704        self.allow_remote = yes;
705        self
706    }
707
708    /// Accept a cross-origin **POST** whose `Origin` header exactly matches
709    /// this origin (scheme + host[:port], compared case-insensitively with a
710    /// single trailing `/` ignored). Call once per origin to allow — there
711    /// is no wildcard or subdomain form, by design: naming
712    /// `https://console.example.com` must never thereby accept
713    /// `https://evil-console.example.com`.
714    ///
715    /// `--allow-remote` does **not** imply this. The Origin check exists
716    /// because the console authenticates browsers with HTTP Basic, which the
717    /// browser caches and re-attaches to cross-site requests — Origin is the
718    /// only thing telling the console's own page apart from an attacker's
719    /// page riding a viewer's cached credential, so it is CSRF protection,
720    /// not defence in depth, and it stays enforced on every non-loopback
721    /// origin except the ones named here.
722    pub fn allow_origin(mut self, origin: impl Into<String>) -> Self {
723        self.allowed_origins.push(normalize_origin(&origin.into()));
724        self
725    }
726
727    /// Whether `origin` (a request's raw `Origin` header value) matches one
728    /// of the operator-configured [`allow_origin`](Self::allow_origin)
729    /// entries, after normalizing both sides identically. Exact match only.
730    fn origin_is_allowed(&self, origin: &str) -> bool {
731        let normalized = normalize_origin(origin);
732        self.allowed_origins.contains(&normalized)
733    }
734
735    /// Require a shared secret on **every** request (the console page, reads,
736    /// and writes). Browsers authenticate through the native `Basic` prompt
737    /// (any username; password = `token`); scripts may send `Authorization:
738    /// Bearer <token>`. Use this to serve the console to more than a single
739    /// trusted local operator. Pair with a TLS-terminating proxy for non-local
740    /// exposure — the token crosses the wire in the clear otherwise.
741    pub fn with_auth(mut self, token: String) -> Self {
742        // An empty token would authenticate `Authorization: Bearer ` (the
743        // empty credential) as the OWNER — refuse at the library boundary,
744        // not just in the CLI's --token-env validation.
745        assert!(
746            !token.trim().is_empty(),
747            "with_auth requires a non-empty token"
748        );
749        self.token = Some(token);
750        self.auth_all = true;
751        self
752    }
753
754    /// Permit or forbid destructive CAL (`FORGET <hash>`) from the query
755    /// console. Enabled by default; pass `false` to serve a read-only console.
756    /// Since the plain console is unauthenticated, disabling this is the safe
757    /// choice when the console is exposed beyond a trusted local operator.
758    pub fn allow_destructive_ops(mut self, allow: bool) -> Self {
759        self.allow_destructive_ops = allow;
760        self.rebuild_executor();
761        self
762    }
763
764    /// Bind and return the listener (lets callers learn the ephemeral port).
765    pub fn bind(addr: &str) -> std::io::Result<TcpListener> {
766        TcpListener::bind(addr)
767    }
768
769    /// Serve forever on an already-bound listener.
770    pub fn serve(&self, listener: TcpListener) -> std::io::Result<()> {
771        for stream in listener.incoming() {
772            match stream {
773                Ok(s) => {
774                    if let Err(e) = self.handle(s) {
775                        eprintln!("areev ui: request error: {e}");
776                    }
777                }
778                Err(e) => eprintln!("areev ui: accept error: {e}"),
779            }
780        }
781        Ok(())
782    }
783
784    /// Configure native TLS from PEM files (`tls` cargo feature). The
785    /// documented default remains a TLS-terminating proxy; this is for
786    /// deployments with nowhere to put one (edge boxes, appliances).
787    #[cfg(feature = "tls")]
788    pub fn with_tls(mut self, cert_pem: &str, key_pem: &str) -> std::io::Result<Self> {
789        use rustls::pki_types::pem::PemObject;
790        let pem_err =
791            |e: rustls::pki_types::pem::Error| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string());
792        let certs: Vec<rustls::pki_types::CertificateDer<'static>> =
793            rustls::pki_types::CertificateDer::pem_file_iter(cert_pem)
794                .map_err(pem_err)?
795                .collect::<Result<_, _>>()
796                .map_err(pem_err)?;
797        let key =
798            rustls::pki_types::PrivateKeyDer::from_pem_file(key_pem).map_err(pem_err)?;
799        let config = rustls::ServerConfig::builder()
800            .with_no_client_auth()
801            .with_single_cert(certs, key)
802            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;
803        self.tls_config = Some(std::sync::Arc::new(config));
804        Ok(self)
805    }
806
807    /// Record one failed authentication attempt from `ip` (issue #126) and
808    /// return the new consecutive-failure count — for the caller to LOG,
809    /// never to sleep on. An entry idle for more than
810    /// `AUTH_FAILURE_IDLE_SECS` is treated as reset rather than accumulating
811    /// forever. The map is bounded at `MAX_AUTH_FAILURE_IPS` — the key is
812    /// one attacker-controlled source IP per entry, so an unbounded map here
813    /// would itself be a memory-exhaustion vector; past the cap, the
814    /// stalest entry is evicted before the new one is inserted. The lock is
815    /// held only for this bookkeeping — never across the response write.
816    ///
817    /// **Deliberately no artificial delay or lockout on this count.**
818    /// `UiServer::serve` is a strictly SERIAL accept loop — one connection
819    /// handled at a time, per its own doc comment — so a `std::thread::sleep`
820    /// here, before a response is written, would not slow down one
821    /// attacker: it would stall the entire console for every caller,
822    /// including the operator, behind whatever backoff an unauthenticated
823    /// caller chooses to trigger by sending bad credentials. That trade is
824    /// worse than the problem this counter exists to fix (a 401 that reads
825    /// as ordinary traffic in the log). Rate limiting belongs in front of
826    /// this server — the TLS-terminating proxy the deployment profile
827    /// already calls for — where it can also see the caller's real address;
828    /// this count and the log line built from it are what such a rule is
829    /// written against. Do not reintroduce a sleep/lockout here without
830    /// first making the accept loop concurrent.
831    fn note_auth_failure(&self, ip: std::net::IpAddr) -> u32 {
832        let now = std::time::Instant::now();
833        let idle = Duration::from_secs(AUTH_FAILURE_IDLE_SECS);
834        let mut map = self
835            .auth_failures
836            .lock()
837            .unwrap_or_else(std::sync::PoisonError::into_inner);
838        match map.get_mut(&ip) {
839            Some((n, last)) if now.duration_since(*last) < idle => {
840                *n = n.saturating_add(1);
841                *last = now;
842                *n
843            }
844            Some(entry) => {
845                *entry = (1, now);
846                1
847            }
848            None => {
849                if map.len() >= MAX_AUTH_FAILURE_IPS {
850                    if let Some(stalest) =
851                        map.iter().min_by_key(|(_, (_, last))| *last).map(|(k, _)| *k)
852                    {
853                        map.remove(&stalest);
854                    }
855                }
856                map.insert(ip, (1, now));
857                1
858            }
859        }
860    }
861
862    /// Clear a source IP's failure streak after it authenticates successfully.
863    fn reset_auth_failures(&self, ip: std::net::IpAddr) {
864        let mut map = self
865            .auth_failures
866            .lock()
867            .unwrap_or_else(std::sync::PoisonError::into_inner);
868        map.remove(&ip);
869    }
870
871    /// A source IP's current consecutive-failure count (0 if it has none, or
872    /// if its last failure is older than `AUTH_FAILURE_IDLE_SECS`).
873    ///
874    /// The idle check is applied on READ as well as on write so a lockout
875    /// expires on its own: a stale entry that `note_auth_failure` has not
876    /// been called on again must not keep refusing forever, which is what
877    /// turns a brute-force brake into a self-inflicted outage.
878    fn auth_failure_count(&self, ip: std::net::IpAddr) -> u32 {
879        let idle = Duration::from_secs(AUTH_FAILURE_IDLE_SECS);
880        self.auth_failures
881            .lock()
882            .unwrap_or_else(std::sync::PoisonError::into_inner)
883            .get(&ip)
884            .filter(|(_, last)| last.elapsed() < idle)
885            .map(|(n, _)| *n)
886            .unwrap_or(0)
887    }
888
889    /// Test-only alias — tests read the counter directly because there is no
890    /// sleep to observe via timing (see `note_auth_failure`).
891    #[cfg(test)]
892    fn auth_failure_count_for_test(&self, ip: std::net::IpAddr) -> u32 {
893        self.auth_failure_count(ip)
894    }
895
896    /// Wrap an accepted socket per the TLS posture. The handshake happens
897    /// lazily on first read/write; a plaintext client fails it loudly.
898    fn wrap(&self, stream: TcpStream) -> std::io::Result<Conn> {
899        #[cfg(feature = "tls")]
900        if let Some(config) = &self.tls_config {
901            let session = rustls::ServerConnection::new(std::sync::Arc::clone(config))
902                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;
903            return Ok(Conn::Tls(Box::new(rustls::StreamOwned::new(session, stream))));
904        }
905        Ok(Conn::Plain(stream))
906    }
907
908    fn handle(&self, stream: TcpStream) -> std::io::Result<()> {
909        // The server handles one connection at a time, so a single slow-drip
910        // client could otherwise hold it open indefinitely (a per-read timeout
911        // resets on every byte). A watchdog thread enforces a hard wall-clock
912        // deadline by shutting the socket down; it is unparked and joined the
913        // instant the request completes, so it adds no latency in the fast path.
914        let watchdog_stream = stream.try_clone()?;
915        let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
916        let watchdog_done = std::sync::Arc::clone(&done);
917        let watchdog = std::thread::spawn(move || {
918            std::thread::park_timeout(Duration::from_secs(REQUEST_DEADLINE_SECS));
919            if !watchdog_done.load(std::sync::atomic::Ordering::Acquire) {
920                let _ = watchdog_stream.shutdown(std::net::Shutdown::Both);
921            }
922        });
923        let raw = stream.try_clone()?;
924        let conn = self.wrap(stream)?;
925        let result = self.handle_request(&raw, conn);
926        done.store(true, std::sync::atomic::Ordering::Release);
927        watchdog.thread().unpark();
928        let _ = watchdog.join();
929        result
930    }
931
932    fn handle_request(&self, raw: &TcpStream, mut conn: Conn) -> std::io::Result<()> {
933        // Bound slow clients (slowloris) and total bytes read from the
934        // connection so a malicious client cannot stall the server or exhaust
935        // memory with an oversized request line / headers / body. The
936        // timeouts sit on the RAW socket, so they bound TLS handshakes too.
937        raw.set_read_timeout(Some(Duration::from_secs(READ_TIMEOUT_SECS)))?;
938        raw.set_write_timeout(Some(Duration::from_secs(READ_TIMEOUT_SECS)))?;
939        let mut reader = BufReader::new((&mut conn).take(MAX_CONN_BYTES));
940        let mut request_line = String::new();
941        reader.read_line(&mut request_line)?;
942        let mut parts = request_line.split_whitespace();
943        let method = parts.next().unwrap_or("").to_string();
944        let path = parts.next().unwrap_or("/").to_string();
945
946        // headers → content-length + authorization + origin + host
947        let mut content_length = 0usize;
948        let mut bearer: Option<String> = None;
949        let mut origin: Option<String> = None;
950        let mut host: Option<String> = None;
951        let mut sso_identity_raw: Option<String> = None;
952        let mut sso_groups_raw: Option<String> = None;
953        #[cfg(feature = "oidc")]
954        let mut cookie_header: Option<String> = None;
955        let mut proxy_secret: Option<String> = None;
956        let mut header_bytes = 0usize;
957        let mut header_count = 0usize;
958        loop {
959            let mut line = String::new();
960            let n = reader.read_line(&mut line)?;
961            if n == 0 {
962                break; // EOF / connection closed by peer
963            }
964            header_bytes += n;
965            header_count += 1;
966            if header_bytes > MAX_HEADER_BYTES || header_count > MAX_HEADERS {
967                return Err(std::io::Error::new(
968                    std::io::ErrorKind::InvalidData,
969                    "request headers too large",
970                ));
971            }
972            let l = line.trim();
973            if l.is_empty() {
974                break;
975            }
976            let low = l.to_ascii_lowercase();
977            if let Some(v) = low.strip_prefix("content-length:") {
978                content_length = v.trim().parse().unwrap_or(0);
979            }
980            if let Some(v) = low.strip_prefix("origin:") {
981                origin = Some(v.trim().to_string());
982            }
983            if let Some(v) = low.strip_prefix("host:") {
984                host = Some(v.trim().to_string());
985            }
986            #[cfg(feature = "oidc")]
987            if low.starts_with("cookie:") {
988                // Re-slice the ORIGINAL line: the lowercased copy would
989                // mangle a base64url session id.
990                if let Some((_, orig)) = l.split_once(':') {
991                    cookie_header = Some(orig.trim().to_string());
992                }
993            }
994            if let Some(v) = low.strip_prefix("x-areev-proxy-secret:") {
995                // Secrets are compared, never logged; the lowercased copy is
996                // wrong for comparison, so re-slice the original line.
997                let _ = v;
998                if let Some((_, orig)) = l.split_once(':') {
999                    proxy_secret = Some(orig.trim().to_string());
1000                }
1001            }
1002            if let Some(h) = &self.sso_header {
1003                if low.starts_with(&format!("{h}:")) {
1004                    if let Some((_, orig)) = l.split_once(':') {
1005                        sso_identity_raw = Some(orig.trim().to_string());
1006                    }
1007                }
1008            }
1009            if let Some(h) = &self.sso_groups_header {
1010                if low.starts_with(&format!("{h}:")) {
1011                    if let Some((_, orig)) = l.split_once(':') {
1012                        sso_groups_raw = Some(orig.trim().to_string());
1013                    }
1014                }
1015            }
1016            if low.starts_with("authorization:") {
1017                if let Some((_, v)) = l.split_once(':') {
1018                    let v = v.trim();
1019                    // Accept `Bearer <token>` (scripts/CLI) or HTTP `Basic`
1020                    // (browsers, via the native login prompt). For Basic the
1021                    // credential is base64(user:pass) and the token is the
1022                    // password; the username is ignored.
1023                    bearer = if let Some(t) =
1024                        v.strip_prefix("Bearer ").or_else(|| v.strip_prefix("bearer "))
1025                    {
1026                        Some(t.trim().to_string())
1027                    } else if let Some(b64) =
1028                        v.strip_prefix("Basic ").or_else(|| v.strip_prefix("basic "))
1029                    {
1030                        basic_auth_password(b64.trim())
1031                    } else {
1032                        Some(v.to_string())
1033                    };
1034                }
1035            }
1036        }
1037        // DNS-rebinding defense: a browser tricked into pointing an attacker
1038        // domain at 127.0.0.1 sends that domain in the Host header. Unless the
1039        // operator opted into remote serving, reject any non-loopback Host on
1040        // *every* method (the Origin check below only covers POST, so this is
1041        // what stops a drive-by page from reading memory over GET). A missing
1042        // Host (bare HTTP/1.0, some CLI clients) passes, mirroring Origin.
1043        if !self.allow_remote && host.as_deref().is_some_and(|h| !host_is_local(h)) {
1044            let payload = br#"{"ok":false,"error":"non-loopback Host rejected (use --allow-remote to serve remotely)"}"#;
1045            drop(reader);
1046            let mut out = conn;
1047            write!(
1048                out,
1049                "HTTP/1.1 403 Forbidden\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1050                payload.len()
1051            )?;
1052            out.write_all(payload)?;
1053            return out.flush();
1054        }
1055
1056        let mut body = vec![0u8; content_length.min(1 << 20)];
1057        if content_length > 0 {
1058            reader.read_exact(&mut body)?;
1059        }
1060
1061        // Cross-origin drive-by protection: browsers attach an Origin header
1062        // to cross-site requests. Only loopback pages (the console itself),
1063        // or an origin the operator explicitly allowlisted with
1064        // --allow-origin (issue #125), may mutate; curl/CLI clients send no
1065        // Origin and pass through. `--allow-remote` does NOT lift this on
1066        // its own — see `allow_origin`'s doc comment for why.
1067        if method == "POST"
1068            && origin
1069                .as_deref()
1070                .is_some_and(|o| !origin_is_local(o) && !self.origin_is_allowed(o))
1071        {
1072            let payload = br#"{"ok":false,"error":"cross-origin request rejected"}"#;
1073            drop(reader);
1074            let mut out = conn;
1075            write!(
1076                out,
1077                "HTTP/1.1 403 Forbidden\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1078                payload.len()
1079            )?;
1080            out.write_all(payload)?;
1081            return out.flush();
1082        }
1083
1084        // Captured before the move below: issue #126's failure counter needs
1085        // to know whether a proxy secret was PRESENTED at all (a
1086        // wrong-guess attempt to count), independent of `sso_identity`,
1087        // which by then only ever reflects a *proven* identity.
1088        let proxy_secret_presented = proxy_secret.is_some();
1089        // The identity header is TRUSTED only when the proxy proved itself
1090        // (constant-time secret check). A forged header without the secret
1091        // is silently ignored — the request proceeds as whatever its other
1092        // credentials make it.
1093        //
1094        // [A2] The secret proves the PROXY; it says nothing about whether
1095        // what the proxy forwarded is well-formed. `sanitize_sso_identity`
1096        // is that second question, and a rejected identity is treated
1097        // exactly like an absent one.
1098        let proxy_proved = match &proxy_secret {
1099            Some(presented) => {
1100                // `fold`, not `any`: `any` short-circuits on the first match,
1101                // so during a rotation window the response time would say
1102                // WHICH secret was presented. Every configured secret is
1103                // compared, every time.
1104                self.sso_secrets
1105                    .iter()
1106                    .fold(false, |acc, s| ct_eq(s.as_bytes(), presented.as_bytes()) | acc)
1107            }
1108            None => false,
1109        };
1110        let sso_identity: Option<String> = sso_identity_raw
1111            .filter(|_| proxy_proved)
1112            .as_deref()
1113            .and_then(sanitize_sso_identity);
1114        let sso_groups: Option<String> = sso_groups_raw.filter(|_| proxy_proved);
1115        // [A3] The OIDC login endpoints own their own responses: they answer
1116        // with redirects and `Set-Cookie`, which the JSON `route` contract
1117        // (status, content-type, body) has no slot for. Handled here, where
1118        // the socket and its headers are already in hand.
1119        #[cfg(feature = "oidc")]
1120        if self.oidc.is_some() && path.starts_with("/auth/") {
1121            let (status, extra, payload) =
1122                self.oidc_route(&method, &path, cookie_header.as_deref());
1123            drop(reader);
1124            let mut out = conn;
1125            write!(
1126                out,
1127                "HTTP/1.1 {status}\r\n{extra}Content-Length: {}\r\nConnection: close\r\n\r\n",
1128                payload.len()
1129            )?;
1130            out.write_all(payload.as_bytes())?;
1131            return out.flush();
1132        }
1133        #[cfg(feature = "oidc")]
1134        let oidc_principal = self.oidc_principal(cookie_header.as_deref());
1135        #[cfg(not(feature = "oidc"))]
1136        let oidc_principal: Option<String> = None;
1137
1138        // [A1] Fail closed after repeated failures from one source.
1139        //
1140        // This REJECTS; it never delays. `serve` is a strictly serial accept
1141        // loop, so a per-request sleep would be a lever an unauthenticated
1142        // caller pulls to stall the console for everyone (the reasoning
1143        // recorded on `note_auth_failure`, which is why that counter only
1144        // ever counted). Rejection has the opposite shape: it is cheaper than
1145        // serving, costs the attacker their pipeline, and — placed HERE,
1146        // before `route` — touches no store, runs no constant-time scan, and
1147        // dispatches nothing.
1148        //
1149        // Only when auth is configured AND a credential was presented, the
1150        // same two conditions the counter itself uses: a console with no auth
1151        // has nothing to brute-force, and a browser's first credential-less
1152        // probe is not an attempt.
1153        //
1154        // AND NOT through a trusted proxy. Behind the documented deployment
1155        // (a TLS-terminating, authenticating proxy) every request shares the
1156        // proxy's source address, so a per-IP lockout would let one attacker's
1157        // ten bad guesses refuse *every* user behind it — a self-inflicted
1158        // outage in exactly the configuration we recommend. A request carrying
1159        // a verified proxy secret is proven to have come through that proxy,
1160        // and per-source throttling there is the proxy's job (the same
1161        // division of labour as TLS and the IdP handshake). Direct connections
1162        // — which is every connection on a console with no proxy — are
1163        // unaffected and still brake.
1164        let auth_configured =
1165            self.token.is_some() || self.credentials.is_some() || !self.sso_secrets.is_empty();
1166        let credential_presented = bearer.is_some() || proxy_secret_presented;
1167        if auth_configured && credential_presented && !proxy_proved {
1168            if let Ok(peer) = raw.peer_addr() {
1169                if self.auth_failure_count(peer.ip()) >= MAX_CONSECUTIVE_AUTH_FAILURES {
1170                    let payload = format!(
1171                        r#"{{"ok":false,"error":"too many failed authentications from this address - wait {} minutes, or restart the console to clear the counter"}}"#,
1172                        AUTH_FAILURE_IDLE_SECS / 60
1173                    );
1174                    drop(reader);
1175                    let mut out = conn;
1176                    write!(
1177                        out,
1178                        "HTTP/1.1 429 Too Many Requests\r\nContent-Type: application/json\r\nRetry-After: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1179                        AUTH_FAILURE_IDLE_SECS,
1180                        payload.len()
1181                    )?;
1182                    out.write_all(payload.as_bytes())?;
1183                    return out.flush();
1184                }
1185            }
1186        }
1187
1188        let (status, ctype, payload) = self.route_full(
1189            &method,
1190            &path,
1191            &body,
1192            bearer.as_deref(),
1193            sso_identity.as_deref(),
1194            sso_groups.as_deref(),
1195            oidc_principal.as_deref(),
1196        );
1197
1198        // Auth-failure count + log (issue #126). Only when this server has
1199        // SOME auth mechanism configured, AND a credential was actually
1200        // PRESENTED (a Bearer/Basic value, or a proxy secret) — a plain
1201        // unauthenticated request (a token-less console's read-only-write
1202        // refusal, a browser's very first Basic-auth probe with no
1203        // Authorization header at all) attempted nothing and has no failure
1204        // to count. The token itself is never logged, not even a prefix.
1205        //
1206        // Deliberately no in-process DELAY here — see the comment on
1207        // `note_auth_failure` for why an artificial delay would itself be the
1208        // more dangerous bug on this server. The cheap rejection above is the
1209        // lockout; this is the counter that feeds it.
1210        if auth_configured && credential_presented {
1211            if let Ok(peer) = raw.peer_addr() {
1212                let ip = peer.ip();
1213                if status.starts_with("401") {
1214                    let consecutive = self.note_auth_failure(ip);
1215                    eprintln!("areev: console auth FAILED from {ip} ({consecutive} consecutive)");
1216                } else {
1217                    self.reset_auth_failures(ip);
1218                }
1219            }
1220        }
1221
1222        // On a console-auth 401, challenge with Basic so browsers show the
1223        // native login prompt (any username; password = token).
1224        let auth_challenge = if self.auth_all && status.starts_with("401") {
1225            "WWW-Authenticate: Basic realm=\"Areev console\", charset=\"UTF-8\"\r\n"
1226        } else {
1227            ""
1228        };
1229        drop(reader);
1230        let mut out = conn;
1231        write!(
1232            out,
1233            "HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\n{auth_challenge}Content-Length: {}\r\nConnection: close\r\n\r\n",
1234            payload.len()
1235        )?;
1236        out.write_all(&payload)?;
1237        out.flush()
1238    }
1239
1240    /// The runtime driver for the /api/run/* surface. The console never
1241    /// EXECUTES tools (list/inspect read; respond/cancel journal) — the
1242    /// executor is a refusing stub, present only to satisfy the driver
1243    /// shape.
1244    fn runner(&self, principal: &str) -> areev_run::Runner {
1245        struct NoExec;
1246        impl areev_run::HostToolExecutor for NoExec {
1247            fn execute(
1248                &self,
1249                tool_name: &str,
1250                _h: &str,
1251                _i: &Value,
1252                _k: &str,
1253            ) -> areev_run::ExecResult {
1254                areev_run::ExecResult::Err {
1255                    cause: areev_run::FailCause::ExecutorError,
1256                    detail: format!("the console does not execute tools ('{tool_name}')"),
1257                }
1258            }
1259        }
1260        areev_run::Runner {
1261            facade: std::sync::Arc::clone(&self.facade),
1262            clock: std::sync::Arc::new(areev_run::SystemClock),
1263            executor: std::sync::Arc::new(NoExec),
1264            llm: None,
1265            observer: None,
1266            ns: self
1267                .facade
1268                .default_namespace()
1269                .unwrap_or("shared")
1270                .to_string(),
1271            principal: principal.to_string(),
1272        }
1273    }
1274
1275    /// The no-groups spelling, for the tests written before A2 added the
1276    /// groups header. Production always goes through
1277    /// [`route_with_groups`](Self::route_with_groups); this exists only so
1278    /// two dozen assertions that never had a groups header do not each grow
1279    /// a trailing `None`.
1280    #[cfg(test)]
1281    fn route(
1282        &self,
1283        method: &str,
1284        path: &str,
1285        body: &[u8],
1286        bearer: Option<&str>,
1287        sso_identity: Option<&str>,
1288    ) -> (&'static str, &'static str, Vec<u8>) {
1289        self.route_full(method, path, body, bearer, sso_identity, None, None)
1290    }
1291
1292    /// [`route`](Self::route) with the A2 groups header but no OIDC session —
1293    /// the spelling the A2 tests use.
1294    #[cfg(test)]
1295    fn route_with_groups(
1296        &self,
1297        method: &str,
1298        path: &str,
1299        body: &[u8],
1300        bearer: Option<&str>,
1301        sso_identity: Option<&str>,
1302        sso_groups: Option<&str>,
1303    ) -> (&'static str, &'static str, Vec<u8>) {
1304        self.route_full(method, path, body, bearer, sso_identity, sso_groups, None)
1305    }
1306
1307    /// Route one request.
1308    ///
1309    /// `sso_groups` is the raw, proxy-proven groups header (A2) and
1310    /// `oidc_principal` the identity behind a valid session cookie (A3) —
1311    /// both already authenticated by the caller, which is why neither
1312    /// carries its proof this far down.
1313    #[allow(clippy::too_many_arguments)]
1314    fn route_full(
1315        &self,
1316        method: &str,
1317        path: &str,
1318        body: &[u8],
1319        bearer: Option<&str>,
1320        sso_identity: Option<&str>,
1321        sso_groups: Option<&str>,
1322        oidc_principal: Option<&str>,
1323    ) -> (&'static str, &'static str, Vec<u8>) {
1324        // Auth: console-auth mode (`auth_all`) guards every request;
1325        // otherwise the token guards only mutating endpoints. The credential
1326        // arrives as a Bearer token or an HTTP Basic password (see
1327        // `handle_request`).
1328        //
1329        // A credential map changes WHO a request is, not WHETHER the shared
1330        // secret is required. When both are configured, a map token
1331        // authenticates as its principal, the shared secret authenticates as
1332        // the implied admin (`docs/cal-all-you-need-proposal.md` §5.2b), and
1333        // anything else is refused — an attached map must never silently
1334        // downgrade a `--token-env` console to an open `anonymous` one.
1335        let mut shared_secret_ok = false;
1336        if let Some(tok) = &self.token {
1337            let guarded = self.auth_all || method == "POST";
1338            shared_secret_ok = bearer.is_some_and(|b| ct_eq(b.as_bytes(), tok.as_bytes()));
1339            let known = shared_secret_ok
1340                || sso_identity.is_some()
1341                || oidc_principal.is_some()
1342                || match (&self.credentials, bearer) {
1343                    (Some(map), Some(b)) => map.resolve_for_memory(b, &self.db_label).is_ok(),
1344                    _ => false,
1345                };
1346            if guarded && !known {
1347                return ("401 Unauthorized", "application/json",
1348                        br#"{"ok":false,"error":"authentication required"}"#.to_vec());
1349            }
1350        } else if self.credentials.is_none()
1351            && sso_identity.is_none()
1352            && oidc_principal.is_none()
1353            && method == "POST"
1354        {
1355            // §5.7: token-less `areev ui` is read-only. The ONLY POST allowed is
1356            // a read-only CAL statement; every write (any loop mutation, an
1357            // ADD/SUPERSEDE/FORGET CAL batch, etc.) requires --token-env. This
1358            // closes the bypass where a local process could execute a
1359            // proposal's CAL directly and skip the review queue.
1360            let base = path.split_once('?').map(|(p, _)| p).unwrap_or(path);
1361            let allowed = base == "/api/cal" && cal_body_is_read_only(body);
1362            if !allowed {
1363                return ("401 Unauthorized", "application/json",
1364                        br#"{"ok":false,"error":"read-only console: restart areev ui with --auth <map> (per-principal credentials, attributable writes and approvals) or --token-env VAR (one shared secret, writes only) to enable writes"}"#.to_vec());
1365            }
1366        }
1367
1368        // Credential-map mode: resolve this request's principal and bind
1369        // the facade for the request's duration (the guard restores the
1370        // owner default on drop). Every verb check downstream — CAL,
1371        // loop scopes, the run gate below — now answers for THIS caller.
1372        // A request authenticated by the shared secret keeps the owner
1373        // session that secret has always carried.
1374        let _session = match (&self.credentials, shared_secret_ok) {
1375            (Some(map), false) => Some(RequestBinding::bind(&self.facade, map, bearer, &self.db_label)),
1376            _ => None,
1377        };
1378        // The request's resolved PRINCIPAL identity — Some only when a
1379        // per-principal credential authenticated it. The shared secret and
1380        // anonymous access deliberately resolve to None: approvals need an
1381        // identity, and "whoever holds the console token" is not one.
1382        let mut request_principal: Option<String> = match (&self.credentials, shared_secret_ok, bearer)
1383        {
1384            (Some(map), false, Some(b)) => map.resolve_for_memory(b, &self.db_label).ok().map(str::to_string),
1385            _ => None,
1386        };
1387        // SSO v0: a proxy-proven identity becomes the request principal when
1388        // no bearer credential resolved one (machines keep tokens; SSO is
1389        // for humans behind the proxy). Rights come from the file's grants.
1390        //
1391        // `principal_from_sso` records the PROVENANCE of the identity, not
1392        // just its value: everything downstream treats a principal as a
1393        // principal, but one control (HITL approval) must distinguish an
1394        // identity proven by a per-principal credential from one asserted by
1395        // a proxy holding a shared secret. See `sso_approvals`.
1396        let mut principal_from_sso = false;
1397        // [A2] `principal_from_group` is a strictly stronger refusal than
1398        // `principal_from_sso`: a role name cannot be an approver's identity
1399        // under ANY setting, because there is no person behind it.
1400        let mut principal_from_group = false;
1401        // [A3] An OIDC session outranks a proxy-asserted header: its identity
1402        // was proven by a signature this process verified against the
1403        // issuer's key set, not by a shared secret whose holder can assert
1404        // anyone. That is the whole reason native OIDC exists here, so it is
1405        // resolved FIRST and the header path never overwrites it.
1406        let mut principal_from_oidc = false;
1407        let _oidc_session = match (&request_principal, oidc_principal, shared_secret_ok) {
1408            (None, Some(principal), false) => {
1409                principal_from_oidc = true;
1410                let binding = RequestBinding::bind_identity(&self.facade, principal);
1411                request_principal = Some(principal.to_string());
1412                Some(binding)
1413            }
1414            _ => None,
1415        };
1416        let _sso_session = match (&request_principal, sso_identity, shared_secret_ok) {
1417            (None, Some(identity), false) => {
1418                match self.resolve_sso_principal(identity, sso_groups) {
1419                    Some((principal, from_group)) => {
1420                        principal_from_sso = true;
1421                        principal_from_group = from_group;
1422                        let binding = RequestBinding::bind_identity(&self.facade, &principal);
1423                        request_principal = Some(principal);
1424                        Some(binding)
1425                    }
1426                    None => None,
1427                }
1428            }
1429            _ => None,
1430        };
1431
1432        let (path, query) = match path.split_once('?') {
1433            Some((p, q)) => (p, q),
1434            None => (path, ""),
1435        };
1436        let q = |key: &str| -> Option<String> {
1437            query.split('&').find_map(|kv| {
1438                let (k, v) = kv.split_once('=')?;
1439                (k == key).then(|| urldecode(v))
1440            })
1441        };
1442        match (method, path) {
1443            ("GET", "/") => (
1444                "200 OK",
1445                "text/html; charset=utf-8",
1446                CONSOLE_HTML
1447                    .replace("{{DB}}", &html_escape(&self.db_label_display))
1448                    .into_bytes(),
1449            ),
1450            ("POST", "/api/cal") => {
1451                let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1452                let queryt = req.get("query").and_then(|v| v.as_str()).unwrap_or("");
1453                match self.executor.execute(queryt, &*self.facade) {
1454                    Ok(res) => ok_json(json!({
1455                        "ok": true,
1456                        "result": res.result,
1457                        "warnings": res.warnings,
1458                        "statement": res.metadata.statement_type,
1459                        "elapsed_ms": res.metadata.execution_time_ms,
1460                    })),
1461                    Err(e) => {
1462                        // Structured error: code + span + hint let the console
1463                        // point at the offending token instead of just quoting.
1464                        let mut err = json!({
1465                            "ok": false,
1466                            "error": e.sanitize_for_client(),
1467                            "code": e.code(),
1468                        });
1469                        if let Some(sp) = e.span() {
1470                            err["span"] = json!({
1471                                "start": sp.start, "end": sp.end,
1472                                "line": sp.line, "col": sp.col,
1473                            });
1474                        }
1475                        if let Some(hint) = e.suggestion() {
1476                            err["suggestion"] = json!(hint);
1477                        }
1478                        ok_json(err)
1479                    }
1480                }
1481            }
1482            ("GET", "/api/stats") => {
1483                let stats = self.facade.with_store(|m| m.stats());
1484                match stats {
1485                    Ok(s) => ok_json(json!({
1486                        "db": self.db_label_display,
1487                        "grains": s.grains, "current": s.current,
1488                        "triples": s.triples, "terms": s.terms,
1489                        "ops": s.ops, "events_indexed": s.events_indexed,
1490                    })),
1491                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
1492                }
1493            }
1494            ("GET", "/api/log") => {
1495                let since: i64 = q("since").and_then(|v| v.parse().ok()).unwrap_or(0);
1496                let limit: usize = q("limit").and_then(|v| v.parse().ok()).unwrap_or(100);
1497                match self.facade.with_store(|m| m.changes_since(since, limit)) {
1498                    Ok(ops) => {
1499                        let rows: Vec<Value> = ops
1500                            .iter()
1501                            .map(|o| {
1502                                json!({
1503                                    "op_seq": o.op_seq, "hlc": o.hlc,
1504                                    "op": match o.op { 1 => "add", 2 => "supersede", 3 => "forget", _ => "?" },
1505                                    "hash": o.hash.to_hex(),
1506                                })
1507                            })
1508                            .collect();
1509                        ok_json(json!(rows))
1510                    }
1511                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
1512                }
1513            }
1514            // Who am I: the principal this request is bound to. In
1515            // credential-map mode this reflects the per-request binding;
1516            // read-only and mode-agnostic.
1517            ("GET", "/api/whoami") => {
1518                let a = self.facade.authz();
1519                ok_json(json!({
1520                    "ok": true,
1521                    "principal": a.principal(),
1522                    "owner": a.is_owner(),
1523                    "mode": if self.credentials.is_some() { "credentials" }
1524                            else if self.token.is_some() { "token" }
1525                            else { "open" },
1526                    // Provenance, not just value: the console shows an
1527                    // approver whether their identity is one this instance
1528                    // will accept on `run.respond` BEFORE they try it.
1529                    "identity_source": if principal_from_oidc { "oidc" }
1530                                       else if principal_from_group { "sso-group" }
1531                                       else if principal_from_sso { "sso" }
1532                                       else if request_principal.is_some() { "credential" }
1533                                       else { "none" },
1534                    "may_approve": request_principal.is_some()
1535                        && !principal_from_group
1536                        && (!principal_from_sso || self.sso_approvals),
1537                }))
1538            }
1539            ("GET", "/api/config") => {
1540                // Read-only observability: the *effective* per-process
1541                // configuration. Nothing here is persisted in the .db —
1542                // the file holds data only; these values are supplied by
1543                // the host at open time.
1544                let cfg = self.executor.config();
1545                let (index_text, embedder_dim, declared_embed, mut warnings) =
1546                    self.facade.with_store(|m| {
1547                        (
1548                            m.index_text_enabled(),
1549                            m.embedder_dim(),
1550                            m.declared_embedding().map(|(mm, d)| (mm.to_string(), d)),
1551                            m.open_warnings().to_vec(),
1552                        )
1553                    });
1554                if let Some((m, d)) = &declared_embed {
1555                    if embedder_dim.is_none() {
1556                        warnings.push(format!(
1557                            "vector leg dormant: file expects {m}@{d}, no embedding backend installed"
1558                        ));
1559                    }
1560                }
1561                // Saved queries and templates the file carries that this build
1562                // cannot load. Same class of thing as an open warning — the
1563                // file and the host disagree — so it belongs in the same list.
1564                warnings.extend(self.facade.meta_warnings());
1565                // Anonymization observability (REQ-ANON-5: no policy is
1566                // loud): declared per-ns modes, the host floor, and the
1567                // audit counters. Modes only — never mappings or values.
1568                let (anon_declared, anon_floor, anon_audit) = self.facade.with_store(|m| {
1569                    (
1570                        m.anon_declared(),
1571                        m.anonymize_egress_floor(),
1572                        m.anon_audit_counts(),
1573                    )
1574                });
1575                let anonymization = json!({
1576                    "policies": anon_declared
1577                        .iter()
1578                        .map(|(ns, mode)| json!({"ns": ns, "mode": mode}))
1579                        .collect::<Vec<_>>(),
1580                    "floor": anon_floor,
1581                    "audit_counts": anon_audit
1582                        .iter()
1583                        .map(|(ns, cat, n)| json!({"ns": ns, "category": cat, "count": n}))
1584                        .collect::<Vec<_>>(),
1585                });
1586                ok_json(json!({
1587                    "ok": true,
1588                    "db": self.db_label_display,
1589                    "warnings": warnings,
1590                    "anonymization": anonymization,
1591                    "file": {
1592                        "text_index": index_text,
1593                        "embedding": declared_embed.map(|(m, d)| json!({"model": m, "dim": d})),
1594                    },
1595                    "session": {
1596                        "namespace": self.facade.session_namespace(),
1597                        "mounts": self.facade.mount_aliases(),
1598                        // Gates the console's "All namespaces" picker option —
1599                        // same rule /api/browse?ns=* and /api/namespaces enforce.
1600                        "is_owner": self.facade.authz().is_owner(),
1601                    },
1602                    "store": {
1603                        "index_text": index_text,
1604                        "embedder": embedder_dim.map(|d| json!({"dim": d})),
1605                    },
1606                    "recall": {
1607                        "fusion": "rrf",
1608                        "rrf_k0": areev_store::RRF_K0,
1609                        "overfetch_factor": AreevFacade::RECALL_OVERFETCH,
1610                        "legs": {
1611                            "structural": true,
1612                            "bm25": index_text,
1613                            "vector": embedder_dim.is_some(),
1614                        },
1615                    },
1616                    "executor": {
1617                        "max_limit": cfg.max_limit,
1618                        "default_limit": cfg.default_limit,
1619                        "tier1_writes": cfg.tier1_enabled,
1620                        "namespace_override": cfg.namespace_override,
1621                        "user_id_override": cfg.user_id_override,
1622                    },
1623                    "server": {
1624                        "auth_required": self.token.is_some(),
1625                        // true = every request is authenticated (console-auth);
1626                        // false with auth_required = writes only.
1627                        "auth_all": self.auth_all,
1628                    },
1629                    "persistence": "per-process (host-supplied at open) — not stored in the .db",
1630                }))
1631            }
1632            ("GET", "/api/browse") => {
1633                // Browse-without-queries: the tail of the op-log joined with
1634                // grain summaries, newest first. Supersession and tombstone
1635                // status are resolved within the returned window so the
1636                // console can dim/strike them (grains are never mutated —
1637                // this reads the index + immutable blobs only).
1638                let limit: i64 = q("limit")
1639                    .and_then(|v| v.parse().ok())
1640                    .unwrap_or(500)
1641                    .clamp(1, 2000);
1642                let built = self.facade.with_store(|m| -> Result<(i64, Vec<Value>), String> {
1643                    let total = m.stats().map_err(|e| e.to_string())?.ops as i64;
1644                    let after = (total - limit).max(0);
1645                    let ops = m.changes_since(after, limit as usize).map_err(|e| e.to_string())?;
1646                    let mut rows: Vec<Value> = Vec::with_capacity(ops.len());
1647                    let mut idx: std::collections::HashMap<String, usize> =
1648                        std::collections::HashMap::new();
1649                    for o in &ops {
1650                        let hex = o.hash.to_hex();
1651                        let op_name = match o.op { 1 => "add", 2 => "supersede", 3 => "forget", _ => "?" };
1652                        if o.op == 3 {
1653                            // tombstone: flag the earlier row if it is in the
1654                            // window, else emit a stub (blob is already gone).
1655                            match idx.get(&hex) {
1656                                Some(&i) => { rows[i]["forgotten"] = json!(true); }
1657                                None => rows.push(json!({
1658                                    "hash": hex, "op_seq": o.op_seq, "hlc": o.hlc,
1659                                    "op": op_name, "forgotten": true,
1660                                })),
1661                            }
1662                            continue;
1663                        }
1664                        // A SUPERSEDE logs two ops for the new grain (add +
1665                        // supersede) — merge them into one row, keeping the
1666                        // later op label.
1667                        if let Some(&i) = idx.get(&hex) {
1668                            rows[i]["op"] = json!(op_name);
1669                            rows[i]["op_seq"] = json!(o.op_seq);
1670                            rows[i]["hlc"] = json!(o.hlc);
1671                            continue;
1672                        }
1673                        let mut row = json!({
1674                            "hash": hex, "op_seq": o.op_seq, "hlc": o.hlc, "op": op_name,
1675                        });
1676                        match m.get(&o.hash) {
1677                            Ok(g) => {
1678                                row["type"] = json!(format!("{:?}", g.grain_type).to_lowercase());
1679                                row["fields"] = serde_json::to_value(&g.fields).unwrap_or(Value::Null);
1680                            }
1681                            // erased since (forget op outside the window)
1682                            Err(_) => { row["missing"] = json!(true); }
1683                        }
1684                        idx.insert(hex, rows.len());
1685                        rows.push(row);
1686                    }
1687                    // A supersede op's grain points at its predecessor via
1688                    // derived_from; mark the predecessor if it is in-window.
1689                    let marks: Vec<(String, String)> = rows.iter()
1690                        .filter(|r| r["op"] == "supersede")
1691                        .filter_map(|r| {
1692                            let old = r["fields"].get("derived_from")?.as_str()?;
1693                            Some((old.to_string(), r["hash"].as_str()?.to_string()))
1694                        })
1695                        .collect();
1696                    for (old, newer) in marks {
1697                        if let Some(&i) = idx.get(&old) {
1698                            rows[i]["superseded_by"] = json!(newer);
1699                        }
1700                    }
1701                    rows.reverse();
1702                    Ok((total, rows))
1703                });
1704                // Scope the browse to a namespace, the way CAL already scopes
1705                // recall. Without this the rail lists entities (`john`, `bob`)
1706                // that every query on this console then reports as missing,
1707                // because the two disagree about what is in view.
1708                //
1709                // `?ns=<name>` lets the console browse a namespace other than
1710                // the one it was launched with, and `?ns=*` lifts the filter
1711                // entirely — both read-gated against the session's own
1712                // `AuthzSet` exactly as a `RECALL ... WHERE namespace = ...`
1713                // would be (`changes_since` itself reads the whole op-log
1714                // unscoped; this filter is the only enforcement point, so it
1715                // has to check what `AreevFacade::recall` checks, not less).
1716                // Omitting `?ns` keeps the original session-default behavior
1717                // byte-for-byte. Rows we cannot attribute — tombstone stubs,
1718                // grains erased since — are kept regardless: dropping them
1719                // would hide an erasure.
1720                let ns_param = q("ns");
1721                let built = built.and_then(|(total, rows)| {
1722                    let authz = self.facade.authz();
1723                    let filter_ns = match ns_param.as_deref() {
1724                        Some("*") => {
1725                            if !authz.is_owner() {
1726                                return Err("not authorized to browse all namespaces".to_string());
1727                            }
1728                            None
1729                        }
1730                        Some(ns) => {
1731                            authz
1732                                .check(areev_core::authz::Verb::Read, ns)
1733                                .map_err(|e| e.to_string())?;
1734                            Some(ns.to_string())
1735                        }
1736                        None => self.facade.session_namespace().map(|s| s.to_string()),
1737                    };
1738                    let Some(ns) = filter_ns else {
1739                        return Ok((total, rows));
1740                    };
1741                    let kept = rows
1742                        .into_iter()
1743                        .filter(|r| {
1744                            r["fields"]
1745                                .get("namespace")
1746                                .and_then(Value::as_str)
1747                                .is_none_or(|got| got == ns)
1748                        })
1749                        .collect();
1750                    Ok((total, kept))
1751                });
1752                match built {
1753                    Ok((total, rows)) => ok_json(json!({"ok": true, "total_ops": total, "grains": rows})),
1754                    Err(e) => ok_json(json!({"ok": false, "error": e})),
1755                }
1756            }
1757            ("GET", "/api/namespaces") => {
1758                // Every namespace present in the file, for the console's
1759                // namespace picker. A restricted principal only ever sees the
1760                // ones its own grants cover — read access to the *names* of
1761                // namespaces it cannot read from would itself be a disclosure.
1762                let result = self.facade.with_store(|m| m.namespaces());
1763                match result {
1764                    Ok(list) => {
1765                        let authz = self.facade.authz();
1766                        let owner = authz.is_owner();
1767                        let arr: Vec<Value> = list
1768                            .into_iter()
1769                            .filter(|(ns, _)| {
1770                                owner || authz.check(areev_core::authz::Verb::Read, ns).is_ok()
1771                            })
1772                            .map(|(ns, n)| json!({"namespace": ns, "count": n}))
1773                            .collect();
1774                        ok_json(json!({"ok": true, "namespaces": arr}))
1775                    }
1776                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
1777                }
1778            }
1779            ("GET", "/api/grain") => {
1780                let hash = q("hash").unwrap_or_default();
1781                match areev_core::error::Hash::from_hex(&hash)
1782                    .and_then(|h| self.facade.get(&h))
1783                {
1784                    Ok(g) => ok_json(json!({
1785                        "hash": g.hash.to_hex(),
1786                        "type": format!("{:?}", g.grain_type).to_lowercase(),
1787                        "fields": g.fields,
1788                    })),
1789                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
1790                }
1791            }
1792            ("GET", "/api/anon/preview") => {
1793                // "As the model sees it" (proposal §8.3): the grain rendered
1794                // the way an egress boundary would show it, policy or not.
1795                let hash = q("hash").unwrap_or_default();
1796                match areev_core::error::Hash::from_hex(&hash)
1797                    .and_then(|h| self.facade.with_store(|m| m.anon_preview(&h)))
1798                {
1799                    Ok(g) => ok_json(json!({
1800                        "hash": g.hash.to_hex(),
1801                        "type": format!("{:?}", g.grain_type).to_lowercase(),
1802                        "fields": g.fields,
1803                    })),
1804                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
1805                }
1806            }
1807            ("GET", "/api/verify") => match self.facade.with_store(|m| m.verify()) {
1808                Ok(r) => ok_json(json!({
1809                    "integrity": r.integrity, "grains": r.grains,
1810                    "hash_mismatches": r.hash_mismatches, "undecodable": r.undecodable,
1811                })),
1812                Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
1813            },
1814            // ── Areev Loop API (§5.4) — GETs are reads (token-less OK); the POST
1815            //    mutations are guarded above (token-less → 401). ────────────
1816            // ── /api/run/*: the governed runtime's console surface ──
1817            ("GET", "/api/run/list") => {
1818                let runner = self.runner("console:read");
1819                match runner.recent_runs(50) {
1820                    Ok(ids) => {
1821                        let rows: Vec<Value> = ids
1822                            .iter()
1823                            .map(|id| {
1824                                let outcome = self.facade.with_store(|m| {
1825                                    m.recent(
1826                                        "agent:harness",
1827                                        Some(areev_core::types::GrainType::Observation),
1828                                        4096,
1829                                    )
1830                                })
1831                                .ok()
1832                                .and_then(|rows| {
1833                                    rows.into_iter().find(|g| {
1834                                        g.get_str("run_id") == Some(id.as_str())
1835                                            && g.get_str("observation_kind")
1836                                                == Some("run_outcome")
1837                                    })
1838                                });
1839                                serde_json::json!({
1840                                    "run_id": id,
1841                                    "outcome": outcome.as_ref().and_then(|g| g.get_str("object")).unwrap_or("open"),
1842                                })
1843                            })
1844                            .collect();
1845                        ok_json(serde_json::json!({"ok": true, "runs": rows}))
1846                    }
1847                    Err(e) => run_api_err(&e.to_string()),
1848                }
1849            }
1850            ("GET", "/api/run/inspect") => {
1851                let Some(run_id) = q("run_id") else {
1852                    return run_api_err("run_id required");
1853                };
1854                // Same Runner::inspect the CLI and bindings call (issue
1855                // #34) — this used to hand-roll a divergent, smaller subset
1856                // (no pinned/budgets/fork_of/superstep/phase).
1857                match self.runner("console:read").inspect(&run_id) {
1858                    Ok(report) => {
1859                        let mut v = serde_json::to_value(&report).unwrap_or(Value::Null);
1860                        if let Some(o) = v.as_object_mut() {
1861                            o.insert("ok".into(), Value::Bool(true));
1862                        }
1863                        ok_json(v)
1864                    }
1865                    Err(e) => run_api_err(&e.to_string()),
1866                }
1867            }
1868            ("POST", "/api/run/respond") => {
1869                // [R3] SHARED-TOKEN APPROVALS ARE REFUSED: an approval whose
1870                // "identity" is a console-wide secret voids the
1871                // approver-identity edge of the provenance chain. Only a
1872                // per-principal credential (areev ui --auth) may respond.
1873                let Some(responder) = request_principal.clone() else {
1874                    return ("403 Forbidden", "application/json",
1875                        br#"{"ok":false,"error":"run.respond requires a per-principal credential (areev ui --auth <map>); shared-token or anonymous approvals are refused - the approver's identity IS the audit record"}"#.to_vec());
1876                };
1877                // [A0] PROXY-ASSERTED APPROVALS ARE REFUSED BY DEFAULT: an
1878                // SSO identity's only proof is a shared, static, fleet-wide
1879                // proxy secret — whoever holds it can assert any identity,
1880                // including this approver's. That is a weaker claim than the
1881                // per-principal credential [R3] demands, and the resulting
1882                // audit grain would be indistinguishable from a real
1883                // approval. Opt in with `areev ui --sso-approvals allow`.
1884                if principal_from_sso && !self.sso_approvals {
1885                    return ("403 Forbidden", "application/json",
1886                        br#"{"ok":false,"error":"run.respond refuses proxy-asserted SSO identities: the identity header is trusted only via a shared proxy secret, which whoever holds it can use to assert any approver. Approve with a per-principal credential (areev ui --auth <map>), or accept the trade-off explicitly with --sso-approvals allow"}"#.to_vec());
1887                }
1888                // [A2] A group-derived principal is a ROLE. It is refused
1889                // even under `--sso-approvals allow`, and deliberately has no
1890                // flag of its own: the audit record would read "role:eng
1891                // approved", which names no one who can be asked why.
1892                if principal_from_group {
1893                    return ("403 Forbidden", "application/json",
1894                        br#"{"ok":false,"error":"run.respond refuses group-derived principals: a role is not an approver, and an audit record naming one identifies nobody. Grant this person a principal of their own, or give them a per-principal credential"}"#.to_vec());
1895                }
1896                let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1897                let (Some(run_id), Some(ask)) = (
1898                    req.get("run_id").and_then(Value::as_str),
1899                    req.get("tool_call_id").and_then(Value::as_str),
1900                ) else {
1901                    return run_api_err("run_id and tool_call_id required");
1902                };
1903                let result = req.get("result").cloned().unwrap_or(Value::Null);
1904                let is_error = req.get("is_error").and_then(Value::as_bool).unwrap_or(false);
1905                let runner = self.runner(&responder);
1906                match runner.respond(run_id, ask, result, is_error, &responder) {
1907                    Ok(()) => ok_json(serde_json::json!({
1908                        "ok": true, "responded": ask, "responder": responder,
1909                        "note": "resume the run to spend the compute",
1910                    })),
1911                    Err(e) => run_api_err(&e.to_string()),
1912                }
1913            }
1914            ("POST", "/api/run/cancel") => {
1915                // The kill switch keeps its LOW bar: any authenticated POST
1916                // may brake a run (the identity label still records who).
1917                let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1918                let Some(run_id) = req.get("run_id").and_then(Value::as_str) else {
1919                    return run_api_err("run_id required");
1920                };
1921                let because = req.get("because").and_then(Value::as_str).unwrap_or("canceled via console");
1922                let who = request_principal.clone().unwrap_or_else(|| "console:shared".into());
1923                let runner = self.runner(&who);
1924                match runner.cancel(run_id, &who, because) {
1925                    Ok(()) => ok_json(serde_json::json!({"ok": true, "canceled": run_id})),
1926                    Err(e) => run_api_err(&e.to_string()),
1927                }
1928            }
1929            ("GET", "/api/loop/recommendations") => {
1930                let status = q("status").and_then(|s| status_from_str(&s));
1931                let sub = BorrowedSubstrate::new(&self.facade);
1932                match self.engine().recommendations(&sub, status) {
1933                    Ok(recs) => ok_json(json!({
1934                        "ok": true,
1935                        "recommendations": recs.iter().map(rec_json).collect::<Vec<_>>(),
1936                    })),
1937                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1938                }
1939            }
1940            ("GET", "/api/loop/health") => {
1941                let sub = BorrowedSubstrate::new(&self.facade);
1942                match self.engine().health(&sub, now_ms()) {
1943                    Ok(h) => ok_json(json!({"ok": true, "health": h})),
1944                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1945                }
1946            }
1947            ("GET", "/api/loop/outcomes") => {
1948                let sub = BorrowedSubstrate::new(&self.facade);
1949                match self.engine().outcomes(&sub) {
1950                    Ok(o) => ok_json(json!({"ok": true, "outcomes": o})),
1951                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1952                }
1953            }
1954            ("GET", "/api/loop/analyzers") => {
1955                // Effective settings (manifest merged with the file-config), so
1956                // the Setup view renders accurate on/off state and floors.
1957                let sub = BorrowedSubstrate::new(&self.facade);
1958                match self.engine().analyzer_settings(&sub) {
1959                    Ok(list) => ok_json(json!({"ok": true, "analyzers": list})),
1960                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1961                }
1962            }
1963            ("GET", "/api/loop/telemetry") => {
1964                // Recall-telemetry rollups for the Sessions view. A read — open
1965                // in read-only mode like the other loop GETs.
1966                let mode = self.facade.with_store(|m| m.telemetry_mode());
1967                if mode == areev_store::TelemetryMode::Off {
1968                    ok_json(json!({"ok": true, "enabled": false}))
1969                } else {
1970                    let access = self.facade.with_store(|m| m.telemetry_access_stats(None));
1971                    let queries = self.facade.with_store(|m| m.telemetry_query_stats(None));
1972                    let budget = self.facade.with_store(|m| m.telemetry_budget_stats());
1973                    match (access, queries, budget) {
1974                        (Ok(mut a), Ok(mut q), Ok(b)) => {
1975                            // Most-recalled first; recurring-gap questions first.
1976                            a.sort_by_key(|x| std::cmp::Reverse(x.recall_count));
1977                            a.truncate(200);
1978                            q.sort_by_key(|x| std::cmp::Reverse(x.run_count));
1979                            q.truncate(200);
1980                            ok_json(json!({
1981                                "ok": true,
1982                                "enabled": true,
1983                                "mode": mode.as_str(),
1984                                "access": a.iter().map(|x| json!({
1985                                    "hash": x.hash, "recall_count": x.recall_count, "last_ms": x.last_ms,
1986                                })).collect::<Vec<_>>(),
1987                                "queries": q.iter().map(|x| json!({
1988                                    "sample": x.sample, "run_count": x.run_count,
1989                                    "empty_count": x.empty_count,
1990                                })).collect::<Vec<_>>(),
1991                                "budget": {
1992                                    "sample_count": b.sample_count,
1993                                    "overflow_count": b.overflow_count,
1994                                },
1995                            }))
1996                        }
1997                        _ => ok_json(json!({"ok": false, "error": "telemetry read failed"})),
1998                    }
1999                }
2000            }
2001            ("POST", "/api/loop/run") => {
2002                let authz = self.facade.authz();
2003                if !authz.is_owner()
2004                    && !authz.allows(areev_core::authz::Verb::LoopRun, areev_loop::LOOP_NS)
2005                {
2006                    return ("403 Forbidden", "application/json",
2007                            br#"{"ok":false,"error":"AUT-E001: this session lacks loop.run"}"#.to_vec());
2008                }
2009                let mut sub = BorrowedSubstrate::new(&self.facade);
2010                // The trigger is recorded as co-creator on LLM/external
2011                // findings, so the same principal cannot later approve them.
2012                // In credential-map mode the actor IS the bound principal —
2013                // a request cannot claim an identity.
2014                let actor = if self.credentials.is_some() {
2015                    authz.principal().to_string()
2016                } else {
2017                    serde_json::from_slice::<Value>(body)
2018                        .ok()
2019                        .and_then(|v| v.get("actor").and_then(Value::as_str).map(str::to_string))
2020                        .unwrap_or_else(|| "user:console".to_string())
2021                };
2022                let opts = RunOptions { triggering_actor: Some(actor), ..Default::default() };
2023                match self.engine().run(&mut sub, &opts, now_ms()) {
2024                    Ok(res) => ok_json(json!({"ok": true, "run": res})),
2025                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
2026                }
2027            }
2028            ("POST", "/api/loop/review") => self.loop_review(body),
2029            ("POST", "/api/loop/apply") => self.loop_apply(body),
2030            ("POST", "/api/loop/rollback") => self.loop_rollback(body),
2031            ("POST", "/api/loop/config") => self.loop_config(body),
2032            ("POST", "/api/anon/config") => self.anon_config(body),
2033            _ => (
2034                "404 Not Found",
2035                "application/json",
2036                br#"{"ok":false,"error":"not found"}"#.to_vec(),
2037            ),
2038        }
2039    }
2040
2041    /// The console session's scopes derive from its grants (an owner
2042    /// session — today's only mode — holds all of them); actor
2043    /// `user:console` unless overridden, observer derived from the actor
2044    /// label, never from request text.
2045    fn loop_review(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
2046        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
2047        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
2048        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
2049        let bound = self.facade.authz();
2050        let actor = if self.credentials.is_some() {
2051            bound.principal().to_string()
2052        } else {
2053            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
2054        };
2055        let actor = actor.as_str();
2056        let decision = if req.get("decision").and_then(Value::as_str) == Some("reject") {
2057            Decision::Reject
2058        } else {
2059            Decision::Approve
2060        };
2061        let mut sub = BorrowedSubstrate::new(&self.facade);
2062        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
2063        let observer = areev_loop_adapter::observer_for_principal(actor);
2064        match self.engine().review(
2065            &mut sub, hash, decision, actor, observer, &scopes, because, now_ms(),
2066        ) {
2067            Ok(()) => ok_json(json!({"ok": true})),
2068            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
2069        }
2070    }
2071
2072    fn loop_apply(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
2073        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
2074        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
2075        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
2076        let bound = self.facade.authz();
2077        let actor = if self.credentials.is_some() {
2078            bound.principal().to_string()
2079        } else {
2080            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
2081        };
2082        let actor = actor.as_str();
2083        let allow_destructive = req.get("allow_destructive").and_then(Value::as_bool).unwrap_or(false);
2084        let mut sub = BorrowedSubstrate::new(&self.facade);
2085        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
2086        let observer = areev_loop_adapter::observer_for_principal(actor);
2087        let engine = self.engine();
2088        // A code or adapter revision applies only through its recorded gating
2089        // edge: `gating_run` names an eval run whose journaled `mg:eval_run`
2090        // summary becomes the evidence — the stats never come from the client.
2091        let gating = match req.get("gating_run").and_then(Value::as_str) {
2092            Some(run_id) => match engine.gating_evidence(&sub, hash, run_id) {
2093                Ok(g) => Some(g),
2094                Err(e) => {
2095                    return ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()}))
2096                }
2097            },
2098            None => None,
2099        };
2100        let applied = match &gating {
2101            Some(g) => engine.apply_gated(
2102                &mut sub, hash, actor, observer, &scopes, because, allow_destructive, g, now_ms(),
2103            ),
2104            None => engine.apply(
2105                &mut sub, hash, actor, observer, &scopes, because, allow_destructive, now_ms(),
2106            ),
2107        };
2108        match applied {
2109            Ok(applied) => ok_json(json!({"ok": true, "rollbackable": applied.rollbackable})),
2110            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
2111        }
2112    }
2113
2114    fn loop_rollback(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
2115        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
2116        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
2117        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
2118        let bound = self.facade.authz();
2119        let actor = if self.credentials.is_some() {
2120            bound.principal().to_string()
2121        } else {
2122            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
2123        };
2124        let actor = actor.as_str();
2125        let mut sub = BorrowedSubstrate::new(&self.facade);
2126        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
2127        let observer = areev_loop_adapter::observer_for_principal(actor);
2128        match self.engine().rollback(
2129            &mut sub, hash, actor, observer, &scopes, because, now_ms(),
2130        ) {
2131            Ok(()) => ok_json(json!({"ok": true})),
2132            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
2133        }
2134    }
2135
2136    /// Edit one analyzer's file-config from the Setup view. The body is
2137    /// `{analyzer_id, enabled?, severity_floor?, clear_floor?, params?,
2138    /// namespaces?}`; absent fields are left unchanged. The console holds all
2139    /// scopes (local root of trust), so `Admin` is satisfied; an unknown
2140    /// analyzer or bad param is a structured `ok:false` (not a 500).
2141    fn loop_config(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
2142        let id = serde_json::from_slice::<Value>(body)
2143            .ok()
2144            .and_then(|v| v.get("analyzer_id").and_then(Value::as_str).map(str::to_string))
2145            .unwrap_or_default();
2146        // The update reads the same body; the extra `analyzer_id` key is ignored.
2147        let update: areev_loop::AnalyzerConfigUpdate = serde_json::from_slice(body).unwrap_or_default();
2148        let mut sub = BorrowedSubstrate::new(&self.facade);
2149        match self.engine().set_analyzer_config(&mut sub, &id, update, &areev_loop_adapter::scopes_for(&self.facade.authz())) {
2150            Ok(cfg) => ok_json(json!({"ok": true, "config": cfg})),
2151            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
2152        }
2153    }
2154}
2155
2156impl UiServer {
2157    /// Declare or clear a per-namespace anonymization policy from the
2158    /// console (Connect → Settings). Rides the same write gate as every
2159    /// console POST (auth + Origin + body cap upstream); the policy itself
2160    /// validates fail-closed in the store.
2161    fn anon_config(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
2162        let v: Value = match serde_json::from_slice(body) {
2163            Ok(v) => v,
2164            Err(e) => return ok_json(json!({"ok": false, "error": e.to_string()})),
2165        };
2166        let Some(ns) = v.get("ns").and_then(Value::as_str).filter(|n| !n.trim().is_empty())
2167        else {
2168            return ok_json(json!({"ok": false, "error": "ns is required"}));
2169        };
2170        let result = if v.get("clear").and_then(Value::as_bool) == Some(true) {
2171            self.facade.with_store(|m| m.clear_anon_policy(ns))
2172        } else {
2173            match v.get("policy") {
2174                Some(policy) => {
2175                    let policy_json = policy.to_string();
2176                    self.facade.with_store(|m| m.set_anon_policy(ns, &policy_json))
2177                }
2178                None => {
2179                    return ok_json(json!({"ok": false, "error": "policy (object) or clear: true is required"}));
2180                }
2181            }
2182        };
2183        match result {
2184            Ok(()) => {
2185                let declared = self.facade.with_store(|m| m.anon_declared());
2186                ok_json(json!({"ok": true, "policies": declared
2187                    .iter()
2188                    .map(|(ns, mode)| json!({"ns": ns, "mode": mode}))
2189                    .collect::<Vec<_>>()}))
2190            }
2191            Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
2192        }
2193    }
2194}
2195
2196/// True when a `host[:port]` (or `[ipv6]:port`) authority names a loopback
2197/// host. Shared by the Origin drive-by check and the Host-header
2198/// (DNS-rebinding) check.
2199fn host_is_local(host_port: &str) -> bool {
2200    let host = if let Some(h) = host_port.strip_prefix('[') {
2201        h.split(']').next().unwrap_or("")
2202    } else {
2203        host_port.split(':').next().unwrap_or("")
2204    };
2205    matches!(host, "127.0.0.1" | "localhost" | "::1")
2206}
2207
2208/// True when an Origin header names a loopback host (any port, http/https).
2209fn origin_is_local(origin: &str) -> bool {
2210    let rest = origin
2211        .strip_prefix("http://")
2212        .or_else(|| origin.strip_prefix("https://"));
2213    let Some(rest) = rest else { return false };
2214    let host_port = rest.split('/').next().unwrap_or("");
2215    host_is_local(host_port)
2216}
2217
2218/// Normalize an origin (an `Origin` header value, or an operator-configured
2219/// `--allow-origin` entry) for EXACT comparison: lowercase, with a single
2220/// trailing `/` dropped. Nothing else — this only makes two spellings of the
2221/// same origin compare equal; it does not validate shape (the CLI's
2222/// `--allow-origin` parser does that at startup).
2223fn normalize_origin(origin: &str) -> String {
2224    let trimmed = origin.trim();
2225    trimmed.strip_suffix('/').unwrap_or(trimmed).to_ascii_lowercase()
2226}
2227
2228/// Redact a DISPLAY copy of a connection-string / file-path DB label
2229/// (issue #124): if `label` has a `scheme://[user[:pass]@]host...` shape and
2230/// the userinfo carries a password, replace the password with `***`.
2231/// Anything else — a plain file path (no `://`), a DSN with no userinfo, or
2232/// userinfo with no password — is returned byte-for-byte unchanged.
2233///
2234/// **DISPLAY ONLY.** The raw label is still what
2235/// `CredentialMap::resolve_for_memory` (`areev-core/src/authz.rs`) matches a
2236/// token's `memories` scope against via an exact string compare — never swap
2237/// in this redacted form at those call sites, or every `--auth FILE`
2238/// deployment that scopes a token to a Postgres memory silently breaks.
2239///
2240/// Hand-rolled (no URL crate, per the workspace's dependency-light policy):
2241/// only the AUTHORITY segment — between `://` and the first `/`, `?`, or `#`
2242/// that follows — is considered, and within it the LAST `@` is taken as the
2243/// userinfo delimiter. RFC 3986 allows a percent-encoded `@` in a password
2244/// and real passwords contain literal `@` too, so an earlier `@` is presumed
2245/// to be *inside* the password rather than a second delimiter; and a `:` or
2246/// `@` appearing later — in a query string, say — is outside the authority
2247/// entirely and is never mistaken for userinfo.
2248pub fn redact_dsn(label: &str) -> String {
2249    let Some(scheme_end) = label.find("://") else {
2250        return label.to_string();
2251    };
2252    let authority_start = scheme_end + 3;
2253    let rest = &label[authority_start..];
2254    let authority_len = rest.find(['/', '?', '#']).unwrap_or(rest.len());
2255    let authority = &rest[..authority_len];
2256    let Some(at) = authority.rfind('@') else {
2257        return label.to_string();
2258    };
2259    let userinfo = &authority[..at];
2260    let Some(colon) = userinfo.find(':') else {
2261        return label.to_string();
2262    };
2263    let user = &userinfo[..colon];
2264    let mut out = String::with_capacity(label.len());
2265    out.push_str(&label[..authority_start]);
2266    out.push_str(user);
2267    out.push_str(":***@");
2268    out.push_str(&authority[at + 1..]);
2269    out.push_str(&rest[authority_len..]);
2270    out
2271}
2272
2273fn ok_json(v: Value) -> (&'static str, &'static str, Vec<u8>) {
2274    ("200 OK", "application/json", v.to_string().into_bytes())
2275}
2276
2277fn run_api_err(msg: &str) -> (&'static str, &'static str, Vec<u8>) {
2278    (
2279        "400 Bad Request",
2280        "application/json",
2281        serde_json::json!({"ok": false, "error": msg}).to_string().into_bytes(),
2282    )
2283}
2284
2285/// True when a `POST /api/cal` body is a read-only statement. Classification
2286/// is delegated to `areev-cal`'s exhaustive [`areev_cal::classify`] module —
2287/// the single source of truth — so grammar growth cannot desynchronize this
2288/// gate (a keyword sniff lived here before and would have silently
2289/// misclassified any new statement). Fail closed: unparseable text is not
2290/// read-only.
2291fn cal_body_is_read_only(body: &[u8]) -> bool {
2292    let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
2293    let q = req.get("query").and_then(Value::as_str).unwrap_or("");
2294    areev_cal::classify::query_is_read_only(q)
2295}
2296
2297fn status_from_str(s: &str) -> Option<RecStatus> {
2298    match s {
2299        "pending" => Some(RecStatus::Pending),
2300        "approved" => Some(RecStatus::Approved),
2301        "rejected" => Some(RecStatus::Rejected),
2302        "applied" => Some(RecStatus::Applied),
2303        "rolled_back" => Some(RecStatus::RolledBack),
2304        "expired" => Some(RecStatus::Expired),
2305        _ => None, // includes "all"
2306    }
2307}
2308
2309fn rec_json(r: &areev_loop::Recommendation) -> Value {
2310    json!({
2311        "hash": r.hash,
2312        "status": r.status.as_str(),
2313        "severity": r.severity.as_str(),
2314        "analyzer": r.analyzer,
2315        "summary": r.summary.render(),
2316        "target_ref": r.target_ref,
2317        "destructive": r.destructive,
2318        "rollbackable": r.rollbackable,
2319        "evidence": r.evidence,
2320        // The Rule E1 pin, when present — the console reads it to know this
2321        // apply needs a recorded gating run (and which evalset to run).
2322        "evalset_hash": r.evalset_hash,
2323    })
2324}
2325
2326fn urldecode(s: &str) -> String {
2327    let mut out = Vec::new();
2328    let b = s.as_bytes();
2329    let mut i = 0;
2330    while i < b.len() {
2331        match b[i] {
2332            b'%' if i + 2 < b.len() + 1 && i + 2 < b.len() + 1 => {
2333                if i + 2 < b.len() + 1 && i + 2 < b.len() {
2334                    let hex = std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or("");
2335                    if let Ok(v) = u8::from_str_radix(hex, 16) {
2336                        out.push(v);
2337                        i += 3;
2338                        continue;
2339                    }
2340                }
2341                out.push(b[i]);
2342                i += 1;
2343            }
2344            b'+' => {
2345                out.push(b' ');
2346                i += 1;
2347            }
2348            c => {
2349                out.push(c);
2350                i += 1;
2351            }
2352        }
2353    }
2354    String::from_utf8_lossy(&out).to_string()
2355}
2356
2357fn html_escape(s: &str) -> String {
2358    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
2359}
2360
2361/// Constant-time byte comparison — avoids leaking the bearer token through
2362/// response timing. A length mismatch fails fast (token length is not secret).
2363fn ct_eq(a: &[u8], b: &[u8]) -> bool {
2364    if a.len() != b.len() {
2365        return false;
2366    }
2367    let mut diff = 0u8;
2368    for (x, y) in a.iter().zip(b.iter()) {
2369        diff |= x ^ y;
2370    }
2371    diff == 0
2372}
2373
2374/// Decode standard base64 (RFC 4648), enough for HTTP Basic credentials.
2375/// The one hand-rolled decoder lives in `areev_core::b64` (the trigger
2376/// evaluator shares it for connector blobs, #93).
2377fn base64_decode(s: &str) -> Option<Vec<u8>> {
2378    areev_core::b64::decode(s)
2379}
2380
2381/// Extract the password from an HTTP Basic credential (`base64("user:pass")`).
2382/// The console ignores the username and treats the password as the token.
2383/// Returns `None` if the value is not valid base64/UTF-8 or has no `:`.
2384fn basic_auth_password(b64: &str) -> Option<String> {
2385    let text = String::from_utf8(base64_decode(b64)?).ok()?;
2386    text.split_once(':').map(|(_user, pass)| pass.to_string())
2387}
2388
2389#[cfg(test)]
2390mod loop_route_tests {
2391    use super::UiServer;
2392    use areev_cal::AreevFacade;
2393    use areev_core::types::{Fact, Grain};
2394    use areev_store::Areev;
2395
2396    fn server(auth: Option<&str>) -> UiServer {
2397        let dir = tempfile::tempdir().unwrap();
2398        let path = dir.path().join("t.db");
2399        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
2400        // Two identical facts → a duplicate-consolidation recommendation.
2401        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller")).unwrap();
2402        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller")).unwrap();
2403        std::mem::forget(dir); // keep the file alive for the server's lifetime
2404        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2405        let s = UiServer::new(facade, "test".into());
2406        match auth {
2407            Some(t) => s.with_auth(t.to_string()),
2408            None => s,
2409        }
2410    }
2411
2412    fn text(r: &(&str, &str, Vec<u8>)) -> String {
2413        String::from_utf8_lossy(&r.2).to_string()
2414    }
2415
2416    #[test]
2417    fn token_less_console_is_read_only() {
2418        let s = server(None);
2419        // A loop mutation (run) is a write → 401.
2420        assert!(s.route("POST", "/api/loop/run", b"{}", None, None).0.starts_with("401"));
2421        // A write CAL → 401.
2422        let w = s.route("POST", "/api/cal", br#"{"query":"ADD fact SET subject=\"x\""}"#, None, None);
2423        assert!(w.0.starts_with("401"), "write CAL must be 401: {}", text(&w));
2424        // A read CAL → 200.
2425        let r = s.route("POST", "/api/cal", br#"{"query":"RECALL facts WHERE subject = \"acme\""}"#, None, None);
2426        assert!(r.0.starts_with("200"), "read CAL allowed: {}", text(&r));
2427        // Areev Loop reads stay open token-less.
2428        assert!(s.route("GET", "/api/loop/recommendations", b"", None, None).0.starts_with("200"));
2429    }
2430
2431    #[test]
2432    fn telemetry_endpoint_is_an_open_read() {
2433        let s = server(None);
2434        let r = s.route("GET", "/api/loop/telemetry", b"", None, None);
2435        assert!(r.0.starts_with("200"), "telemetry read open: {}", text(&r));
2436        let body = text(&r);
2437        assert!(body.contains("\"ok\":true"), "{body}");
2438        // The test store opens bare (telemetry off) → enabled:false.
2439        assert!(body.contains("\"enabled\":false"), "{body}");
2440    }
2441
2442    #[test]
2443    fn authenticated_run_review_apply_roundtrip() {
2444        let s = server(Some("tok"));
2445        let run = s.route("POST", "/api/loop/run", b"{}", Some("tok"), None);
2446        assert!(run.0.starts_with("200"), "run: {}", text(&run));
2447        assert!(text(&run).contains("\"ran\""));
2448
2449        let list = s.route("GET", "/api/loop/recommendations?status=pending", b"", Some("tok"), None);
2450        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
2451        let recs = v["recommendations"].as_array().unwrap();
2452        assert!(!recs.is_empty(), "at least one recommendation");
2453        let hash = recs[0]["hash"].as_str().unwrap().to_string();
2454
2455        let rev = s.route(
2456            "POST",
2457            "/api/loop/review",
2458            format!(r#"{{"hash":"{hash}","decision":"approve","because":"ok"}}"#).as_bytes(),
2459            Some("tok"),
2460            None,
2461        );
2462        assert!(text(&rev).contains("\"ok\":true"), "review: {}", text(&rev));
2463
2464        let ap = s.route(
2465            "POST",
2466            "/api/loop/apply",
2467            format!(r#"{{"hash":"{hash}","because":"go"}}"#).as_bytes(),
2468            Some("tok"),
2469            None,
2470        );
2471        assert!(text(&ap).contains("\"ok\":true"), "apply: {}", text(&ap));
2472    }
2473
2474    #[test]
2475    fn config_edit_toggles_analyzer_via_console() {
2476        let s = server(Some("tok"));
2477        // Token-less write → 401 (guarded like every POST).
2478        assert!(s.route("POST", "/api/loop/config", b"{}", None, None).0.starts_with("401"));
2479
2480        // Read the analyzers; pick one that is on by default.
2481        let list = s.route("GET", "/api/loop/analyzers", b"", Some("tok"), None);
2482        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
2483        let id = v["analyzers"]
2484            .as_array()
2485            .unwrap()
2486            .iter()
2487            .find(|x| x["enabled"] == true)
2488            .expect("some analyzer is on")["id"]
2489            .as_str()
2490            .unwrap()
2491            .to_string();
2492
2493        // Disable it via the console endpoint.
2494        let post = s.route(
2495            "POST",
2496            "/api/loop/config",
2497            format!(r#"{{"analyzer_id":"{id}","enabled":false}}"#).as_bytes(),
2498            Some("tok"),
2499            None,
2500        );
2501        assert!(text(&post).contains("\"ok\":true"), "config: {}", text(&post));
2502
2503        // It reads back disabled.
2504        let list2 = s.route("GET", "/api/loop/analyzers", b"", Some("tok"), None);
2505        let v2: serde_json::Value = serde_json::from_slice(&list2.2).unwrap();
2506        let now = v2["analyzers"]
2507            .as_array()
2508            .unwrap()
2509            .iter()
2510            .find(|x| x["id"] == id.as_str())
2511            .unwrap();
2512        assert_eq!(now["enabled"], false, "toggled off and persisted");
2513    }
2514
2515    #[test]
2516    fn self_approval_surfaces_lop_code() {
2517        let s = server(Some("tok"));
2518        s.route("POST", "/api/loop/run", b"{}", Some("tok"), None);
2519        let list = s.route("GET", "/api/loop/recommendations?status=pending", b"", Some("tok"), None);
2520        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
2521        let rec = &v["recommendations"].as_array().unwrap()[0];
2522        let hash = rec["hash"].as_str().unwrap();
2523        let analyzer = rec["analyzer"].as_str().unwrap();
2524        let creator = format!("engine:{analyzer}");
2525        // The engine actor approving its own proposal is blocked.
2526        let rev = s.route(
2527            "POST",
2528            "/api/loop/review",
2529            format!(r#"{{"hash":"{hash}","decision":"approve","because":"self","actor":"{creator}"}}"#).as_bytes(),
2530            Some("tok"),
2531            None,
2532        );
2533        assert!(text(&rev).contains("LOP-E021"), "self-approval blocked: {}", text(&rev));
2534    }
2535}
2536
2537#[cfg(test)]
2538mod security_tests {
2539    use super::{base64_decode, basic_auth_password, ct_eq, normalize_origin, redact_dsn};
2540
2541    #[test]
2542    fn ct_eq_matches_only_equal() {
2543        assert!(ct_eq(b"secret-token", b"secret-token"));
2544        assert!(!ct_eq(b"secret-token", b"secret-toker"));
2545        assert!(!ct_eq(b"secret", b"secret-token")); // length mismatch
2546        assert!(ct_eq(b"", b""));
2547    }
2548
2549    #[test]
2550    fn base64_decode_roundtrips_known_vectors() {
2551        // RFC 4648 test vectors (with and without padding).
2552        assert_eq!(base64_decode("").unwrap(), b"");
2553        assert_eq!(base64_decode("Zg==").unwrap(), b"f");
2554        assert_eq!(base64_decode("Zm8=").unwrap(), b"fo");
2555        assert_eq!(base64_decode("Zm9v").unwrap(), b"foo");
2556        assert_eq!(base64_decode("Zm9vYmFy").unwrap(), b"foobar");
2557        // padding is optional for us
2558        assert_eq!(base64_decode("Zg").unwrap(), b"f");
2559        // invalid characters are rejected
2560        assert!(base64_decode("****").is_none());
2561    }
2562
2563    #[test]
2564    fn basic_auth_extracts_password_ignoring_username() {
2565        // base64("areev:s3cret") and base64(":s3cret") both yield the token.
2566        assert_eq!(basic_auth_password("ZGVqYTpzM2NyZXQ=").as_deref(), Some("s3cret"));
2567        assert_eq!(basic_auth_password("OnMzY3JldA==").as_deref(), Some("s3cret"));
2568        // a password may itself contain ':' — only the first ':' splits.
2569        // base64("u:a:b") -> "a:b"
2570        assert_eq!(basic_auth_password("dTphOmI=").as_deref(), Some("a:b"));
2571        // no ':' at all → not a valid Basic credential
2572        assert_eq!(basic_auth_password("bm9jb2xvbg=="), None); // "nocolon"
2573        assert_eq!(basic_auth_password("****"), None); // not base64
2574    }
2575
2576    // ── redact_dsn (issue #124) ─────────────────────────────────────────
2577
2578    #[test]
2579    fn redact_dsn_hides_a_password() {
2580        assert_eq!(
2581            redact_dsn("postgresql://rounic:SUPERSECRET@pg-x:5432/rounic?sslmode=verify-full&schema=desk_invoice"),
2582            "postgresql://rounic:***@pg-x:5432/rounic?sslmode=verify-full&schema=desk_invoice",
2583        );
2584    }
2585
2586    #[test]
2587    fn redact_dsn_leaves_no_password_alone() {
2588        assert_eq!(redact_dsn("postgres://user@host:5432/db"), "postgres://user@host:5432/db");
2589    }
2590
2591    #[test]
2592    fn redact_dsn_leaves_no_userinfo_alone() {
2593        assert_eq!(redact_dsn("postgres://host:5432/db"), "postgres://host:5432/db");
2594    }
2595
2596    #[test]
2597    fn redact_dsn_leaves_a_plain_file_path_alone() {
2598        assert_eq!(redact_dsn("demo.db"), "demo.db");
2599        assert_eq!(redact_dsn("/var/lib/areev/demo.db"), "/var/lib/areev/demo.db");
2600    }
2601
2602    #[test]
2603    fn redact_dsn_hides_a_percent_encoded_password() {
2604        // %40 is an encoded '@' inside the password — the LITERAL '@' that
2605        // ends the authority is the one after it.
2606        assert_eq!(
2607            redact_dsn("postgres://user:pa%40ss@host:5432/db"),
2608            "postgres://user:***@host:5432/db",
2609        );
2610    }
2611
2612    #[test]
2613    fn redact_dsn_hides_a_password_with_a_literal_at_sign() {
2614        // The LAST '@' in the authority is the userinfo/host boundary, so a
2615        // literal '@' inside the password is presumed to be part of it.
2616        assert_eq!(
2617            redact_dsn("postgres://user:p@ss@host:5432/db"),
2618            "postgres://user:***@host:5432/db",
2619        );
2620    }
2621
2622    #[test]
2623    fn redact_dsn_ignores_colon_and_at_in_the_query_string() {
2624        assert_eq!(
2625            redact_dsn("postgres://user:pass@host:5432/db?options=-c%20foo:bar@baz"),
2626            "postgres://user:***@host:5432/db?options=-c%20foo:bar@baz",
2627        );
2628    }
2629
2630    #[test]
2631    fn redact_dsn_handles_empty_string() {
2632        assert_eq!(redact_dsn(""), "");
2633    }
2634
2635    // ── normalize_origin (issue #125) ───────────────────────────────────
2636
2637    #[test]
2638    fn normalize_origin_lowercases_and_drops_one_trailing_slash() {
2639        assert_eq!(normalize_origin("https://Console.Example.com"), "https://console.example.com");
2640        assert_eq!(normalize_origin("https://console.example.com/"), "https://console.example.com");
2641        assert_eq!(
2642            normalize_origin("HTTPS://Console.Example.com/"),
2643            "https://console.example.com",
2644        );
2645    }
2646}
2647
2648#[cfg(test)]
2649mod credential_route_tests {
2650    use super::UiServer;
2651    use areev_cal::AreevFacade;
2652    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
2653    use areev_core::types::{Fact, Grain};
2654    use areev_store::Areev;
2655
2656    /// The tuning seam over HTTP: an adapter recommendation applies only
2657    /// with `gating_run` in the POST body — evidence loaded from the
2658    /// journaled eval summary, never from the client — and the rec row
2659    /// carries `evalset_hash` so the console knows the apply is gated.
2660    #[test]
2661    fn loop_apply_honors_a_gating_run() {
2662        let dir = tempfile::tempdir().unwrap();
2663        let path = dir.path().join("g.db");
2664        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
2665        // The pin and a clean recorded gate run, as `areev eval` writes them.
2666        let evalset = store
2667            .add(
2668                &Fact::new("evalset:gate", "mg:evalset", "{\"name\":\"gate\",\"cases\":[]}")
2669                    .namespace("agent:harness")
2670                    .created_at(1_000),
2671            )
2672            .unwrap()
2673            .to_hex();
2674        store
2675            .add(
2676                &Fact::new(
2677                    &format!("evalset:{evalset}"),
2678                    "mg:eval_run",
2679                    "{\"run_id\":\"eval-1\",\"passed\":3,\"failed\":0}",
2680                )
2681                .namespace("agent:harness")
2682                .created_at(2_000),
2683            )
2684            .unwrap();
2685        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(3_000)).unwrap();
2686        std::mem::forget(dir);
2687        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2688        // Register an adapter with real lineage (a recorded corpus export).
2689        let manifest = facade
2690            .record_corpus_export("RECALL facts", "train.jsonl", None, 4_000, &[], &[])
2691            .unwrap()
2692            .to_hex();
2693        facade
2694            .record_adapter(
2695                r#"{"adapter":{"uri":"file:///tmp/a","sha256":"feed"},"base_model":"qwen3-4b","serves_as":"acme-support"}"#,
2696                &manifest,
2697                &evalset,
2698                5_000,
2699            )
2700            .unwrap();
2701        // Token mode: the shared secret is the implied local owner — the
2702        // token-less console is read-only by design.
2703        let s = UiServer::new(facade, "test".into()).with_auth("gate-token".into());
2704        let tok = Some("gate-token");
2705
2706        // Propose, then find the adapter rec — its row must carry the pin.
2707        let run = s.route("POST", "/api/loop/run", b"{}", tok, None);
2708        assert!(run.0.starts_with("200"), "{}", text(&run));
2709        let list = s.route("GET", "/api/loop/recommendations?status=pending", b"", tok, None);
2710        let rows: serde_json::Value = serde_json::from_str(&text(&list)).unwrap();
2711        let rec = rows["recommendations"]
2712            .as_array()
2713            .unwrap()
2714            .iter()
2715            .find(|r| r["analyzer"].as_str().unwrap_or("").contains("adapter_intake"))
2716            .unwrap_or_else(|| panic!("adapter_intake must propose: {rows}"));
2717        assert_eq!(rec["evalset_hash"], evalset.as_str(), "the row must carry the pin");
2718        let hash = rec["hash"].as_str().unwrap().to_string();
2719
2720        // Approve (the console's first POST), then: ungated apply refused,
2721        // a bad run id refused, the recorded run admits.
2722        let approve = format!(r#"{{"hash":"{hash}","decision":"approve","because":"reviewed"}}"#);
2723        let r = s.route("POST", "/api/loop/review", approve.as_bytes(), tok, None);
2724        assert!(text(&r).contains("\"ok\":true"), "{}", text(&r));
2725        let bare = format!(r#"{{"hash":"{hash}","because":"ship it"}}"#);
2726        let r = s.route("POST", "/api/loop/apply", bare.as_bytes(), tok, None);
2727        assert!(text(&r).contains("gating run"), "ungated must refuse: {}", text(&r));
2728        let bad = format!(r#"{{"hash":"{hash}","because":"ship","gating_run":"eval-nope"}}"#);
2729        let r = s.route("POST", "/api/loop/apply", bad.as_bytes(), tok, None);
2730        assert!(text(&r).contains("no recorded gate run"), "{}", text(&r));
2731        let good = format!(r#"{{"hash":"{hash}","because":"gated and green","gating_run":"eval-1"}}"#);
2732        let r = s.route("POST", "/api/loop/apply", good.as_bytes(), tok, None);
2733        assert!(text(&r).contains("\"ok\":true"), "gated apply failed: {}", text(&r));
2734    }
2735
2736    /// A server in credential-map mode: two env-referenced tokens, rights
2737    /// seeded as grant grains in the file itself.
2738    fn server() -> UiServer {
2739        std::env::set_var("AREEV_TEST_READER_TOK", "reader-secret");
2740        std::env::set_var("AREEV_TEST_WRITER_TOK", "writer-secret");
2741        let dir = tempfile::tempdir().unwrap();
2742        let path = dir.path().join("t.db");
2743        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
2744        store
2745            .add(&Fact::new("user:reader", REL_PERMITS, "read ON *").namespace(AUTHZ_NS).created_at(1_000))
2746            .unwrap();
2747        store
2748            .add(
2749                &Fact::new("agent:writer", REL_PERMITS, "read,write ON caller")
2750                    .namespace(AUTHZ_NS)
2751                    .created_at(2_000),
2752            )
2753            .unwrap();
2754        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(3_000)).unwrap();
2755        std::mem::forget(dir);
2756        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2757        let map = CredentialMap::from_json(
2758            r#"{"version":1,"tokens":[
2759                {"env":"AREEV_TEST_READER_TOK","principal":"user:reader"},
2760                {"env":"AREEV_TEST_WRITER_TOK","principal":"agent:writer"}
2761            ]}"#,
2762        )
2763        .unwrap();
2764        UiServer::new(facade, "test".into()).with_credentials(map)
2765    }
2766
2767    fn text(r: &(&str, &str, Vec<u8>)) -> String {
2768        String::from_utf8_lossy(&r.2).to_string()
2769    }
2770
2771    const READ: &[u8] = br#"{"query":"RECALL facts WHERE subject = \"acme\""}"#;
2772    const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
2773
2774    #[test]
2775    fn tokens_bind_principals_and_verbs_decide() {
2776        let s = server();
2777
2778        // The reader reads…
2779        let r = s.route("POST", "/api/cal", READ, Some("reader-secret"), None);
2780        assert!(r.0.starts_with("200"), "{}", text(&r));
2781        assert!(text(&r).contains("grains"));
2782        // …and cannot write.
2783        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
2784        assert!(text(&w).contains("AUT-E001"), "reader write must be refused: {}", text(&w));
2785
2786        // The writer writes.
2787        let w = s.route("POST", "/api/cal", WRITE, Some("writer-secret"), None);
2788        assert!(text(&w).contains("added"), "writer write must land: {}", text(&w));
2789
2790        // Sequential isolation: the very next reader request is still
2791        // read-only — nothing leaked from the writer's binding.
2792        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
2793        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
2794    }
2795
2796    #[test]
2797    fn anonymous_is_read_only_and_loop_run_is_verb_gated() {
2798        let s = server();
2799        // No token → anonymous: reads work…
2800        let r = s.route("POST", "/api/cal", READ, None, None);
2801        assert!(r.0.starts_with("200"), "{}", text(&r));
2802        assert!(text(&r).contains("grains"));
2803        // …writes are verb-refused…
2804        let w = s.route("POST", "/api/cal", WRITE, None, None);
2805        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
2806        // …and an unknown token is anonymous too, never an escalation.
2807        let w = s.route("POST", "/api/cal", WRITE, Some("stolen-guess"), None);
2808        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
2809
2810        // The analysis trigger needs loop.run — anonymous gets 403.
2811        let run = s.route("POST", "/api/loop/run", b"{}", None, None);
2812        assert!(run.0.starts_with("403"), "{}", text(&run));
2813    }
2814
2815    #[test]
2816    fn whoami_reports_the_bound_principal() {
2817        let s = server();
2818        let r = s.route("GET", "/api/whoami", b"", Some("reader-secret"), None);
2819        assert!(text(&r).contains("user:reader"), "{}", text(&r));
2820        assert!(text(&r).contains("credentials"));
2821        let r = s.route("GET", "/api/whoami", b"", None, None);
2822        assert!(text(&r).contains("anonymous"), "{}", text(&r));
2823    }
2824
2825    /// A credential map must not silently disable `--token-env`. Attaching
2826    /// one changes WHO a request is; the operator who also asked for a
2827    /// shared secret still gets authentication on every request.
2828    #[test]
2829    fn a_credential_map_does_not_disable_the_shared_secret() {
2830        let s = server().with_auth("console-token".into());
2831
2832        // No credential at all: refused, not dropped to `anonymous`.
2833        let r = s.route("POST", "/api/cal", READ, None, None);
2834        assert!(r.0.starts_with("401"), "{}", text(&r));
2835        let page = s.route("GET", "/", b"", None, None);
2836        assert!(page.0.starts_with("401"), "the console page is guarded too");
2837        // An unrecognized token is refused rather than downgraded.
2838        let r = s.route("POST", "/api/cal", READ, Some("stolen-guess"), None);
2839        assert!(r.0.starts_with("401"), "{}", text(&r));
2840
2841        // A map token still binds its principal and its verbs still decide.
2842        let r = s.route("POST", "/api/cal", READ, Some("reader-secret"), None);
2843        assert!(r.0.starts_with("200"), "{}", text(&r));
2844        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
2845        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
2846
2847        // The shared secret is the implied admin (docs/cal-all-you-need
2848        // -proposal.md §5.2b) — it keeps the owner session it always had.
2849        let w = s.route("POST", "/api/cal", WRITE, Some("console-token"), None);
2850        assert!(text(&w).contains("added"), "{}", text(&w));
2851    }
2852
2853    /// `RUN LOOP` through CAL is gated exactly as `POST /api/loop/run` is —
2854    /// otherwise the CAL surface is a way around the HTTP gate.
2855    #[test]
2856    fn run_loop_via_cal_is_verb_gated_like_the_route() {
2857        let s = server();
2858        let run = s.route("POST", "/api/loop/run", b"{}", None, None);
2859        assert!(run.0.starts_with("403"), "{}", text(&run));
2860        let cal = s.route("POST", "/api/cal", br#"{"query":"RUN LOOP"}"#, None, None);
2861        assert!(
2862            text(&cal).contains("AUT-E001"),
2863            "anonymous must not run the loop through CAL either: {}",
2864            text(&cal)
2865        );
2866    }
2867}
2868
2869#[cfg(test)]
2870mod namespace_route_tests {
2871    use super::UiServer;
2872    use areev_cal::AreevFacade;
2873    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
2874    use areev_core::types::{Fact, Grain};
2875    use areev_store::Areev;
2876
2877    fn text(r: &(&str, &str, Vec<u8>)) -> String {
2878        String::from_utf8_lossy(&r.2).to_string()
2879    }
2880
2881    /// `agent:writer` is granted read+write on `caller` only — nothing on
2882    /// `other`, nothing on the audit namespace.
2883    fn restricted_server() -> UiServer {
2884        std::env::set_var("AREEV_TEST_NS_WRITER_TOK", "writer-secret");
2885        let dir = tempfile::tempdir().unwrap();
2886        let path = dir.path().join("t.db");
2887        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
2888        store
2889            .add(&Fact::new("agent:writer", REL_PERMITS, "read,write ON caller").namespace(AUTHZ_NS).created_at(1_000))
2890            .unwrap();
2891        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(2_000)).unwrap();
2892        store.add(&Fact::new("bob", "role", "admin").namespace("other").created_at(3_000)).unwrap();
2893        std::mem::forget(dir);
2894        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2895        let map = CredentialMap::from_json(
2896            r#"{"version":1,"tokens":[{"env":"AREEV_TEST_NS_WRITER_TOK","principal":"agent:writer"}]}"#,
2897        )
2898        .unwrap();
2899        UiServer::new(facade, "test".into()).with_credentials(map)
2900    }
2901
2902    /// Unbound local open — the implicit owner, unrestricted on every
2903    /// namespace, same as a plain `areev ui` with no `--auth`.
2904    fn owner_server() -> UiServer {
2905        let dir = tempfile::tempdir().unwrap();
2906        let path = dir.path().join("t.db");
2907        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
2908        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(1_000)).unwrap();
2909        store.add(&Fact::new("bob", "role", "admin").namespace("other").created_at(2_000)).unwrap();
2910        std::mem::forget(dir);
2911        UiServer::new(AreevFacade::with_session(store, Some("caller".into()), None), "t".into())
2912    }
2913
2914    #[test]
2915    fn namespaces_route_hides_what_the_principal_cannot_read() {
2916        let s = restricted_server();
2917        let r = s.route("GET", "/api/namespaces", b"", Some("writer-secret"), None);
2918        let body = text(&r);
2919        assert!(body.contains("\"caller\""), "granted namespace must be listed: {body}");
2920        assert!(!body.contains("\"other\""), "ungranted namespace must not be listed: {body}");
2921        assert!(!body.contains(AUTHZ_NS), "the audit namespace must not leak either: {body}");
2922    }
2923
2924    #[test]
2925    fn namespaces_route_lists_everything_for_the_owner() {
2926        let s = owner_server();
2927        let r = s.route("GET", "/api/namespaces", b"", None, None);
2928        let body = text(&r);
2929        assert!(body.contains("\"caller\"") && body.contains("\"other\""), "{body}");
2930    }
2931
2932    #[test]
2933    fn browse_ns_param_is_read_gated_for_a_restricted_principal() {
2934        let s = restricted_server();
2935        let ok = s.route("GET", "/api/browse?ns=caller", b"", Some("writer-secret"), None);
2936        assert!(text(&ok).contains("\"ok\":true"), "their own granted namespace must work: {}", text(&ok));
2937
2938        let denied = s.route("GET", "/api/browse?ns=other", b"", Some("writer-secret"), None);
2939        let body = text(&denied);
2940        assert!(body.contains("\"ok\":false"), "an ungranted namespace must be refused, not silently emptied: {body}");
2941    }
2942
2943    #[test]
2944    fn browse_ns_star_requires_owner() {
2945        let s = restricted_server();
2946        let r = s.route("GET", "/api/browse?ns=*", b"", Some("writer-secret"), None);
2947        assert!(text(&r).contains("\"ok\":false"), "a restricted principal must not get the unfiltered view: {}", text(&r));
2948
2949        let owner = owner_server();
2950        let r2 = owner.route("GET", "/api/browse?ns=*", b"", None, None);
2951        let body2 = text(&r2);
2952        assert!(body2.contains("\"ok\":true"), "the owner session may lift the filter: {body2}");
2953        assert!(body2.contains("\"caller\"") && body2.contains("\"other\""), "{body2}");
2954    }
2955
2956    #[test]
2957    fn browse_without_ns_param_keeps_original_session_default_behavior() {
2958        let s = owner_server();
2959        let r = s.route("GET", "/api/browse", b"", None, None);
2960        let body = text(&r);
2961        assert!(body.contains("\"caller\""), "{body}");
2962        assert!(!body.contains("\"other\""), "omitting ?ns must behave exactly as before this feature existed: {body}");
2963    }
2964}
2965
2966#[cfg(test)]
2967mod builder_tests {
2968    use super::UiServer;
2969    use areev_cal::AreevFacade;
2970    use areev_store::Areev;
2971
2972    fn server() -> UiServer {
2973        let dir = tempfile::tempdir().unwrap();
2974        let path = dir.path().join("t.db");
2975        let store = Areev::open(path.to_str().unwrap()).unwrap();
2976        std::mem::forget(dir);
2977        UiServer::new(AreevFacade::with_session(store, Some("caller".into()), None), "t".into())
2978    }
2979
2980    /// `areev ui --no-destructive-ops --policy FILE` calls these in this
2981    /// order. A later builder must not re-enable destruction the operator
2982    /// turned off — the console was announced as read-only.
2983    #[test]
2984    fn attaching_a_loop_policy_preserves_the_destructive_cap() {
2985        let s = server()
2986            .allow_destructive_ops(false)
2987            .with_loop_policy(areev_loop::Policy::default());
2988        let r = s.route(
2989            "POST",
2990            "/api/cal",
2991            br#"{"query":"FORGET sha256:684c6c9bda818630a870119d0726e4d242ed537af061658ef6f3acb158a2c67d"}"#,
2992            None,
2993            None,
2994        );
2995        let body = String::from_utf8_lossy(&r.2).to_string();
2996        assert!(
2997            body.contains("--no-destructive-ops") || r.0.starts_with("401"),
2998            "destruction must stay disabled: {body}"
2999        );
3000    }
3001}
3002
3003#[cfg(test)]
3004mod run_api_tests {
3005    use super::UiServer;
3006    use areev_cal::AreevFacade;
3007    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
3008    use areev_core::types::{Fact, Grain, Tool, ToolKind, Workflow};
3009    use areev_store::Areev;
3010    use std::sync::Arc;
3011
3012    /// A server whose file holds a PARKED run (Client-gated approve node) —
3013    /// the HITL queue's fixture. Returns (server, ask id).
3014    fn parked_server() -> (UiServer, String) {
3015        std::env::set_var("AREEV_RUN_OFFICER_TOK", "officer-secret");
3016        std::env::set_var("AREEV_RUN_STARTER_TOK", "starter-secret");
3017        let dir = tempfile::tempdir().unwrap();
3018        let path = dir.path().join("t.db");
3019        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
3020        for (who, what) in [
3021            ("user:officer", "read,run.respond ON ops"),
3022            ("user:starter", "read ON ops"),
3023        ] {
3024            store
3025                .add(&Fact::new(who, REL_PERMITS, what).namespace(AUTHZ_NS).created_at(900))
3026                .unwrap();
3027        }
3028        std::mem::forget(dir);
3029        let facade = Arc::new(AreevFacade::with_session(store, Some("ops".into()), None));
3030
3031        // Seed + run the plan to the park with a scripted runner.
3032        let (wf, _g, _a) = facade
3033            .with_store(|m| {
3034                let greet = Tool::new("greet")
3035                    .kind(ToolKind::Definition)
3036                    .tool_description("t")
3037                    .created_at(500)
3038                    .namespace("ops");
3039                let gh = m.add(&greet)?;
3040                let approve = Tool::new("approve")
3041                    .kind(ToolKind::Definition)
3042                    .tool_description("human approves")
3043                    .executor_kind(areev_core::types::ExecutorKind::Client)
3044                    .created_at(501)
3045                    .namespace("ops");
3046                let ah = m.add(&approve)?;
3047                let wf = Workflow::new(vec!["greet".into(), "approve".into()])
3048                    .edge("greet", "approve")
3049                    .bind("greet", &gh.to_hex())
3050                    .bind("approve", &ah.to_hex())
3051                    .created_at(502)
3052                    .namespace("ops");
3053                let wh = m.add(&wf)?;
3054                Ok::<_, areev_core::error::AreevError>((wh, gh, ah))
3055            })
3056            .unwrap();
3057        struct Ok1;
3058        impl areev_run::HostToolExecutor for Ok1 {
3059            fn execute(
3060                &self,
3061                t: &str,
3062                _h: &str,
3063                _i: &serde_json::Value,
3064                _k: &str,
3065            ) -> areev_run::ExecResult {
3066                areev_run::ExecResult::Ok(serde_json::json!({t.to_string(): true}))
3067            }
3068        }
3069        let runner = areev_run::Runner {
3070            facade: Arc::clone(&facade),
3071            clock: Arc::new(areev_run::ScriptedClock::new(
3072                (0..100).map(|i| 1_758_000_000_000 + i * 10).collect(),
3073            )),
3074            executor: Arc::new(Ok1),
3075            llm: None,
3076            observer: None,
3077            ns: "ops".into(),
3078            principal: "user:starter".into(),
3079        };
3080        let session = runner
3081            .start(&wf, "hitl-1", serde_json::json!({}), &areev_run::RunOptions {
3082                workers: 1,
3083                ..Default::default()
3084            })
3085            .unwrap();
3086        let areev_run::RunSession::Parked { envelope, .. } = session else {
3087            panic!("expected park")
3088        };
3089        let ask = envelope["asks"][0]["tool_call_id"].as_str().unwrap().to_string();
3090
3091        // Rebuild a facade-owning server over the SAME file is impossible
3092        // (single writer) — hand the server the same Arc'd facade via the
3093        // Arc-aware constructor path: UiServer::new takes AreevFacade, so
3094        // we build the server FIRST in real deployments; here we reuse the
3095        // internal Arc through a second UiServer field write. Instead:
3096        // drop the runner (facade Arc count drops) and unwrap.
3097        drop(runner);
3098        let facade = Arc::try_unwrap(facade).unwrap_or_else(|_| panic!("facade still shared"));
3099        let map = CredentialMap::from_json(
3100            r#"{"version":1,"tokens":[
3101                {"env":"AREEV_RUN_OFFICER_TOK","principal":"user:officer"},
3102                {"env":"AREEV_RUN_STARTER_TOK","principal":"user:starter"}
3103            ]}"#,
3104        )
3105        .unwrap();
3106        let server = UiServer::new(facade, "test".into())
3107            .with_auth("shared-console-secret".into())
3108            .with_credentials(map);
3109        (server, ask)
3110    }
3111
3112    fn body(run_id: &str, ask: &str) -> Vec<u8> {
3113        serde_json::json!({"run_id": run_id, "tool_call_id": ask, "result": {"approved": true}})
3114            .to_string()
3115            .into_bytes()
3116    }
3117
3118    #[test]
3119    fn shared_token_approvals_are_refused_and_principals_approve() {
3120        let (s, ask) = parked_server();
3121
3122        // The HITL queue is visible.
3123        let r = s.route("GET", "/api/run/list", b"", Some("shared-console-secret"), None);
3124        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
3125        let r = s.route(
3126            "GET",
3127            "/api/run/inspect?run_id=hitl-1",
3128            b"",
3129            Some("shared-console-secret"),
3130            None,
3131        );
3132        assert!(String::from_utf8_lossy(&r.2).contains(&ask), "ask visible in inspect");
3133
3134        // 1. The SHARED console secret cannot approve — identity is the point.
3135        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("shared-console-secret"), None);
3136        assert!(r.0.starts_with("403"), "shared-token approval must refuse: {}", r.0);
3137
3138        // 2. The STARTER's own credential cannot approve their own run
3139        //    (separation of duties, enforced by the runtime).
3140        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("starter-secret"), None);
3141        let text = String::from_utf8_lossy(&r.2).to_string();
3142        assert!(text.contains("responder") || text.contains("RUN-E012"), "{text}");
3143
3144        // 3. The officer's principal-bound credential approves.
3145        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("officer-secret"), None);
3146        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
3147        assert!(String::from_utf8_lossy(&r.2).contains("user:officer"));
3148
3149        // 4. The kill switch keeps its low bar: shared token may cancel.
3150        let r = s.route(
3151            "POST",
3152            "/api/run/cancel",
3153            br#"{"run_id":"hitl-1","because":"test brake"}"#,
3154            Some("shared-console-secret"),
3155            None,
3156        );
3157        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
3158    }
3159
3160    /// [A0] The approval trust floor. `user:officer` holds `run.respond ON
3161    /// ops` in the FILE, so the grants are identical whichever way the
3162    /// identity arrives — which is exactly the point. What differs is the
3163    /// PROOF: a credential-map token is a per-principal secret; an SSO header
3164    /// is trusted via one shared, fleet-wide proxy secret that lets its
3165    /// holder assert any approver. The default refuses the weaker proof.
3166    #[test]
3167    fn proxy_asserted_identities_cannot_approve_by_default() {
3168        let (s, ask) = parked_server();
3169        let s = s.with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>);
3170
3171        // The SSO identity is a GRANTED principal and still cannot approve.
3172        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), None, Some("user:officer"));
3173        assert!(
3174            r.0.starts_with("403"),
3175            "proxy-asserted approval must refuse by default: {} {}",
3176            r.0,
3177            String::from_utf8_lossy(&r.2)
3178        );
3179        let text = String::from_utf8_lossy(&r.2).to_string();
3180        assert!(
3181            text.contains("--sso-approvals"),
3182            "the refusal must name the flag that lifts it: {text}"
3183        );
3184
3185        // Reviewing is unaffected — SSO identities keep every read.
3186        let r = s.route("GET", "/api/run/list", b"", None, Some("user:officer"));
3187        assert!(r.0.starts_with("200"), "SSO identities may still review: {}", r.0);
3188
3189        // And the SAME principal, proven by its own credential, approves.
3190        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("officer-secret"), None);
3191        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
3192    }
3193
3194    /// [A0] `--sso-approvals allow` is the operator accepting that trade-off
3195    /// explicitly. Nothing else changes: the same identity, the same file
3196    /// grants, the same runtime separation-of-duties check behind it.
3197    #[test]
3198    fn sso_approvals_allow_opts_in_to_proxy_asserted_approvals() {
3199        let (s, ask) = parked_server();
3200        let s = s
3201            .with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>)
3202            .with_sso_approvals(true);
3203
3204        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), None, Some("user:officer"));
3205        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
3206        assert!(String::from_utf8_lossy(&r.2).contains("user:officer"));
3207    }
3208
3209    /// [A2] Groups → principals, so SSO scales without a grant grain per
3210    /// person — and the precedence that makes it safe: an identity with its
3211    /// own grants outranks its group, so adding a groups header can never
3212    /// narrow someone who already had rights.
3213    #[test]
3214    fn groups_resolve_to_principals_but_never_outrank_an_identity() {
3215        let (s, _ask) = parked_server();
3216        // `user:officer` is granted in the file; `role:reviewer` is not a
3217        // credential, only a group target.
3218        let map = CredentialMap::from_json(
3219            r#"{"version":1,
3220                "tokens":[{"env":"AREEV_RUN_OFFICER_TOK","principal":"user:officer","id":"off"}],
3221                "groups":{"Engineering":"user:officer"}}"#,
3222        )
3223        .unwrap();
3224        let s = s
3225            .with_credentials(map)
3226            .with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>)
3227            .with_sso_groups_header("x-forwarded-groups");
3228
3229        // An UNGRANTED identity in a mapped group inherits the group's
3230        // principal — the whole point of the feature.
3231        let r = s.route_with_groups(
3232            "GET",
3233            "/api/whoami",
3234            b"",
3235            None,
3236            Some("user:newhire@example.com"),
3237            Some("platform,Engineering"),
3238        );
3239        let text = String::from_utf8_lossy(&r.2).to_string();
3240        assert!(text.contains("user:officer"), "group should resolve: {text}");
3241        assert!(text.contains(r#""identity_source":"sso-group""#), "{text}");
3242
3243        // Case-insensitive: directories are inconsistent, and a mapping that
3244        // misses on case would fail OPEN into the identity's own (empty)
3245        // grants.
3246        let r = s.route_with_groups(
3247            "GET", "/api/whoami", b"", None, Some("user:newhire@example.com"), Some("ENGINEERING"),
3248        );
3249        assert!(String::from_utf8_lossy(&r.2).contains("user:officer"));
3250
3251        // An identity that IS granted keeps its own principal, group or not.
3252        let r = s.route_with_groups(
3253            "GET", "/api/whoami", b"", None, Some("user:officer"), Some("Engineering"),
3254        );
3255        let text = String::from_utf8_lossy(&r.2).to_string();
3256        assert!(text.contains(r#""identity_source":"sso""#), "identity outranks group: {text}");
3257
3258        // An unmapped group resolves to nothing and the identity stands.
3259        let r = s.route_with_groups(
3260            "GET", "/api/whoami", b"", None, Some("user:newhire@example.com"), Some("sales"),
3261        );
3262        assert!(String::from_utf8_lossy(&r.2).contains("user:newhire@example.com"));
3263    }
3264
3265    /// [A2] A role is not an approver. This refusal has no flag of its own —
3266    /// `--sso-approvals allow` does not lift it — because an audit record
3267    /// reading "role:eng approved" names nobody who can be asked why.
3268    #[test]
3269    fn group_derived_principals_can_never_approve() {
3270        let (s, ask) = parked_server();
3271        let map = CredentialMap::from_json(
3272            r#"{"version":1,
3273                "tokens":[{"env":"AREEV_RUN_OFFICER_TOK","principal":"user:officer","id":"off"}],
3274                "groups":{"approvers":"user:officer"}}"#,
3275        )
3276        .unwrap();
3277        let s = s
3278            .with_credentials(map)
3279            .with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>)
3280            .with_sso_groups_header("x-forwarded-groups")
3281            // Even with the A0 opt-in explicitly granted.
3282            .with_sso_approvals(true);
3283
3284        let r = s.route_with_groups(
3285            "POST",
3286            "/api/run/respond",
3287            &body("hitl-1", &ask),
3288            None,
3289            Some("user:newhire@example.com"),
3290            Some("approvers"),
3291        );
3292        assert!(r.0.starts_with("403"), "{} {}", r.0, String::from_utf8_lossy(&r.2));
3293        let text = String::from_utf8_lossy(&r.2).to_string();
3294        assert!(text.contains("role"), "the refusal must say why: {text}");
3295    }
3296
3297    /// [A2] The prefix keeps IdP-sourced principals visibly distinct from
3298    /// local ones everywhere they land.
3299    #[test]
3300    fn the_principal_prefix_is_stamped_on_proxy_asserted_identities() {
3301        let (s, _ask) = parked_server();
3302        let s = s
3303            .with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>)
3304            .with_sso_principal_prefix("sso:");
3305
3306        let r = s.route("GET", "/api/whoami", b"", None, Some("pat@example.com"));
3307        assert!(String::from_utf8_lossy(&r.2).contains("sso:pat@example.com"), "{}", String::from_utf8_lossy(&r.2));
3308
3309        // Idempotent: an identity the proxy already prefixed is not
3310        // double-stamped into a different principal than the grant names.
3311        let r = s.route("GET", "/api/whoami", b"", None, Some("sso:pat@example.com"));
3312        let text = String::from_utf8_lossy(&r.2).to_string();
3313        assert!(text.contains("sso:pat@example.com"), "{text}");
3314        assert!(!text.contains("sso:sso:"), "must not double-stamp: {text}");
3315    }
3316
3317    /// [A0] `whoami` tells an approver where they stand BEFORE they try to
3318    /// approve — a console that only discovers this at the 403 is a console
3319    /// that discovers it mid-incident.
3320    #[test]
3321    fn whoami_reports_identity_provenance_and_approval_capability() {
3322        let (s, _ask) = parked_server();
3323        let s = s.with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>);
3324
3325        let r = s.route("GET", "/api/whoami", b"", None, Some("user:officer"));
3326        let text = String::from_utf8_lossy(&r.2).to_string();
3327        assert!(text.contains(r#""identity_source":"sso""#), "{text}");
3328        assert!(text.contains(r#""may_approve":false"#), "{text}");
3329
3330        let r = s.route("GET", "/api/whoami", b"", Some("officer-secret"), None);
3331        let text = String::from_utf8_lossy(&r.2).to_string();
3332        assert!(text.contains(r#""identity_source":"credential""#), "{text}");
3333        assert!(text.contains(r#""may_approve":true"#), "{text}");
3334    }
3335}
3336
3337#[cfg(test)]
3338mod memory_scoped_token_tests {
3339    use super::UiServer;
3340    use areev_cal::AreevFacade;
3341    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
3342    use areev_core::types::{Fact, Grain};
3343    use areev_store::Areev;
3344
3345    /// The enterprise-plane rule: one auth file, per-memory token
3346    /// scopes — a token listed for memory A is an UNKNOWN token on
3347    /// memory B's server.
3348    #[test]
3349    fn memory_scoped_tokens_do_not_cross_memories() {
3350        std::env::set_var("AREEV_SCOPED_TOK", "scoped-secret");
3351        let map_json = r#"{"version":1,"tokens":[
3352            {"env":"AREEV_SCOPED_TOK","principal":"agent:sync","memories":["memory-a"]}
3353        ]}"#;
3354        let server_for = |label: &str| {
3355            let dir = tempfile::tempdir().unwrap();
3356            let mut store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3357            store
3358                .add(
3359                    &Fact::new("agent:sync", REL_PERMITS, "read,write ON caller")
3360                        .namespace(AUTHZ_NS)
3361                        .created_at(1_000),
3362                )
3363                .unwrap();
3364            store
3365                .add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(2_000))
3366                .unwrap();
3367            std::mem::forget(dir);
3368            let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3369            UiServer::new(facade, label.into())
3370                .with_credentials(CredentialMap::from_json(map_json).unwrap())
3371        };
3372        const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
3373
3374        // On memory-a the token authenticates and its grants let the write
3375        // through (no authorization refusal in the CAL payload).
3376        let a = server_for("memory-a");
3377        let r = a.route("POST", "/api/cal", WRITE, Some("scoped-secret"), None);
3378        let text = String::from_utf8_lossy(&r.2).to_string();
3379        assert!(r.0.starts_with("200") && !text.contains("AUT-E001"), "{text}");
3380
3381        // On memory-b the SAME token is an unknown credential: the request
3382        // runs as anonymous and the write is refused (AUT-E001 rides the
3383        // CAL payload — the console surfaces statement results in-band).
3384        let b = server_for("memory-b");
3385        let r = b.route("POST", "/api/cal", WRITE, Some("scoped-secret"), None);
3386        let text = String::from_utf8_lossy(&r.2).to_string();
3387        assert!(
3388            text.contains("AUT-E001") && text.contains("anonymous"),
3389            "scoped token must not cross memories: {text}"
3390        );
3391
3392        // An auth file with an EMPTY memories scope refuses to load.
3393        assert!(CredentialMap::from_json(
3394            r#"{"version":1,"tokens":[{"env":"AREEV_SCOPED_TOK","principal":"x","memories":[]}]}"#
3395        )
3396        .is_err());
3397    }
3398}
3399
3400#[cfg(all(test, feature = "tls"))]
3401mod tls_tests {
3402    use super::UiServer;
3403    use areev_cal::AreevFacade;
3404    use areev_store::Areev;
3405    use std::io::{Read, Write};
3406
3407    fn self_signed(dir: &std::path::Path) -> Option<(String, String)> {
3408        let cert = dir.join("cert.pem");
3409        let key = dir.join("key.pem");
3410        let status = std::process::Command::new("openssl")
3411            .args([
3412                "req", "-x509", "-newkey", "rsa:2048", "-nodes",
3413                "-keyout", key.to_str().unwrap(), "-out", cert.to_str().unwrap(),
3414                "-days", "1", "-subj", "/CN=localhost",
3415                "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1",
3416                "-addext", "basicConstraints=critical,CA:FALSE",
3417            ])
3418            .stdout(std::process::Stdio::null())
3419            .stderr(std::process::Stdio::null())
3420            .status();
3421        match status {
3422            Ok(s) if s.success() => Some((
3423                cert.to_str().unwrap().to_string(),
3424                key.to_str().unwrap().to_string(),
3425            )),
3426            _ => None, // no openssl on this host: the CI leg covers it
3427        }
3428    }
3429
3430    /// The §3.2 gate: a TLS round-trip succeeds, and a PLAINTEXT client on
3431    /// the same listener is refused (no silent downgrade).
3432    #[test]
3433    fn tls_round_trip_and_no_plaintext_downgrade() {
3434        let dir = tempfile::tempdir().unwrap();
3435        let Some((cert, key)) = self_signed(dir.path()) else {
3436            eprintln!("skipping: no openssl binary");
3437            return;
3438        };
3439        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3440        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3441        let server = UiServer::new(facade, "tls-test".into())
3442            .with_tls(&cert, &key)
3443            .unwrap();
3444        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3445        let addr = listener.local_addr().unwrap();
3446        let handle = std::thread::spawn(move || {
3447            // Two connections: the TLS client, then the plaintext prober.
3448            for _ in 0..2 {
3449                if let Ok((s, _)) = listener.accept() {
3450                    let _ = server.handle(s);
3451                }
3452            }
3453        });
3454
3455        // 1. TLS round-trip: trust exactly our self-signed cert.
3456        let mut roots = rustls::RootCertStore::empty();
3457        {
3458            use rustls::pki_types::pem::PemObject;
3459            for c in rustls::pki_types::CertificateDer::pem_file_iter(&cert).unwrap() {
3460                roots.add(c.unwrap()).unwrap();
3461            }
3462        }
3463        let config = std::sync::Arc::new(
3464            rustls::ClientConfig::builder()
3465                .with_root_certificates(roots)
3466                .with_no_client_auth(),
3467        );
3468        let name = rustls::pki_types::ServerName::try_from("localhost").unwrap();
3469        let session = rustls::ClientConnection::new(config, name).unwrap();
3470        let tcp = std::net::TcpStream::connect(addr).unwrap();
3471        let mut tls = rustls::StreamOwned::new(session, tcp);
3472        tls.write_all(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")
3473            .unwrap();
3474        let mut response = String::new();
3475        let _ = tls.read_to_string(&mut response);
3476        assert!(response.starts_with("HTTP/1.1 200"), "{}", &response[..response.len().min(120)]);
3477        assert!(response.contains("Areev"), "console served over TLS");
3478
3479        // 2. No downgrade: plaintext HTTP on the TLS listener gets a
3480        // handshake failure, never a page.
3481        let mut plain = std::net::TcpStream::connect(addr).unwrap();
3482        plain
3483            .write_all(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")
3484            .unwrap();
3485        let mut buf = Vec::new();
3486        let _ = plain.read_to_end(&mut buf);
3487        let text = String::from_utf8_lossy(&buf);
3488        assert!(
3489            !text.contains("HTTP/1.1 200"),
3490            "plaintext must not be served on a TLS listener: {text}"
3491        );
3492        handle.join().unwrap();
3493    }
3494
3495    /// `with_tls` composes with `with_auth` — `with_auth` only sets the
3496    /// token/auth_all fields, not the connection layer, so an authenticated
3497    /// console terminates TLS identically to an open one. Pins the CLI
3498    /// wiring that lets `areev ui --token-env VAR --tls-cert ... --tls-key
3499    /// ...` work, not just `areev ui --tls-cert ...`.
3500    #[test]
3501    fn an_authenticated_console_terminates_tls_the_same_way() {
3502        let dir = tempfile::tempdir().unwrap();
3503        let Some((cert, key)) = self_signed(dir.path()) else {
3504            eprintln!("skipping: no openssl binary");
3505            return;
3506        };
3507        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3508        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3509        let server = UiServer::new(facade, "auth-tls-test".into())
3510            .with_auth("console-token".into())
3511            .with_tls(&cert, &key)
3512            .unwrap();
3513        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3514        let addr = listener.local_addr().unwrap();
3515        let handle = std::thread::spawn(move || {
3516            if let Ok((s, _)) = listener.accept() {
3517                let _ = server.handle(s);
3518            }
3519        });
3520
3521        let mut roots = rustls::RootCertStore::empty();
3522        {
3523            use rustls::pki_types::pem::PemObject;
3524            for c in rustls::pki_types::CertificateDer::pem_file_iter(&cert).unwrap() {
3525                roots.add(c.unwrap()).unwrap();
3526            }
3527        }
3528        let config = std::sync::Arc::new(
3529            rustls::ClientConfig::builder()
3530                .with_root_certificates(roots)
3531                .with_no_client_auth(),
3532        );
3533        let name = rustls::pki_types::ServerName::try_from("localhost").unwrap();
3534        let session = rustls::ClientConnection::new(config, name).unwrap();
3535        let tcp = std::net::TcpStream::connect(addr).unwrap();
3536        let mut tls = rustls::StreamOwned::new(session, tcp);
3537        tls.write_all(
3538            b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\
3539              Authorization: Bearer console-token\r\nConnection: close\r\n\r\n",
3540        )
3541        .unwrap();
3542        let mut response = String::new();
3543        let _ = tls.read_to_string(&mut response);
3544        assert!(
3545            response.starts_with("HTTP/1.1 200"),
3546            "an authenticated console should terminate TLS like an open one: {}",
3547            &response[..response.len().min(120)]
3548        );
3549        handle.join().unwrap();
3550    }
3551}
3552
3553#[cfg(test)]
3554mod sso_tests {
3555    use super::UiServer;
3556    use areev_cal::AreevFacade;
3557    use areev_core::authz::{AUTHZ_NS, REL_PERMITS};
3558    use areev_core::types::{Fact, Grain};
3559    use areev_store::Areev;
3560    use std::io::{Read, Write};
3561
3562    const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
3563
3564    fn sso_server() -> UiServer {
3565        sso_server_with("proxy-secret", None)
3566    }
3567
3568    /// The same server mid-rotation: `proxy-secret` deployed, `next` incoming.
3569    fn sso_server_rotating(next: Option<&str>) -> UiServer {
3570        sso_server_with("proxy-secret", next)
3571    }
3572
3573    fn sso_server_with(secret: &str, next: Option<&str>) -> UiServer {
3574        let dir = tempfile::tempdir().unwrap();
3575        let mut store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3576        store
3577            .add(
3578                &Fact::new("user:pat@example.com", REL_PERMITS, "read,write ON caller")
3579                    .namespace(AUTHZ_NS)
3580                    .created_at(1_000),
3581            )
3582            .unwrap();
3583        std::mem::forget(dir);
3584        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3585        UiServer::new(facade, "sso-test".into())
3586            .with_sso_rotating("x-forwarded-user", secret, next)
3587    }
3588
3589    fn post(server: &UiServer, extra_headers: &str) -> String {
3590        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3591        let addr = listener.local_addr().unwrap();
3592        std::thread::scope(|scope| {
3593            scope.spawn(|| {
3594                if let Ok((s, _)) = listener.accept() {
3595                    let _ = server.handle(s);
3596                }
3597            });
3598            let mut c = std::net::TcpStream::connect(addr).unwrap();
3599            let req = format!(
3600                "POST /api/cal HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n{extra_headers}Content-Length: {}\r\nConnection: close\r\n\r\n",
3601                WRITE.len()
3602            );
3603            c.write_all(req.as_bytes()).unwrap();
3604            c.write_all(WRITE).unwrap();
3605            let mut out = String::new();
3606            let _ = c.read_to_string(&mut out);
3607            out
3608        })
3609    }
3610
3611    /// The §3.3 gate: a proxy-proven identity lands as a named actor whose
3612    /// FILE grants decide; a forged identity header without the proxy
3613    /// secret is ignored (the write is refused as anonymous).
3614    #[test]
3615    fn proxied_identity_works_and_forged_headers_are_ignored() {
3616        let server = sso_server();
3617
3618        // 1. Proxy-proven: identity + secret → the granted principal writes.
3619        let ok = post(
3620            &server,
3621            "X-Forwarded-User: user:pat@example.com\r\nX-Areev-Proxy-Secret: proxy-secret\r\n",
3622        );
3623        assert!(ok.contains("HTTP/1.1 200"), "{}", &ok[..ok.len().min(200)]);
3624        assert!(!ok.contains("AUT-E001"), "granted principal must write: {ok}");
3625
3626        // 2. Forged: the identity header WITHOUT the secret is ignored — the
3627        // request is anonymous and the write refuses.
3628        let forged = post(&server, "X-Forwarded-User: user:pat@example.com\r\n");
3629        assert!(
3630            forged.contains("anonymous") || forged.contains("401"),
3631            "forged identity must not authenticate: {forged}"
3632        );
3633
3634        // 3. Wrong secret: same refusal (constant-time compare, same path).
3635        let wrong = post(
3636            &server,
3637            "X-Forwarded-User: user:pat@example.com\r\nX-Areev-Proxy-Secret: guess\r\n",
3638        );
3639        assert!(
3640            wrong.contains("anonymous") || wrong.contains("401"),
3641            "wrong proxy secret must not authenticate: {wrong}"
3642        );
3643    }
3644
3645    /// [A2] The proxy secret proves the PROXY. It does not make whatever the
3646    /// proxy forwarded well-formed — and an identity lands in immutable,
3647    /// replicating audit grains, so a malformed one outlives its request.
3648    #[test]
3649    fn malformed_identities_are_rejected_even_with_a_valid_proxy_secret() {
3650        assert_eq!(
3651            super::sanitize_sso_identity("  user:pat@example.com  ").as_deref(),
3652            Some("user:pat@example.com"),
3653            "surrounding whitespace is trimmed, not rejected"
3654        );
3655
3656        // CR/LF would smuggle a second line into every log and audit record.
3657        assert!(super::sanitize_sso_identity("user:a\r\nX-Admin: true").is_none());
3658        assert!(super::sanitize_sso_identity("user:a\tb").is_none());
3659        // Internal whitespace would make "user: a" and "user:a" two audit
3660        // identities for one person.
3661        assert!(super::sanitize_sso_identity("user a").is_none());
3662        assert!(super::sanitize_sso_identity("").is_none());
3663        assert!(super::sanitize_sso_identity(&"x".repeat(129)).is_none());
3664        // Reserved: an audit line must never be ambiguous between a vouched
3665        // person and the console's own floor/ceiling principals.
3666        assert!(super::sanitize_sso_identity("anonymous").is_none());
3667        assert!(super::sanitize_sso_identity("user:console").is_none());
3668    }
3669
3670    /// [A2] A rejected identity is treated as an ABSENT one — the request
3671    /// degrades to anonymous rather than the console refusing to serve, so a
3672    /// misconfigured proxy cannot take the console down.
3673    #[test]
3674    fn a_rejected_identity_degrades_to_anonymous_rather_than_erroring() {
3675        let server = sso_server();
3676        let out = post(
3677            &server,
3678            "X-Forwarded-User: anonymous\r\nX-Areev-Proxy-Secret: proxy-secret\r\n",
3679        );
3680        assert!(
3681            out.contains("anonymous") || out.contains("401"),
3682            "a reserved name must not authenticate: {out}"
3683        );
3684        assert!(!out.contains("HTTP/1.1 500"), "and must not error: {out}");
3685    }
3686
3687    /// The rotation window (#79): while two secrets are configured, either
3688    /// proves the proxy — so the fleet moves over one node at a time instead
3689    /// of atomically, which is the only way an impersonation-grade credential
3690    /// gets rotated without an outage or a gap.
3691    #[test]
3692    fn both_secrets_authenticate_during_a_rotation_window() {
3693        let server = sso_server_rotating(Some("new-secret"));
3694        let id = "X-Forwarded-User: user:pat@example.com\r\n";
3695
3696        for secret in ["proxy-secret", "new-secret"] {
3697            let out = post(&server, &format!("{id}X-Areev-Proxy-Secret: {secret}\r\n"));
3698            assert!(out.contains("HTTP/1.1 200"), "{secret} rejected: {out}");
3699            assert!(!out.contains("AUT-E001"), "{secret} must authenticate: {out}");
3700        }
3701
3702        // The window widens what proves the proxy, never what a proved
3703        // identity may do, and never to a third value.
3704        let wrong = post(&server, &format!("{id}X-Areev-Proxy-Secret: guess\r\n"));
3705        assert!(
3706            wrong.contains("anonymous") || wrong.contains("401"),
3707            "an unrelated secret must still be refused mid-rotation: {wrong}"
3708        );
3709    }
3710
3711    /// Closing the window is what actually retires the old credential — the
3712    /// step the runbook exists to make sure nobody skips.
3713    #[test]
3714    fn the_retired_secret_stops_working_once_the_window_closes() {
3715        // Rotation complete: the new value is now the only one deployed.
3716        let server = sso_server_with("new-secret", None);
3717        let id = "X-Forwarded-User: user:pat@example.com\r\n";
3718
3719        let ok = post(&server, &format!("{id}X-Areev-Proxy-Secret: new-secret\r\n"));
3720        assert!(ok.contains("HTTP/1.1 200"), "{ok}");
3721        assert!(!ok.contains("AUT-E001"), "the promoted secret must authenticate: {ok}");
3722
3723        let old = post(&server, &format!("{id}X-Areev-Proxy-Secret: proxy-secret\r\n"));
3724        assert!(
3725            old.contains("anonymous") || old.contains("401"),
3726            "the retired secret must stop working: {old}"
3727        );
3728    }
3729
3730    #[test]
3731    #[should_panic(expected = "must differ")]
3732    fn rotating_to_the_same_value_is_refused() {
3733        // A rotation that deploys the same value twice did not happen, and it
3734        // would read as "both live" in every log and status line.
3735        let _ = sso_server_rotating(Some("proxy-secret"));
3736    }
3737
3738    use crate::CONSOLE_HTML;
3739    use std::collections::BTreeSet;
3740
3741    /// Every `<section class="page" id="page-X">` must be named in the one
3742    /// array in `render()` that clears `hidden`, and every sidebar
3743    /// `data-page="X"` must have such a section.
3744    ///
3745    /// The console's page sections ship `hidden` in the markup, so a page is
3746    /// visible only if `render()` un-hides it. The Triggers tab shipped
3747    /// missing from that array: `renderTriggers()` filled `#trgBody` on every
3748    /// render, the nav item highlighted, the hash routed — and the section
3749    /// stayed `hidden` while every other page was hidden too, so the tab
3750    /// showed a blank pane. Nothing else in the file could catch it: the
3751    /// omission is a *missing* string, not a wrong one.
3752    #[test]
3753    fn every_console_page_is_in_the_visibility_list() {
3754        fn all(hay: &str, open: &str) -> BTreeSet<String> {
3755            let mut out = BTreeSet::new();
3756            let mut rest = hay;
3757            while let Some(i) = rest.find(open) {
3758                rest = &rest[i + open.len()..];
3759                let end = rest.find('"').expect("unterminated attribute");
3760                out.insert(rest[..end].to_string());
3761                rest = &rest[end..];
3762            }
3763            out
3764        }
3765
3766        let sections = all(CONSOLE_HTML, "id=\"page-");
3767        let nav = all(CONSOLE_HTML, "data-page=\"");
3768        for want in ["workflows", "runs", "tools"] {
3769            assert!(sections.contains(want), "the {want} section itself went missing");
3770        }
3771        // Triggers deliberately have no page: a trigger points AT a plan and is
3772        // only legible next to it, so they render in the workflow canvas's own
3773        // lane. The old deep link must still land somewhere real.
3774        assert!(!sections.contains("triggers"), "triggers belong on the canvas, not on a page");
3775        assert!(
3776            CONSOLE_HTML.contains("if (head === 'triggers')"),
3777            "#triggers must still route somewhere — a removed page is not a dead bookmark"
3778        );
3779
3780        // The single array in render() that drives `.hidden`.
3781        let head = "for (const p of [";
3782        let i = CONSOLE_HTML.find(head).expect("render()'s page-visibility loop");
3783        let tail = &CONSOLE_HTML[i + head.len()..];
3784        let j = tail.find(']').expect("unterminated page array");
3785        let listed: BTreeSet<String> = tail[..j]
3786            .split(',')
3787            .map(|t| t.trim().trim_matches('\'').to_string())
3788            .filter(|t| !t.is_empty())
3789            .collect();
3790
3791        assert_eq!(
3792            sections, listed,
3793            "page sections and render()'s visibility list disagree; a section missing \
3794             from the list renders into a pane that never un-hides"
3795        );
3796        let orphan: Vec<_> = nav.difference(&sections).collect();
3797        assert!(orphan.is_empty(), "nav items with no page section: {orphan:?}");
3798    }
3799}
3800
3801/// Issue #124: the console must never disclose the password half of a
3802/// Postgres DSN, at any of its three display surfaces, while the RAW label
3803/// keeps working as the credential map's `memories` comparison key.
3804#[cfg(test)]
3805mod dsn_redaction_tests {
3806    use super::UiServer;
3807    use areev_cal::AreevFacade;
3808    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
3809    use areev_core::types::{Fact, Grain};
3810    use areev_store::Areev;
3811
3812    const DSN: &str = "postgresql://u:SUPERSECRET@h:5432/d?sslmode=require";
3813
3814    fn server() -> UiServer {
3815        let dir = tempfile::tempdir().unwrap();
3816        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3817        std::mem::forget(dir);
3818        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3819        UiServer::new(facade, DSN.to_string())
3820    }
3821
3822    fn text(r: &(&str, &str, Vec<u8>)) -> String {
3823        String::from_utf8_lossy(&r.2).to_string()
3824    }
3825
3826    #[test]
3827    fn stats_config_and_html_redact_the_dsn_password_but_keep_the_host() {
3828        let s = server();
3829        for (method, path) in [("GET", "/api/stats"), ("GET", "/api/config"), ("GET", "/")] {
3830            let r = s.route(method, path, b"", None, None);
3831            let body = text(&r);
3832            assert!(!body.contains("SUPERSECRET"), "{path} leaked the password: {body}");
3833            assert!(body.contains("h:5432"), "{path} redacted more than the password: {body}");
3834        }
3835    }
3836
3837    /// Redaction is DISPLAY ONLY: a credential map's `memories` entry is
3838    /// documented as the raw `--db` value, and it must still resolve —
3839    /// proving the redacted form never leaked into the auth-comparison
3840    /// path (`resolve_for_memory`'s exact string compare).
3841    #[test]
3842    fn credential_map_memories_entry_still_matches_the_raw_dsn() {
3843        std::env::set_var("AREEV_DSN_TOK", "dsn-scoped-secret");
3844        let map_json = format!(
3845            r#"{{"version":1,"tokens":[{{"env":"AREEV_DSN_TOK","principal":"agent:sync","memories":["{DSN}"]}}]}}"#
3846        );
3847        let dir = tempfile::tempdir().unwrap();
3848        let mut store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3849        store
3850            .add(
3851                &Fact::new("agent:sync", REL_PERMITS, "read,write ON caller")
3852                    .namespace(AUTHZ_NS)
3853                    .created_at(1_000),
3854            )
3855            .unwrap();
3856        std::mem::forget(dir);
3857        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3858        let s = UiServer::new(facade, DSN.to_string())
3859            .with_credentials(CredentialMap::from_json(&map_json).unwrap());
3860
3861        const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
3862        let r = s.route("POST", "/api/cal", WRITE, Some("dsn-scoped-secret"), None);
3863        let body = text(&r);
3864        assert!(r.0.starts_with("200") && !body.contains("AUT-E001"), "{body}");
3865    }
3866}
3867
3868/// Issue #125: `--allow-origin` lets an exact origin's cross-origin POSTs
3869/// through, without weakening the check for anyone else — no wildcards, no
3870/// suffix/subdomain matching. The Origin header is parsed in
3871/// `handle_request` (not `route`), so these go over a real socket.
3872#[cfg(test)]
3873mod origin_tests {
3874    use super::UiServer;
3875    use areev_cal::AreevFacade;
3876    use areev_store::Areev;
3877    use std::io::{Read, Write};
3878
3879    fn server() -> UiServer {
3880        let dir = tempfile::tempdir().unwrap();
3881        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3882        std::mem::forget(dir);
3883        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3884        UiServer::new(facade, "origin-test".into())
3885    }
3886
3887    /// POST a read-only CAL query (works token-less on an open console) with
3888    /// an optional `Origin` header, returning the raw HTTP response text.
3889    fn post_with_origin(server: &UiServer, origin: Option<&str>) -> String {
3890        let body: &[u8] = br#"{"query":"RECALL facts WHERE subject = \"acme\""}"#;
3891        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3892        let addr = listener.local_addr().unwrap();
3893        std::thread::scope(|scope| {
3894            scope.spawn(|| {
3895                if let Ok((s, _)) = listener.accept() {
3896                    let _ = server.handle(s);
3897                }
3898            });
3899            let mut c = std::net::TcpStream::connect(addr).unwrap();
3900            let origin_header = origin.map(|o| format!("Origin: {o}\r\n")).unwrap_or_default();
3901            let req = format!(
3902                "POST /api/cal HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n{origin_header}Content-Length: {}\r\nConnection: close\r\n\r\n",
3903                body.len()
3904            );
3905            c.write_all(req.as_bytes()).unwrap();
3906            c.write_all(body).unwrap();
3907            let mut out = String::new();
3908            let _ = c.read_to_string(&mut out);
3909            out
3910        })
3911    }
3912
3913    #[test]
3914    fn matching_allowed_origin_is_accepted() {
3915        let s = server().allow_origin("https://console.example.com");
3916        let r = post_with_origin(&s, Some("https://console.example.com"));
3917        assert!(r.contains("HTTP/1.1 200"), "{r}");
3918    }
3919
3920    #[test]
3921    fn non_matching_origin_is_still_rejected() {
3922        let s = server().allow_origin("https://console.example.com");
3923        let r = post_with_origin(&s, Some("https://not-allowed.example.com"));
3924        assert!(r.contains("403"), "{r}");
3925        assert!(r.contains("cross-origin request rejected"), "{r}");
3926    }
3927
3928    #[test]
3929    fn a_subdomain_of_an_allowed_origin_is_rejected_not_matched() {
3930        // The allowlist entry is the console's real origin; a lookalike
3931        // subdomain must not be accepted by suffix matching.
3932        let s = server().allow_origin("https://console.example.com");
3933        let r = post_with_origin(&s, Some("https://evil-console.example.com"));
3934        assert!(r.contains("403"), "{r}");
3935    }
3936
3937    #[test]
3938    fn loopback_origin_still_works_with_no_allowlist_set() {
3939        let s = server();
3940        let r = post_with_origin(&s, Some("http://127.0.0.1:7437"));
3941        assert!(r.contains("HTTP/1.1 200"), "{r}");
3942    }
3943
3944    #[test]
3945    fn no_origin_header_still_works() {
3946        let s = server();
3947        let r = post_with_origin(&s, None);
3948        assert!(r.contains("HTTP/1.1 200"), "{r}");
3949    }
3950
3951    #[test]
3952    fn matching_origin_differing_only_in_case_and_trailing_slash_is_accepted() {
3953        let s = server().allow_origin("https://console.example.com");
3954        let r = post_with_origin(&s, Some("HTTPS://Console.Example.com/"));
3955        assert!(r.contains("HTTP/1.1 200"), "{r}");
3956    }
3957}
3958
3959/// Issue #126: repeated bad credentials from one source IP are COUNTED and
3960/// LOGGED in a stable, greppable shape — but never delayed or locked out
3961/// in-process (`serve` is a strictly serial accept loop; see
3962/// `note_auth_failure`'s doc comment for why a sleep here would itself be a
3963/// denial-of-service lever). A request that never presented a credential at
3964/// all has nothing to fail and is never counted.
3965/// [A3] Native OIDC at the request level: cookies, the `/auth/*` endpoints,
3966/// and the approval rules an IdP-proven identity is subject to.
3967#[cfg(all(test, feature = "oidc"))]
3968mod oidc_route_tests {
3969    use super::{cookie_value, oidc, UiServer};
3970    use areev_cal::AreevFacade;
3971    use areev_core::authz::{AUTHZ_NS, REL_PERMITS};
3972    use areev_core::types::{Fact, Grain};
3973    use areev_store::Areev;
3974
3975    fn cfg() -> oidc::OidcConfig {
3976        oidc::OidcConfig {
3977            issuer: "https://idp.example.com".into(),
3978            client_id: "console".into(),
3979            client_secret: "s3cr3t".into(),
3980            redirect_uri: "https://console.example.com/auth/callback".into(),
3981            scopes: "openid email".into(),
3982            principal_claim: "email".into(),
3983            principal_prefix: None,
3984        }
3985    }
3986
3987    /// A cookie header is attacker-influenced: any script on any same-site
3988    /// origin can set cookies. A prefix or substring match would let a decoy
3989    /// shadow the real session.
3990    #[test]
3991    fn cookie_lookup_is_exact_on_the_name() {
3992        let h = "theme=dark; areev_session=real; other=x";
3993        assert_eq!(cookie_value(h, "areev_session").as_deref(), Some("real"));
3994        // A decoy whose name merely CONTAINS the real one must not match.
3995        let decoy = "areev_session_decoy=evil; areev_session=real";
3996        assert_eq!(cookie_value(decoy, "areev_session").as_deref(), Some("real"));
3997        let only_decoy = "xareev_session=evil; areev_sessionx=evil2";
3998        assert!(cookie_value(only_decoy, "areev_session").is_none());
3999        assert!(cookie_value("", "areev_session").is_none());
4000    }
4001
4002    /// `/auth/login` redirects to the IdP and stores nothing in the browser;
4003    /// `/auth/logout` clears the cookie AND drops the server-side session.
4004    #[test]
4005    fn the_auth_endpoints_redirect_and_manage_the_cookie() {
4006        let dir = tempfile::tempdir().unwrap();
4007        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
4008        std::mem::forget(dir);
4009        let facade = AreevFacade::with_session(store, Some("ops".into()), None);
4010        let provider = oidc::OidcProvider::with_test_session(cfg(), "sid-1", "user:pat");
4011        let s = UiServer::new(facade, "oidc-test".into()).with_oidc(provider);
4012
4013        // login → 302 to the IdP, and no Set-Cookie (nothing to remember yet).
4014        let (status, extra, _) = s.oidc_route("GET", "/auth/login", None);
4015        assert!(status.starts_with("302"), "{status}");
4016        assert!(extra.contains("Location: https://idp.example.com/authorize"), "{extra}");
4017        assert!(!extra.contains("Set-Cookie"), "{extra}");
4018        assert!(extra.contains("Cache-Control: no-store"), "a redirect carrying state must not cache: {extra}");
4019
4020        // The session works before logout...
4021        assert!(s.oidc_principal(Some("areev_session=sid-1")).is_some());
4022
4023        // ...and logout clears the browser copy AND invalidates server-side.
4024        let (status, extra, _) =
4025            s.oidc_route("POST", "/auth/logout", Some("areev_session=sid-1"));
4026        assert!(status.starts_with("302"), "{status}");
4027        assert!(extra.contains("Max-Age=0"), "{extra}");
4028        assert!(extra.contains("HttpOnly"), "{extra}");
4029        assert!(extra.contains("SameSite=Strict"), "{extra}");
4030        assert!(
4031            s.oidc_principal(Some("areev_session=sid-1")).is_none(),
4032            "logout must invalidate the session, not just the browser's copy"
4033        );
4034
4035        // A callback with no code surfaces the IdP's own error.
4036        let (status, _, body) =
4037            s.oidc_route("GET", "/auth/callback?error=access_denied", None);
4038        assert!(status.starts_with("400"), "{status}");
4039        assert!(body.contains("access_denied"), "{body}");
4040    }
4041
4042    /// The cookie is `HttpOnly` + `SameSite=Strict`, and `Secure` exactly
4043    /// when the redirect URI is https — a loopback console over plain http
4044    /// must still be able to log in.
4045    #[test]
4046    fn the_session_cookie_is_httponly_strict_and_secure_only_over_https() {
4047        let mk = |redirect: &str| {
4048            let dir = tempfile::tempdir().unwrap();
4049            let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
4050            std::mem::forget(dir);
4051            let facade = AreevFacade::with_session(store, Some("ops".into()), None);
4052            let mut c = cfg();
4053            c.redirect_uri = redirect.into();
4054            let p = oidc::OidcProvider::with_test_session(c, "sid", "user:pat");
4055            UiServer::new(facade, "t".into()).with_oidc(p)
4056        };
4057
4058        let https = mk("https://console.example.com/auth/callback");
4059        let (_, extra, _) = https.oidc_route("GET", "/auth/logout", None);
4060        assert!(extra.contains("; Secure"), "https deployment must set Secure: {extra}");
4061
4062        let http = mk("http://127.0.0.1:7437/auth/callback");
4063        let (_, extra, _) = http.oidc_route("GET", "/auth/logout", None);
4064        assert!(!extra.contains("; Secure"), "loopback http must not set Secure: {extra}");
4065        // The other two are unconditional.
4066        assert!(extra.contains("HttpOnly") && extra.contains("SameSite=Strict"), "{extra}");
4067    }
4068
4069    /// The point of the whole feature: an OIDC-proven identity MAY approve,
4070    /// and `--sso-approvals` (which governs the header path) does not touch
4071    /// it. A signature verified against the issuer's key set is a stronger
4072    /// claim than a shared proxy secret, so it gets the stronger right.
4073    #[test]
4074    fn an_oidc_principal_may_approve_regardless_of_sso_approvals() {
4075        let dir = tempfile::tempdir().unwrap();
4076        let path = dir.path().join("t.db");
4077        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
4078        store
4079            .add(
4080                &Fact::new("user:pat", REL_PERMITS, "read,run.respond ON ops")
4081                    .namespace(AUTHZ_NS)
4082                    .created_at(900),
4083            )
4084            .unwrap();
4085        std::mem::forget(dir);
4086        let facade = AreevFacade::with_session(store, Some("ops".into()), None);
4087        let provider = oidc::OidcProvider::with_test_session(cfg(), "sid-1", "user:pat");
4088        let s = UiServer::new(facade, "oidc-test".into())
4089            .with_oidc(provider)
4090            // The A0 default, explicitly: SSO headers may NOT approve.
4091            .with_sso_approvals(false);
4092
4093        let r = s.route_full("GET", "/api/whoami", b"", None, None, None, Some("user:pat"));
4094        let text = String::from_utf8_lossy(&r.2).to_string();
4095        assert!(text.contains(r#""identity_source":"oidc""#), "{text}");
4096        assert!(
4097            text.contains(r#""may_approve":true"#),
4098            "an IdP-proven identity is exactly what --sso-approvals exists to \
4099             substitute for; it must not be caught by that refusal: {text}"
4100        );
4101        assert!(text.contains("user:pat"), "{text}");
4102    }
4103}
4104
4105#[cfg(test)]
4106mod auth_failure_tracking_tests {
4107    use super::UiServer;
4108    use areev_cal::AreevFacade;
4109    use areev_store::Areev;
4110    use std::io::{Read, Write};
4111    use std::net::IpAddr;
4112
4113    const LOCALHOST: IpAddr = IpAddr::V4(std::net::Ipv4Addr::LOCALHOST);
4114
4115    fn server() -> UiServer {
4116        let dir = tempfile::tempdir().unwrap();
4117        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
4118        std::mem::forget(dir);
4119        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
4120        UiServer::new(facade, "auth-failure-test".into()).with_auth("right-token".into())
4121    }
4122
4123    /// GET `/` with an optional `Authorization: Bearer` header, over a real
4124    /// socket (the counter hooks `handle_request`, not `route`).
4125    fn get_root(server: &UiServer, bearer: Option<&str>) -> String {
4126        let auth_header = bearer
4127            .map(|t| format!("Authorization: Bearer {t}\r\n"))
4128            .unwrap_or_default();
4129        get_root_with(server, &auth_header)
4130    }
4131
4132    /// `GET /` with arbitrary extra headers, over a real socket (the counter
4133    /// hooks `handle_request`, not `route`).
4134    fn get_root_with(server: &UiServer, extra_headers: &str) -> String {
4135        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4136        let addr = listener.local_addr().unwrap();
4137        std::thread::scope(|scope| {
4138            scope.spawn(|| {
4139                if let Ok((s, _)) = listener.accept() {
4140                    let _ = server.handle(s);
4141                }
4142            });
4143            let mut c = std::net::TcpStream::connect(addr).unwrap();
4144            let req = format!("GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n{extra_headers}Connection: close\r\n\r\n");
4145            c.write_all(req.as_bytes()).unwrap();
4146            let mut out = String::new();
4147            let _ = c.read_to_string(&mut out);
4148            out
4149        })
4150    }
4151
4152    #[test]
4153    fn a_bare_request_is_401_but_not_counted() {
4154        let s = server();
4155        // No credential presented at all: 401 (auth_all guards every
4156        // request), but nothing was attempted, so it must not be counted —
4157        // a token-less probe is not an attack attempt.
4158        let bare = get_root(&s, None);
4159        assert!(bare.contains("HTTP/1.1 401"), "{bare}");
4160        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 0, "a bare request has nothing to fail");
4161    }
4162
4163    #[test]
4164    fn a_wrong_token_is_401_and_is_counted() {
4165        let s = server();
4166        let wrong = get_root(&s, Some("guess"));
4167        assert!(wrong.contains("HTTP/1.1 401"), "{wrong}");
4168        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 1);
4169
4170        let wrong_again = get_root(&s, Some("guess"));
4171        assert!(wrong_again.contains("HTTP/1.1 401"), "{wrong_again}");
4172        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 2, "consecutive failures accumulate");
4173    }
4174
4175    #[test]
4176    fn a_right_token_after_a_streak_succeeds_immediately_and_resets_it() {
4177        let s = server();
4178        for _ in 0..5 {
4179            let r = get_root(&s, Some("guess"));
4180            assert!(r.contains("HTTP/1.1 401"), "{r}");
4181        }
4182        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 5);
4183
4184        // The right token succeeds on the very next request — there is no
4185        // in-process DELAY at any streak length, and below
4186        // MAX_CONSECUTIVE_AUTH_FAILURES no rejection either, so an operator
4187        // who fat-fingers a pasted token is never locked out.
4188        let ok = get_root(&s, Some("right-token"));
4189        assert!(ok.contains("HTTP/1.1 200"), "{ok}");
4190        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 0, "success resets the streak");
4191
4192        // The next wrong guess starts a fresh streak at 1, not 6.
4193        let r = get_root(&s, Some("guess"));
4194        assert!(r.contains("HTTP/1.1 401"), "{r}");
4195        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 1);
4196    }
4197
4198    /// [A1] Behind a trusted proxy every request shares ONE source address,
4199    /// so a per-IP lockout would let one attacker's bad guesses refuse every
4200    /// user behind it — a self-inflicted outage in the deployment we
4201    /// recommend. A proxy-proven request is exempt; throttling there belongs
4202    /// to the proxy, like TLS and the IdP handshake.
4203    #[test]
4204    fn a_proxy_proven_request_is_never_locked_out() {
4205        let dir = tempfile::tempdir().unwrap();
4206        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
4207        std::mem::forget(dir);
4208        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
4209        let s = UiServer::new(facade, "proxy-test".into())
4210            .with_auth("right-token".into())
4211            .with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>);
4212
4213        // Burn well past the threshold with wrong bearer tokens, but all
4214        // arriving through the proxy (valid proxy secret on every request).
4215        for _ in 0..(super::MAX_CONSECUTIVE_AUTH_FAILURES + 5) {
4216            let _ = get_root_with(
4217                &s,
4218                "Authorization: Bearer guess\r\nX-Areev-Proxy-Secret: proxy-secret\r\n",
4219            );
4220        }
4221        // A legitimate user behind the same proxy is still served.
4222        let ok = get_root_with(
4223            &s,
4224            "Authorization: Bearer right-token\r\nX-Areev-Proxy-Secret: proxy-secret\r\n",
4225        );
4226        assert!(ok.contains("HTTP/1.1 200"), "proxy-borne traffic must not be locked out: {ok}");
4227    }
4228
4229    /// [A1] Past the threshold the console stops answering credential-bearing
4230    /// requests from that source — refusing, never sleeping, because a serial
4231    /// accept loop makes a sleep a denial-of-service lever for everyone else.
4232    #[test]
4233    fn a_long_streak_is_refused_with_429_until_it_goes_idle() {
4234        let s = server();
4235        for i in 0..super::MAX_CONSECUTIVE_AUTH_FAILURES {
4236            let r = get_root(&s, Some("guess"));
4237            assert!(r.contains("HTTP/1.1 401"), "attempt {i} should still be a 401: {r}");
4238        }
4239
4240        // The next credential-bearing request is refused before routing.
4241        let blocked = get_root(&s, Some("guess"));
4242        assert!(blocked.contains("HTTP/1.1 429"), "{blocked}");
4243        assert!(blocked.contains("Retry-After:"), "a 429 must say when: {blocked}");
4244
4245        // The brake is on the SOURCE, not on the credential: even the right
4246        // token is refused while the streak stands. That is the intended
4247        // trade — an attacker who has burned an IP cannot then race a guess
4248        // through — and it is why the streak expires on its own.
4249        let right = get_root(&s, Some("right-token"));
4250        assert!(right.contains("HTTP/1.1 429"), "{right}");
4251
4252        // A credential-LESS request is untouched: it was never counted, so it
4253        // must not be blocked either. The console page still serves its 401
4254        // challenge, which is what lets a browser prompt for a fresh login.
4255        let bare = get_root(&s, None);
4256        assert!(bare.contains("HTTP/1.1 401"), "{bare}");
4257    }
4258}