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                // Paged and namespace-scoped on the server (#165): the
1819                // console used to filter a fixed newest-50 page client-side,
1820                // so a quiet tenant's runs — open approvals included — were
1821                // simply absent behind a busier tenant's. `ns` takes an exact
1822                // name or an `org.*` prefix; `limit` is clamped so one
1823                // request cannot ask for the whole history; the response
1824                // says the total and whether it truncated.
1825                let runner = self.runner("console:read");
1826                let ns = q("ns").filter(|s| !s.is_empty() && s.as_str() != "*");
1827                let limit = q("limit")
1828                    .and_then(|v| v.parse::<usize>().ok())
1829                    .unwrap_or(50)
1830                    .clamp(1, 500);
1831                let offset = q("offset").and_then(|v| v.parse::<usize>().ok()).unwrap_or(0);
1832                match runner.list_runs(ns.as_deref(), offset, limit) {
1833                    Ok(page) => {
1834                        let rows: Vec<Value> = page
1835                            .runs
1836                            .iter()
1837                            .map(|r| {
1838                                serde_json::json!({
1839                                    "run_id": r.run_id,
1840                                    "ns": r.ns,
1841                                    "outcome": r.outcome,
1842                                })
1843                            })
1844                            .collect();
1845                        ok_json(serde_json::json!({
1846                            "ok": true,
1847                            "runs": rows,
1848                            "total": page.total,
1849                            "truncated": page.truncated,
1850                            "offset": page.offset,
1851                            "limit": page.limit,
1852                            "unattributed": page.unattributed,
1853                        }))
1854                    }
1855                    Err(e) => run_api_err(&e.to_string()),
1856                }
1857            }
1858            ("GET", "/api/run/inspect") => {
1859                let Some(run_id) = q("run_id") else {
1860                    return run_api_err("run_id required");
1861                };
1862                // Same Runner::inspect the CLI and bindings call (issue
1863                // #34) — this used to hand-roll a divergent, smaller subset
1864                // (no pinned/budgets/fork_of/superstep/phase).
1865                match self.runner("console:read").inspect(&run_id) {
1866                    Ok(report) => {
1867                        let mut v = serde_json::to_value(&report).unwrap_or(Value::Null);
1868                        if let Some(o) = v.as_object_mut() {
1869                            o.insert("ok".into(), Value::Bool(true));
1870                        }
1871                        ok_json(v)
1872                    }
1873                    Err(e) => run_api_err(&e.to_string()),
1874                }
1875            }
1876            ("POST", "/api/run/respond") => {
1877                // [R3] SHARED-TOKEN APPROVALS ARE REFUSED: an approval whose
1878                // "identity" is a console-wide secret voids the
1879                // approver-identity edge of the provenance chain. Only a
1880                // per-principal credential (areev ui --auth) may respond.
1881                let Some(responder) = request_principal.clone() else {
1882                    return ("403 Forbidden", "application/json",
1883                        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());
1884                };
1885                // [A0] PROXY-ASSERTED APPROVALS ARE REFUSED BY DEFAULT: an
1886                // SSO identity's only proof is a shared, static, fleet-wide
1887                // proxy secret — whoever holds it can assert any identity,
1888                // including this approver's. That is a weaker claim than the
1889                // per-principal credential [R3] demands, and the resulting
1890                // audit grain would be indistinguishable from a real
1891                // approval. Opt in with `areev ui --sso-approvals allow`.
1892                if principal_from_sso && !self.sso_approvals {
1893                    return ("403 Forbidden", "application/json",
1894                        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());
1895                }
1896                // [A2] A group-derived principal is a ROLE. It is refused
1897                // even under `--sso-approvals allow`, and deliberately has no
1898                // flag of its own: the audit record would read "role:eng
1899                // approved", which names no one who can be asked why.
1900                if principal_from_group {
1901                    return ("403 Forbidden", "application/json",
1902                        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());
1903                }
1904                let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1905                let (Some(run_id), Some(ask)) = (
1906                    req.get("run_id").and_then(Value::as_str),
1907                    req.get("tool_call_id").and_then(Value::as_str),
1908                ) else {
1909                    return run_api_err("run_id and tool_call_id required");
1910                };
1911                let result = req.get("result").cloned().unwrap_or(Value::Null);
1912                let is_error = req.get("is_error").and_then(Value::as_bool).unwrap_or(false);
1913                let runner = self.runner(&responder);
1914                match runner.respond(run_id, ask, result, is_error, &responder) {
1915                    Ok(()) => ok_json(serde_json::json!({
1916                        "ok": true, "responded": ask, "responder": responder,
1917                        "note": "resume the run to spend the compute",
1918                    })),
1919                    Err(e) => run_api_err(&e.to_string()),
1920                }
1921            }
1922            ("POST", "/api/run/cancel") => {
1923                // The kill switch keeps its LOW bar: any authenticated POST
1924                // may brake a run (the identity label still records who).
1925                let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1926                let Some(run_id) = req.get("run_id").and_then(Value::as_str) else {
1927                    return run_api_err("run_id required");
1928                };
1929                let because = req.get("because").and_then(Value::as_str).unwrap_or("canceled via console");
1930                let who = request_principal.clone().unwrap_or_else(|| "console:shared".into());
1931                let runner = self.runner(&who);
1932                match runner.cancel(run_id, &who, because) {
1933                    Ok(()) => ok_json(serde_json::json!({"ok": true, "canceled": run_id})),
1934                    Err(e) => run_api_err(&e.to_string()),
1935                }
1936            }
1937            ("GET", "/api/loop/recommendations") => {
1938                let status = q("status").and_then(|s| status_from_str(&s));
1939                let sub = BorrowedSubstrate::new(&self.facade);
1940                match self.engine().recommendations(&sub, status) {
1941                    Ok(recs) => ok_json(json!({
1942                        "ok": true,
1943                        "recommendations": recs.iter().map(rec_json).collect::<Vec<_>>(),
1944                    })),
1945                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1946                }
1947            }
1948            ("GET", "/api/loop/health") => {
1949                let sub = BorrowedSubstrate::new(&self.facade);
1950                match self.engine().health(&sub, now_ms()) {
1951                    Ok(h) => ok_json(json!({"ok": true, "health": h})),
1952                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1953                }
1954            }
1955            ("GET", "/api/loop/outcomes") => {
1956                let sub = BorrowedSubstrate::new(&self.facade);
1957                match self.engine().outcomes(&sub) {
1958                    Ok(o) => ok_json(json!({"ok": true, "outcomes": o})),
1959                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1960                }
1961            }
1962            ("GET", "/api/loop/analyzers") => {
1963                // Effective settings (manifest merged with the file-config), so
1964                // the Setup view renders accurate on/off state and floors.
1965                let sub = BorrowedSubstrate::new(&self.facade);
1966                match self.engine().analyzer_settings(&sub) {
1967                    Ok(list) => ok_json(json!({"ok": true, "analyzers": list})),
1968                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1969                }
1970            }
1971            ("GET", "/api/loop/telemetry") => {
1972                // Recall-telemetry rollups for the Sessions view. A read — open
1973                // in read-only mode like the other loop GETs.
1974                let mode = self.facade.with_store(|m| m.telemetry_mode());
1975                if mode == areev_store::TelemetryMode::Off {
1976                    ok_json(json!({"ok": true, "enabled": false}))
1977                } else {
1978                    let access = self.facade.with_store(|m| m.telemetry_access_stats(None));
1979                    let queries = self.facade.with_store(|m| m.telemetry_query_stats(None));
1980                    let budget = self.facade.with_store(|m| m.telemetry_budget_stats());
1981                    match (access, queries, budget) {
1982                        (Ok(mut a), Ok(mut q), Ok(b)) => {
1983                            // Most-recalled first; recurring-gap questions first.
1984                            a.sort_by_key(|x| std::cmp::Reverse(x.recall_count));
1985                            a.truncate(200);
1986                            q.sort_by_key(|x| std::cmp::Reverse(x.run_count));
1987                            q.truncate(200);
1988                            ok_json(json!({
1989                                "ok": true,
1990                                "enabled": true,
1991                                "mode": mode.as_str(),
1992                                "access": a.iter().map(|x| json!({
1993                                    "hash": x.hash, "recall_count": x.recall_count, "last_ms": x.last_ms,
1994                                })).collect::<Vec<_>>(),
1995                                "queries": q.iter().map(|x| json!({
1996                                    "sample": x.sample, "run_count": x.run_count,
1997                                    "empty_count": x.empty_count,
1998                                })).collect::<Vec<_>>(),
1999                                "budget": {
2000                                    "sample_count": b.sample_count,
2001                                    "overflow_count": b.overflow_count,
2002                                },
2003                            }))
2004                        }
2005                        _ => ok_json(json!({"ok": false, "error": "telemetry read failed"})),
2006                    }
2007                }
2008            }
2009            ("POST", "/api/loop/run") => {
2010                let authz = self.facade.authz();
2011                if !authz.is_owner()
2012                    && !authz.allows(areev_core::authz::Verb::LoopRun, areev_loop::LOOP_NS)
2013                {
2014                    return ("403 Forbidden", "application/json",
2015                            br#"{"ok":false,"error":"AUT-E001: this session lacks loop.run"}"#.to_vec());
2016                }
2017                let mut sub = BorrowedSubstrate::new(&self.facade);
2018                // The trigger is recorded as co-creator on LLM/external
2019                // findings, so the same principal cannot later approve them.
2020                // In credential-map mode the actor IS the bound principal —
2021                // a request cannot claim an identity.
2022                let actor = if self.credentials.is_some() {
2023                    authz.principal().to_string()
2024                } else {
2025                    serde_json::from_slice::<Value>(body)
2026                        .ok()
2027                        .and_then(|v| v.get("actor").and_then(Value::as_str).map(str::to_string))
2028                        .unwrap_or_else(|| "user:console".to_string())
2029                };
2030                let opts = RunOptions { triggering_actor: Some(actor), ..Default::default() };
2031                match self.engine().run(&mut sub, &opts, now_ms()) {
2032                    Ok(res) => ok_json(json!({"ok": true, "run": res})),
2033                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
2034                }
2035            }
2036            ("POST", "/api/loop/review") => self.loop_review(body),
2037            ("POST", "/api/loop/apply") => self.loop_apply(body),
2038            ("POST", "/api/loop/rollback") => self.loop_rollback(body),
2039            ("POST", "/api/loop/config") => self.loop_config(body),
2040            ("POST", "/api/anon/config") => self.anon_config(body),
2041            _ => (
2042                "404 Not Found",
2043                "application/json",
2044                br#"{"ok":false,"error":"not found"}"#.to_vec(),
2045            ),
2046        }
2047    }
2048
2049    /// The console session's scopes derive from its grants (an owner
2050    /// session — today's only mode — holds all of them); actor
2051    /// `user:console` unless overridden, observer derived from the actor
2052    /// label, never from request text.
2053    fn loop_review(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
2054        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
2055        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
2056        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
2057        let bound = self.facade.authz();
2058        let actor = if self.credentials.is_some() {
2059            bound.principal().to_string()
2060        } else {
2061            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
2062        };
2063        let actor = actor.as_str();
2064        let decision = if req.get("decision").and_then(Value::as_str) == Some("reject") {
2065            Decision::Reject
2066        } else {
2067            Decision::Approve
2068        };
2069        let mut sub = BorrowedSubstrate::new(&self.facade);
2070        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
2071        let observer = areev_loop_adapter::observer_for_principal(actor);
2072        match self.engine().review(
2073            &mut sub, hash, decision, actor, observer, &scopes, because, now_ms(),
2074        ) {
2075            Ok(()) => ok_json(json!({"ok": true})),
2076            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
2077        }
2078    }
2079
2080    fn loop_apply(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
2081        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
2082        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
2083        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
2084        let bound = self.facade.authz();
2085        let actor = if self.credentials.is_some() {
2086            bound.principal().to_string()
2087        } else {
2088            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
2089        };
2090        let actor = actor.as_str();
2091        let allow_destructive = req.get("allow_destructive").and_then(Value::as_bool).unwrap_or(false);
2092        let mut sub = BorrowedSubstrate::new(&self.facade);
2093        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
2094        let observer = areev_loop_adapter::observer_for_principal(actor);
2095        let engine = self.engine();
2096        // A code or adapter revision applies only through its recorded gating
2097        // edge: `gating_run` names an eval run whose journaled `mg:eval_run`
2098        // summary becomes the evidence — the stats never come from the client.
2099        let gating = match req.get("gating_run").and_then(Value::as_str) {
2100            Some(run_id) => match engine.gating_evidence(&sub, hash, run_id) {
2101                Ok(g) => Some(g),
2102                Err(e) => {
2103                    return ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()}))
2104                }
2105            },
2106            None => None,
2107        };
2108        let applied = match &gating {
2109            Some(g) => engine.apply_gated(
2110                &mut sub, hash, actor, observer, &scopes, because, allow_destructive, g, now_ms(),
2111            ),
2112            None => engine.apply(
2113                &mut sub, hash, actor, observer, &scopes, because, allow_destructive, now_ms(),
2114            ),
2115        };
2116        match applied {
2117            Ok(applied) => ok_json(json!({"ok": true, "rollbackable": applied.rollbackable})),
2118            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
2119        }
2120    }
2121
2122    fn loop_rollback(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
2123        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
2124        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
2125        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
2126        let bound = self.facade.authz();
2127        let actor = if self.credentials.is_some() {
2128            bound.principal().to_string()
2129        } else {
2130            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
2131        };
2132        let actor = actor.as_str();
2133        let mut sub = BorrowedSubstrate::new(&self.facade);
2134        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
2135        let observer = areev_loop_adapter::observer_for_principal(actor);
2136        match self.engine().rollback(
2137            &mut sub, hash, actor, observer, &scopes, because, now_ms(),
2138        ) {
2139            Ok(()) => ok_json(json!({"ok": true})),
2140            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
2141        }
2142    }
2143
2144    /// Edit one analyzer's file-config from the Setup view. The body is
2145    /// `{analyzer_id, enabled?, severity_floor?, clear_floor?, params?,
2146    /// namespaces?}`; absent fields are left unchanged. The console holds all
2147    /// scopes (local root of trust), so `Admin` is satisfied; an unknown
2148    /// analyzer or bad param is a structured `ok:false` (not a 500).
2149    fn loop_config(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
2150        let id = serde_json::from_slice::<Value>(body)
2151            .ok()
2152            .and_then(|v| v.get("analyzer_id").and_then(Value::as_str).map(str::to_string))
2153            .unwrap_or_default();
2154        // The update reads the same body; the extra `analyzer_id` key is ignored.
2155        let update: areev_loop::AnalyzerConfigUpdate = serde_json::from_slice(body).unwrap_or_default();
2156        let mut sub = BorrowedSubstrate::new(&self.facade);
2157        match self.engine().set_analyzer_config(&mut sub, &id, update, &areev_loop_adapter::scopes_for(&self.facade.authz())) {
2158            Ok(cfg) => ok_json(json!({"ok": true, "config": cfg})),
2159            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
2160        }
2161    }
2162}
2163
2164impl UiServer {
2165    /// Declare or clear a per-namespace anonymization policy from the
2166    /// console (Connect → Settings). Rides the same write gate as every
2167    /// console POST (auth + Origin + body cap upstream); the policy itself
2168    /// validates fail-closed in the store.
2169    fn anon_config(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
2170        let v: Value = match serde_json::from_slice(body) {
2171            Ok(v) => v,
2172            Err(e) => return ok_json(json!({"ok": false, "error": e.to_string()})),
2173        };
2174        let Some(ns) = v.get("ns").and_then(Value::as_str).filter(|n| !n.trim().is_empty())
2175        else {
2176            return ok_json(json!({"ok": false, "error": "ns is required"}));
2177        };
2178        let result = if v.get("clear").and_then(Value::as_bool) == Some(true) {
2179            self.facade.with_store(|m| m.clear_anon_policy(ns))
2180        } else {
2181            match v.get("policy") {
2182                Some(policy) => {
2183                    let policy_json = policy.to_string();
2184                    self.facade.with_store(|m| m.set_anon_policy(ns, &policy_json))
2185                }
2186                None => {
2187                    return ok_json(json!({"ok": false, "error": "policy (object) or clear: true is required"}));
2188                }
2189            }
2190        };
2191        match result {
2192            Ok(()) => {
2193                let declared = self.facade.with_store(|m| m.anon_declared());
2194                ok_json(json!({"ok": true, "policies": declared
2195                    .iter()
2196                    .map(|(ns, mode)| json!({"ns": ns, "mode": mode}))
2197                    .collect::<Vec<_>>()}))
2198            }
2199            Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
2200        }
2201    }
2202}
2203
2204/// True when a `host[:port]` (or `[ipv6]:port`) authority names a loopback
2205/// host. Shared by the Origin drive-by check and the Host-header
2206/// (DNS-rebinding) check.
2207fn host_is_local(host_port: &str) -> bool {
2208    let host = if let Some(h) = host_port.strip_prefix('[') {
2209        h.split(']').next().unwrap_or("")
2210    } else {
2211        host_port.split(':').next().unwrap_or("")
2212    };
2213    matches!(host, "127.0.0.1" | "localhost" | "::1")
2214}
2215
2216/// True when an Origin header names a loopback host (any port, http/https).
2217fn origin_is_local(origin: &str) -> bool {
2218    let rest = origin
2219        .strip_prefix("http://")
2220        .or_else(|| origin.strip_prefix("https://"));
2221    let Some(rest) = rest else { return false };
2222    let host_port = rest.split('/').next().unwrap_or("");
2223    host_is_local(host_port)
2224}
2225
2226/// Normalize an origin (an `Origin` header value, or an operator-configured
2227/// `--allow-origin` entry) for EXACT comparison: lowercase, with a single
2228/// trailing `/` dropped. Nothing else — this only makes two spellings of the
2229/// same origin compare equal; it does not validate shape (the CLI's
2230/// `--allow-origin` parser does that at startup).
2231fn normalize_origin(origin: &str) -> String {
2232    let trimmed = origin.trim();
2233    trimmed.strip_suffix('/').unwrap_or(trimmed).to_ascii_lowercase()
2234}
2235
2236/// Redact a DISPLAY copy of a connection-string / file-path DB label
2237/// (issue #124): if `label` has a `scheme://[user[:pass]@]host...` shape and
2238/// the userinfo carries a password, replace the password with `***`.
2239/// Anything else — a plain file path (no `://`), a DSN with no userinfo, or
2240/// userinfo with no password — is returned byte-for-byte unchanged.
2241///
2242/// **DISPLAY ONLY.** The raw label is still what
2243/// `CredentialMap::resolve_for_memory` (`areev-core/src/authz.rs`) matches a
2244/// token's `memories` scope against via an exact string compare — never swap
2245/// in this redacted form at those call sites, or every `--auth FILE`
2246/// deployment that scopes a token to a Postgres memory silently breaks.
2247///
2248/// Hand-rolled (no URL crate, per the workspace's dependency-light policy):
2249/// only the AUTHORITY segment — between `://` and the first `/`, `?`, or `#`
2250/// that follows — is considered, and within it the LAST `@` is taken as the
2251/// userinfo delimiter. RFC 3986 allows a percent-encoded `@` in a password
2252/// and real passwords contain literal `@` too, so an earlier `@` is presumed
2253/// to be *inside* the password rather than a second delimiter; and a `:` or
2254/// `@` appearing later — in a query string, say — is outside the authority
2255/// entirely and is never mistaken for userinfo.
2256pub fn redact_dsn(label: &str) -> String {
2257    let Some(scheme_end) = label.find("://") else {
2258        return label.to_string();
2259    };
2260    let authority_start = scheme_end + 3;
2261    let rest = &label[authority_start..];
2262    let authority_len = rest.find(['/', '?', '#']).unwrap_or(rest.len());
2263    let authority = &rest[..authority_len];
2264    let Some(at) = authority.rfind('@') else {
2265        return label.to_string();
2266    };
2267    let userinfo = &authority[..at];
2268    let Some(colon) = userinfo.find(':') else {
2269        return label.to_string();
2270    };
2271    let user = &userinfo[..colon];
2272    let mut out = String::with_capacity(label.len());
2273    out.push_str(&label[..authority_start]);
2274    out.push_str(user);
2275    out.push_str(":***@");
2276    out.push_str(&authority[at + 1..]);
2277    out.push_str(&rest[authority_len..]);
2278    out
2279}
2280
2281fn ok_json(v: Value) -> (&'static str, &'static str, Vec<u8>) {
2282    ("200 OK", "application/json", v.to_string().into_bytes())
2283}
2284
2285fn run_api_err(msg: &str) -> (&'static str, &'static str, Vec<u8>) {
2286    (
2287        "400 Bad Request",
2288        "application/json",
2289        serde_json::json!({"ok": false, "error": msg}).to_string().into_bytes(),
2290    )
2291}
2292
2293/// True when a `POST /api/cal` body is a read-only statement. Classification
2294/// is delegated to `areev-cal`'s exhaustive [`areev_cal::classify`] module —
2295/// the single source of truth — so grammar growth cannot desynchronize this
2296/// gate (a keyword sniff lived here before and would have silently
2297/// misclassified any new statement). Fail closed: unparseable text is not
2298/// read-only.
2299fn cal_body_is_read_only(body: &[u8]) -> bool {
2300    let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
2301    let q = req.get("query").and_then(Value::as_str).unwrap_or("");
2302    areev_cal::classify::query_is_read_only(q)
2303}
2304
2305fn status_from_str(s: &str) -> Option<RecStatus> {
2306    match s {
2307        "pending" => Some(RecStatus::Pending),
2308        "approved" => Some(RecStatus::Approved),
2309        "rejected" => Some(RecStatus::Rejected),
2310        "applied" => Some(RecStatus::Applied),
2311        "rolled_back" => Some(RecStatus::RolledBack),
2312        "expired" => Some(RecStatus::Expired),
2313        _ => None, // includes "all"
2314    }
2315}
2316
2317fn rec_json(r: &areev_loop::Recommendation) -> Value {
2318    json!({
2319        "hash": r.hash,
2320        "status": r.status.as_str(),
2321        "severity": r.severity.as_str(),
2322        "analyzer": r.analyzer,
2323        "summary": r.summary.render(),
2324        "target_ref": r.target_ref,
2325        "destructive": r.destructive,
2326        "rollbackable": r.rollbackable,
2327        "evidence": r.evidence,
2328        // The Rule E1 pin, when present — the console reads it to know this
2329        // apply needs a recorded gating run (and which evalset to run).
2330        "evalset_hash": r.evalset_hash,
2331    })
2332}
2333
2334fn urldecode(s: &str) -> String {
2335    let mut out = Vec::new();
2336    let b = s.as_bytes();
2337    let mut i = 0;
2338    while i < b.len() {
2339        match b[i] {
2340            b'%' if i + 2 < b.len() + 1 && i + 2 < b.len() + 1 => {
2341                if i + 2 < b.len() + 1 && i + 2 < b.len() {
2342                    let hex = std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or("");
2343                    if let Ok(v) = u8::from_str_radix(hex, 16) {
2344                        out.push(v);
2345                        i += 3;
2346                        continue;
2347                    }
2348                }
2349                out.push(b[i]);
2350                i += 1;
2351            }
2352            b'+' => {
2353                out.push(b' ');
2354                i += 1;
2355            }
2356            c => {
2357                out.push(c);
2358                i += 1;
2359            }
2360        }
2361    }
2362    String::from_utf8_lossy(&out).to_string()
2363}
2364
2365fn html_escape(s: &str) -> String {
2366    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
2367}
2368
2369/// Constant-time byte comparison — avoids leaking the bearer token through
2370/// response timing. A length mismatch fails fast (token length is not secret).
2371fn ct_eq(a: &[u8], b: &[u8]) -> bool {
2372    if a.len() != b.len() {
2373        return false;
2374    }
2375    let mut diff = 0u8;
2376    for (x, y) in a.iter().zip(b.iter()) {
2377        diff |= x ^ y;
2378    }
2379    diff == 0
2380}
2381
2382/// Decode standard base64 (RFC 4648), enough for HTTP Basic credentials.
2383/// The one hand-rolled decoder lives in `areev_core::b64` (the trigger
2384/// evaluator shares it for connector blobs, #93).
2385fn base64_decode(s: &str) -> Option<Vec<u8>> {
2386    areev_core::b64::decode(s)
2387}
2388
2389/// Extract the password from an HTTP Basic credential (`base64("user:pass")`).
2390/// The console ignores the username and treats the password as the token.
2391/// Returns `None` if the value is not valid base64/UTF-8 or has no `:`.
2392fn basic_auth_password(b64: &str) -> Option<String> {
2393    let text = String::from_utf8(base64_decode(b64)?).ok()?;
2394    text.split_once(':').map(|(_user, pass)| pass.to_string())
2395}
2396
2397#[cfg(test)]
2398mod loop_route_tests {
2399    use super::UiServer;
2400    use areev_cal::AreevFacade;
2401    use areev_core::types::{Fact, Grain};
2402    use areev_store::Areev;
2403
2404    fn server(auth: Option<&str>) -> UiServer {
2405        let dir = tempfile::tempdir().unwrap();
2406        let path = dir.path().join("t.db");
2407        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
2408        // Two identical facts → a duplicate-consolidation recommendation.
2409        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller")).unwrap();
2410        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller")).unwrap();
2411        std::mem::forget(dir); // keep the file alive for the server's lifetime
2412        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2413        let s = UiServer::new(facade, "test".into());
2414        match auth {
2415            Some(t) => s.with_auth(t.to_string()),
2416            None => s,
2417        }
2418    }
2419
2420    fn text(r: &(&str, &str, Vec<u8>)) -> String {
2421        String::from_utf8_lossy(&r.2).to_string()
2422    }
2423
2424    #[test]
2425    fn token_less_console_is_read_only() {
2426        let s = server(None);
2427        // A loop mutation (run) is a write → 401.
2428        assert!(s.route("POST", "/api/loop/run", b"{}", None, None).0.starts_with("401"));
2429        // A write CAL → 401.
2430        let w = s.route("POST", "/api/cal", br#"{"query":"ADD fact SET subject=\"x\""}"#, None, None);
2431        assert!(w.0.starts_with("401"), "write CAL must be 401: {}", text(&w));
2432        // A read CAL → 200.
2433        let r = s.route("POST", "/api/cal", br#"{"query":"RECALL facts WHERE subject = \"acme\""}"#, None, None);
2434        assert!(r.0.starts_with("200"), "read CAL allowed: {}", text(&r));
2435        // Areev Loop reads stay open token-less.
2436        assert!(s.route("GET", "/api/loop/recommendations", b"", None, None).0.starts_with("200"));
2437    }
2438
2439    #[test]
2440    fn telemetry_endpoint_is_an_open_read() {
2441        let s = server(None);
2442        let r = s.route("GET", "/api/loop/telemetry", b"", None, None);
2443        assert!(r.0.starts_with("200"), "telemetry read open: {}", text(&r));
2444        let body = text(&r);
2445        assert!(body.contains("\"ok\":true"), "{body}");
2446        // The test store opens bare (telemetry off) → enabled:false.
2447        assert!(body.contains("\"enabled\":false"), "{body}");
2448    }
2449
2450    #[test]
2451    fn authenticated_run_review_apply_roundtrip() {
2452        let s = server(Some("tok"));
2453        let run = s.route("POST", "/api/loop/run", b"{}", Some("tok"), None);
2454        assert!(run.0.starts_with("200"), "run: {}", text(&run));
2455        assert!(text(&run).contains("\"ran\""));
2456
2457        let list = s.route("GET", "/api/loop/recommendations?status=pending", b"", Some("tok"), None);
2458        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
2459        let recs = v["recommendations"].as_array().unwrap();
2460        assert!(!recs.is_empty(), "at least one recommendation");
2461        let hash = recs[0]["hash"].as_str().unwrap().to_string();
2462
2463        let rev = s.route(
2464            "POST",
2465            "/api/loop/review",
2466            format!(r#"{{"hash":"{hash}","decision":"approve","because":"ok"}}"#).as_bytes(),
2467            Some("tok"),
2468            None,
2469        );
2470        assert!(text(&rev).contains("\"ok\":true"), "review: {}", text(&rev));
2471
2472        let ap = s.route(
2473            "POST",
2474            "/api/loop/apply",
2475            format!(r#"{{"hash":"{hash}","because":"go"}}"#).as_bytes(),
2476            Some("tok"),
2477            None,
2478        );
2479        assert!(text(&ap).contains("\"ok\":true"), "apply: {}", text(&ap));
2480    }
2481
2482    #[test]
2483    fn config_edit_toggles_analyzer_via_console() {
2484        let s = server(Some("tok"));
2485        // Token-less write → 401 (guarded like every POST).
2486        assert!(s.route("POST", "/api/loop/config", b"{}", None, None).0.starts_with("401"));
2487
2488        // Read the analyzers; pick one that is on by default.
2489        let list = s.route("GET", "/api/loop/analyzers", b"", Some("tok"), None);
2490        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
2491        let id = v["analyzers"]
2492            .as_array()
2493            .unwrap()
2494            .iter()
2495            .find(|x| x["enabled"] == true)
2496            .expect("some analyzer is on")["id"]
2497            .as_str()
2498            .unwrap()
2499            .to_string();
2500
2501        // Disable it via the console endpoint.
2502        let post = s.route(
2503            "POST",
2504            "/api/loop/config",
2505            format!(r#"{{"analyzer_id":"{id}","enabled":false}}"#).as_bytes(),
2506            Some("tok"),
2507            None,
2508        );
2509        assert!(text(&post).contains("\"ok\":true"), "config: {}", text(&post));
2510
2511        // It reads back disabled.
2512        let list2 = s.route("GET", "/api/loop/analyzers", b"", Some("tok"), None);
2513        let v2: serde_json::Value = serde_json::from_slice(&list2.2).unwrap();
2514        let now = v2["analyzers"]
2515            .as_array()
2516            .unwrap()
2517            .iter()
2518            .find(|x| x["id"] == id.as_str())
2519            .unwrap();
2520        assert_eq!(now["enabled"], false, "toggled off and persisted");
2521    }
2522
2523    #[test]
2524    fn self_approval_surfaces_lop_code() {
2525        let s = server(Some("tok"));
2526        s.route("POST", "/api/loop/run", b"{}", Some("tok"), None);
2527        let list = s.route("GET", "/api/loop/recommendations?status=pending", b"", Some("tok"), None);
2528        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
2529        let rec = &v["recommendations"].as_array().unwrap()[0];
2530        let hash = rec["hash"].as_str().unwrap();
2531        let analyzer = rec["analyzer"].as_str().unwrap();
2532        let creator = format!("engine:{analyzer}");
2533        // The engine actor approving its own proposal is blocked.
2534        let rev = s.route(
2535            "POST",
2536            "/api/loop/review",
2537            format!(r#"{{"hash":"{hash}","decision":"approve","because":"self","actor":"{creator}"}}"#).as_bytes(),
2538            Some("tok"),
2539            None,
2540        );
2541        assert!(text(&rev).contains("LOP-E021"), "self-approval blocked: {}", text(&rev));
2542    }
2543}
2544
2545#[cfg(test)]
2546mod security_tests {
2547    use super::{base64_decode, basic_auth_password, ct_eq, normalize_origin, redact_dsn};
2548
2549    #[test]
2550    fn ct_eq_matches_only_equal() {
2551        assert!(ct_eq(b"secret-token", b"secret-token"));
2552        assert!(!ct_eq(b"secret-token", b"secret-toker"));
2553        assert!(!ct_eq(b"secret", b"secret-token")); // length mismatch
2554        assert!(ct_eq(b"", b""));
2555    }
2556
2557    #[test]
2558    fn base64_decode_roundtrips_known_vectors() {
2559        // RFC 4648 test vectors (with and without padding).
2560        assert_eq!(base64_decode("").unwrap(), b"");
2561        assert_eq!(base64_decode("Zg==").unwrap(), b"f");
2562        assert_eq!(base64_decode("Zm8=").unwrap(), b"fo");
2563        assert_eq!(base64_decode("Zm9v").unwrap(), b"foo");
2564        assert_eq!(base64_decode("Zm9vYmFy").unwrap(), b"foobar");
2565        // padding is optional for us
2566        assert_eq!(base64_decode("Zg").unwrap(), b"f");
2567        // invalid characters are rejected
2568        assert!(base64_decode("****").is_none());
2569    }
2570
2571    #[test]
2572    fn basic_auth_extracts_password_ignoring_username() {
2573        // base64("areev:s3cret") and base64(":s3cret") both yield the token.
2574        assert_eq!(basic_auth_password("ZGVqYTpzM2NyZXQ=").as_deref(), Some("s3cret"));
2575        assert_eq!(basic_auth_password("OnMzY3JldA==").as_deref(), Some("s3cret"));
2576        // a password may itself contain ':' — only the first ':' splits.
2577        // base64("u:a:b") -> "a:b"
2578        assert_eq!(basic_auth_password("dTphOmI=").as_deref(), Some("a:b"));
2579        // no ':' at all → not a valid Basic credential
2580        assert_eq!(basic_auth_password("bm9jb2xvbg=="), None); // "nocolon"
2581        assert_eq!(basic_auth_password("****"), None); // not base64
2582    }
2583
2584    // ── redact_dsn (issue #124) ─────────────────────────────────────────
2585
2586    #[test]
2587    fn redact_dsn_hides_a_password() {
2588        assert_eq!(
2589            redact_dsn("postgresql://rounic:SUPERSECRET@pg-x:5432/rounic?sslmode=verify-full&schema=desk_invoice"),
2590            "postgresql://rounic:***@pg-x:5432/rounic?sslmode=verify-full&schema=desk_invoice",
2591        );
2592    }
2593
2594    #[test]
2595    fn redact_dsn_leaves_no_password_alone() {
2596        assert_eq!(redact_dsn("postgres://user@host:5432/db"), "postgres://user@host:5432/db");
2597    }
2598
2599    #[test]
2600    fn redact_dsn_leaves_no_userinfo_alone() {
2601        assert_eq!(redact_dsn("postgres://host:5432/db"), "postgres://host:5432/db");
2602    }
2603
2604    #[test]
2605    fn redact_dsn_leaves_a_plain_file_path_alone() {
2606        assert_eq!(redact_dsn("demo.db"), "demo.db");
2607        assert_eq!(redact_dsn("/var/lib/areev/demo.db"), "/var/lib/areev/demo.db");
2608    }
2609
2610    #[test]
2611    fn redact_dsn_hides_a_percent_encoded_password() {
2612        // %40 is an encoded '@' inside the password — the LITERAL '@' that
2613        // ends the authority is the one after it.
2614        assert_eq!(
2615            redact_dsn("postgres://user:pa%40ss@host:5432/db"),
2616            "postgres://user:***@host:5432/db",
2617        );
2618    }
2619
2620    #[test]
2621    fn redact_dsn_hides_a_password_with_a_literal_at_sign() {
2622        // The LAST '@' in the authority is the userinfo/host boundary, so a
2623        // literal '@' inside the password is presumed to be part of it.
2624        assert_eq!(
2625            redact_dsn("postgres://user:p@ss@host:5432/db"),
2626            "postgres://user:***@host:5432/db",
2627        );
2628    }
2629
2630    #[test]
2631    fn redact_dsn_ignores_colon_and_at_in_the_query_string() {
2632        assert_eq!(
2633            redact_dsn("postgres://user:pass@host:5432/db?options=-c%20foo:bar@baz"),
2634            "postgres://user:***@host:5432/db?options=-c%20foo:bar@baz",
2635        );
2636    }
2637
2638    #[test]
2639    fn redact_dsn_handles_empty_string() {
2640        assert_eq!(redact_dsn(""), "");
2641    }
2642
2643    // ── normalize_origin (issue #125) ───────────────────────────────────
2644
2645    #[test]
2646    fn normalize_origin_lowercases_and_drops_one_trailing_slash() {
2647        assert_eq!(normalize_origin("https://Console.Example.com"), "https://console.example.com");
2648        assert_eq!(normalize_origin("https://console.example.com/"), "https://console.example.com");
2649        assert_eq!(
2650            normalize_origin("HTTPS://Console.Example.com/"),
2651            "https://console.example.com",
2652        );
2653    }
2654}
2655
2656#[cfg(test)]
2657mod credential_route_tests {
2658    use super::UiServer;
2659    use areev_cal::AreevFacade;
2660    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
2661    use areev_core::types::{Fact, Grain};
2662    use areev_store::Areev;
2663
2664    /// The tuning seam over HTTP: an adapter recommendation applies only
2665    /// with `gating_run` in the POST body — evidence loaded from the
2666    /// journaled eval summary, never from the client — and the rec row
2667    /// carries `evalset_hash` so the console knows the apply is gated.
2668    #[test]
2669    fn loop_apply_honors_a_gating_run() {
2670        let dir = tempfile::tempdir().unwrap();
2671        let path = dir.path().join("g.db");
2672        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
2673        // The pin and a clean recorded gate run, as `areev eval` writes them.
2674        let evalset = store
2675            .add(
2676                &Fact::new("evalset:gate", "mg:evalset", "{\"name\":\"gate\",\"cases\":[]}")
2677                    .namespace("agent:harness")
2678                    .created_at(1_000),
2679            )
2680            .unwrap()
2681            .to_hex();
2682        store
2683            .add(
2684                &Fact::new(
2685                    &format!("evalset:{evalset}"),
2686                    "mg:eval_run",
2687                    "{\"run_id\":\"eval-1\",\"passed\":3,\"failed\":0}",
2688                )
2689                .namespace("agent:harness")
2690                .created_at(2_000),
2691            )
2692            .unwrap();
2693        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(3_000)).unwrap();
2694        std::mem::forget(dir);
2695        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2696        // Register an adapter with real lineage (a recorded corpus export).
2697        let manifest = facade
2698            .record_corpus_export("RECALL facts", "train.jsonl", None, 4_000, &[], &[])
2699            .unwrap()
2700            .to_hex();
2701        facade
2702            .record_adapter(
2703                r#"{"adapter":{"uri":"file:///tmp/a","sha256":"feed"},"base_model":"qwen3-4b","serves_as":"acme-support"}"#,
2704                &manifest,
2705                &evalset,
2706                5_000,
2707            )
2708            .unwrap();
2709        // Token mode: the shared secret is the implied local owner — the
2710        // token-less console is read-only by design.
2711        let s = UiServer::new(facade, "test".into()).with_auth("gate-token".into());
2712        let tok = Some("gate-token");
2713
2714        // Propose, then find the adapter rec — its row must carry the pin.
2715        let run = s.route("POST", "/api/loop/run", b"{}", tok, None);
2716        assert!(run.0.starts_with("200"), "{}", text(&run));
2717        let list = s.route("GET", "/api/loop/recommendations?status=pending", b"", tok, None);
2718        let rows: serde_json::Value = serde_json::from_str(&text(&list)).unwrap();
2719        let rec = rows["recommendations"]
2720            .as_array()
2721            .unwrap()
2722            .iter()
2723            .find(|r| r["analyzer"].as_str().unwrap_or("").contains("adapter_intake"))
2724            .unwrap_or_else(|| panic!("adapter_intake must propose: {rows}"));
2725        assert_eq!(rec["evalset_hash"], evalset.as_str(), "the row must carry the pin");
2726        let hash = rec["hash"].as_str().unwrap().to_string();
2727
2728        // Approve (the console's first POST), then: ungated apply refused,
2729        // a bad run id refused, the recorded run admits.
2730        let approve = format!(r#"{{"hash":"{hash}","decision":"approve","because":"reviewed"}}"#);
2731        let r = s.route("POST", "/api/loop/review", approve.as_bytes(), tok, None);
2732        assert!(text(&r).contains("\"ok\":true"), "{}", text(&r));
2733        let bare = format!(r#"{{"hash":"{hash}","because":"ship it"}}"#);
2734        let r = s.route("POST", "/api/loop/apply", bare.as_bytes(), tok, None);
2735        assert!(text(&r).contains("gating run"), "ungated must refuse: {}", text(&r));
2736        let bad = format!(r#"{{"hash":"{hash}","because":"ship","gating_run":"eval-nope"}}"#);
2737        let r = s.route("POST", "/api/loop/apply", bad.as_bytes(), tok, None);
2738        assert!(text(&r).contains("no recorded gate run"), "{}", text(&r));
2739        let good = format!(r#"{{"hash":"{hash}","because":"gated and green","gating_run":"eval-1"}}"#);
2740        let r = s.route("POST", "/api/loop/apply", good.as_bytes(), tok, None);
2741        assert!(text(&r).contains("\"ok\":true"), "gated apply failed: {}", text(&r));
2742    }
2743
2744    /// A server in credential-map mode: two env-referenced tokens, rights
2745    /// seeded as grant grains in the file itself.
2746    fn server() -> UiServer {
2747        std::env::set_var("AREEV_TEST_READER_TOK", "reader-secret");
2748        std::env::set_var("AREEV_TEST_WRITER_TOK", "writer-secret");
2749        let dir = tempfile::tempdir().unwrap();
2750        let path = dir.path().join("t.db");
2751        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
2752        store
2753            .add(&Fact::new("user:reader", REL_PERMITS, "read ON *").namespace(AUTHZ_NS).created_at(1_000))
2754            .unwrap();
2755        store
2756            .add(
2757                &Fact::new("agent:writer", REL_PERMITS, "read,write ON caller")
2758                    .namespace(AUTHZ_NS)
2759                    .created_at(2_000),
2760            )
2761            .unwrap();
2762        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(3_000)).unwrap();
2763        std::mem::forget(dir);
2764        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2765        let map = CredentialMap::from_json(
2766            r#"{"version":1,"tokens":[
2767                {"env":"AREEV_TEST_READER_TOK","principal":"user:reader"},
2768                {"env":"AREEV_TEST_WRITER_TOK","principal":"agent:writer"}
2769            ]}"#,
2770        )
2771        .unwrap();
2772        UiServer::new(facade, "test".into()).with_credentials(map)
2773    }
2774
2775    fn text(r: &(&str, &str, Vec<u8>)) -> String {
2776        String::from_utf8_lossy(&r.2).to_string()
2777    }
2778
2779    const READ: &[u8] = br#"{"query":"RECALL facts WHERE subject = \"acme\""}"#;
2780    const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
2781
2782    #[test]
2783    fn tokens_bind_principals_and_verbs_decide() {
2784        let s = server();
2785
2786        // The reader reads…
2787        let r = s.route("POST", "/api/cal", READ, Some("reader-secret"), None);
2788        assert!(r.0.starts_with("200"), "{}", text(&r));
2789        assert!(text(&r).contains("grains"));
2790        // …and cannot write.
2791        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
2792        assert!(text(&w).contains("AUT-E001"), "reader write must be refused: {}", text(&w));
2793
2794        // The writer writes.
2795        let w = s.route("POST", "/api/cal", WRITE, Some("writer-secret"), None);
2796        assert!(text(&w).contains("added"), "writer write must land: {}", text(&w));
2797
2798        // Sequential isolation: the very next reader request is still
2799        // read-only — nothing leaked from the writer's binding.
2800        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
2801        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
2802    }
2803
2804    #[test]
2805    fn anonymous_is_read_only_and_loop_run_is_verb_gated() {
2806        let s = server();
2807        // No token → anonymous: reads work…
2808        let r = s.route("POST", "/api/cal", READ, None, None);
2809        assert!(r.0.starts_with("200"), "{}", text(&r));
2810        assert!(text(&r).contains("grains"));
2811        // …writes are verb-refused…
2812        let w = s.route("POST", "/api/cal", WRITE, None, None);
2813        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
2814        // …and an unknown token is anonymous too, never an escalation.
2815        let w = s.route("POST", "/api/cal", WRITE, Some("stolen-guess"), None);
2816        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
2817
2818        // The analysis trigger needs loop.run — anonymous gets 403.
2819        let run = s.route("POST", "/api/loop/run", b"{}", None, None);
2820        assert!(run.0.starts_with("403"), "{}", text(&run));
2821    }
2822
2823    #[test]
2824    fn whoami_reports_the_bound_principal() {
2825        let s = server();
2826        let r = s.route("GET", "/api/whoami", b"", Some("reader-secret"), None);
2827        assert!(text(&r).contains("user:reader"), "{}", text(&r));
2828        assert!(text(&r).contains("credentials"));
2829        let r = s.route("GET", "/api/whoami", b"", None, None);
2830        assert!(text(&r).contains("anonymous"), "{}", text(&r));
2831    }
2832
2833    /// A credential map must not silently disable `--token-env`. Attaching
2834    /// one changes WHO a request is; the operator who also asked for a
2835    /// shared secret still gets authentication on every request.
2836    #[test]
2837    fn a_credential_map_does_not_disable_the_shared_secret() {
2838        let s = server().with_auth("console-token".into());
2839
2840        // No credential at all: refused, not dropped to `anonymous`.
2841        let r = s.route("POST", "/api/cal", READ, None, None);
2842        assert!(r.0.starts_with("401"), "{}", text(&r));
2843        let page = s.route("GET", "/", b"", None, None);
2844        assert!(page.0.starts_with("401"), "the console page is guarded too");
2845        // An unrecognized token is refused rather than downgraded.
2846        let r = s.route("POST", "/api/cal", READ, Some("stolen-guess"), None);
2847        assert!(r.0.starts_with("401"), "{}", text(&r));
2848
2849        // A map token still binds its principal and its verbs still decide.
2850        let r = s.route("POST", "/api/cal", READ, Some("reader-secret"), None);
2851        assert!(r.0.starts_with("200"), "{}", text(&r));
2852        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
2853        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
2854
2855        // The shared secret is the implied admin (docs/cal-all-you-need
2856        // -proposal.md §5.2b) — it keeps the owner session it always had.
2857        let w = s.route("POST", "/api/cal", WRITE, Some("console-token"), None);
2858        assert!(text(&w).contains("added"), "{}", text(&w));
2859    }
2860
2861    /// `RUN LOOP` through CAL is gated exactly as `POST /api/loop/run` is —
2862    /// otherwise the CAL surface is a way around the HTTP gate.
2863    #[test]
2864    fn run_loop_via_cal_is_verb_gated_like_the_route() {
2865        let s = server();
2866        let run = s.route("POST", "/api/loop/run", b"{}", None, None);
2867        assert!(run.0.starts_with("403"), "{}", text(&run));
2868        let cal = s.route("POST", "/api/cal", br#"{"query":"RUN LOOP"}"#, None, None);
2869        assert!(
2870            text(&cal).contains("AUT-E001"),
2871            "anonymous must not run the loop through CAL either: {}",
2872            text(&cal)
2873        );
2874    }
2875}
2876
2877#[cfg(test)]
2878mod namespace_route_tests {
2879    use super::UiServer;
2880    use areev_cal::AreevFacade;
2881    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
2882    use areev_core::types::{Fact, Grain};
2883    use areev_store::Areev;
2884
2885    fn text(r: &(&str, &str, Vec<u8>)) -> String {
2886        String::from_utf8_lossy(&r.2).to_string()
2887    }
2888
2889    /// `agent:writer` is granted read+write on `caller` only — nothing on
2890    /// `other`, nothing on the audit namespace.
2891    fn restricted_server() -> UiServer {
2892        std::env::set_var("AREEV_TEST_NS_WRITER_TOK", "writer-secret");
2893        let dir = tempfile::tempdir().unwrap();
2894        let path = dir.path().join("t.db");
2895        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
2896        store
2897            .add(&Fact::new("agent:writer", REL_PERMITS, "read,write ON caller").namespace(AUTHZ_NS).created_at(1_000))
2898            .unwrap();
2899        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(2_000)).unwrap();
2900        store.add(&Fact::new("bob", "role", "admin").namespace("other").created_at(3_000)).unwrap();
2901        std::mem::forget(dir);
2902        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2903        let map = CredentialMap::from_json(
2904            r#"{"version":1,"tokens":[{"env":"AREEV_TEST_NS_WRITER_TOK","principal":"agent:writer"}]}"#,
2905        )
2906        .unwrap();
2907        UiServer::new(facade, "test".into()).with_credentials(map)
2908    }
2909
2910    /// Unbound local open — the implicit owner, unrestricted on every
2911    /// namespace, same as a plain `areev ui` with no `--auth`.
2912    fn owner_server() -> UiServer {
2913        let dir = tempfile::tempdir().unwrap();
2914        let path = dir.path().join("t.db");
2915        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
2916        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(1_000)).unwrap();
2917        store.add(&Fact::new("bob", "role", "admin").namespace("other").created_at(2_000)).unwrap();
2918        std::mem::forget(dir);
2919        UiServer::new(AreevFacade::with_session(store, Some("caller".into()), None), "t".into())
2920    }
2921
2922    #[test]
2923    fn namespaces_route_hides_what_the_principal_cannot_read() {
2924        let s = restricted_server();
2925        let r = s.route("GET", "/api/namespaces", b"", Some("writer-secret"), None);
2926        let body = text(&r);
2927        assert!(body.contains("\"caller\""), "granted namespace must be listed: {body}");
2928        assert!(!body.contains("\"other\""), "ungranted namespace must not be listed: {body}");
2929        assert!(!body.contains(AUTHZ_NS), "the audit namespace must not leak either: {body}");
2930    }
2931
2932    #[test]
2933    fn namespaces_route_lists_everything_for_the_owner() {
2934        let s = owner_server();
2935        let r = s.route("GET", "/api/namespaces", b"", None, None);
2936        let body = text(&r);
2937        assert!(body.contains("\"caller\"") && body.contains("\"other\""), "{body}");
2938    }
2939
2940    #[test]
2941    fn browse_ns_param_is_read_gated_for_a_restricted_principal() {
2942        let s = restricted_server();
2943        let ok = s.route("GET", "/api/browse?ns=caller", b"", Some("writer-secret"), None);
2944        assert!(text(&ok).contains("\"ok\":true"), "their own granted namespace must work: {}", text(&ok));
2945
2946        let denied = s.route("GET", "/api/browse?ns=other", b"", Some("writer-secret"), None);
2947        let body = text(&denied);
2948        assert!(body.contains("\"ok\":false"), "an ungranted namespace must be refused, not silently emptied: {body}");
2949    }
2950
2951    #[test]
2952    fn browse_ns_star_requires_owner() {
2953        let s = restricted_server();
2954        let r = s.route("GET", "/api/browse?ns=*", b"", Some("writer-secret"), None);
2955        assert!(text(&r).contains("\"ok\":false"), "a restricted principal must not get the unfiltered view: {}", text(&r));
2956
2957        let owner = owner_server();
2958        let r2 = owner.route("GET", "/api/browse?ns=*", b"", None, None);
2959        let body2 = text(&r2);
2960        assert!(body2.contains("\"ok\":true"), "the owner session may lift the filter: {body2}");
2961        assert!(body2.contains("\"caller\"") && body2.contains("\"other\""), "{body2}");
2962    }
2963
2964    #[test]
2965    fn browse_without_ns_param_keeps_original_session_default_behavior() {
2966        let s = owner_server();
2967        let r = s.route("GET", "/api/browse", b"", None, None);
2968        let body = text(&r);
2969        assert!(body.contains("\"caller\""), "{body}");
2970        assert!(!body.contains("\"other\""), "omitting ?ns must behave exactly as before this feature existed: {body}");
2971    }
2972}
2973
2974#[cfg(test)]
2975mod builder_tests {
2976    use super::UiServer;
2977    use areev_cal::AreevFacade;
2978    use areev_store::Areev;
2979
2980    fn server() -> UiServer {
2981        let dir = tempfile::tempdir().unwrap();
2982        let path = dir.path().join("t.db");
2983        let store = Areev::open(path.to_str().unwrap()).unwrap();
2984        std::mem::forget(dir);
2985        UiServer::new(AreevFacade::with_session(store, Some("caller".into()), None), "t".into())
2986    }
2987
2988    /// `areev ui --no-destructive-ops --policy FILE` calls these in this
2989    /// order. A later builder must not re-enable destruction the operator
2990    /// turned off — the console was announced as read-only.
2991    #[test]
2992    fn attaching_a_loop_policy_preserves_the_destructive_cap() {
2993        let s = server()
2994            .allow_destructive_ops(false)
2995            .with_loop_policy(areev_loop::Policy::default());
2996        let r = s.route(
2997            "POST",
2998            "/api/cal",
2999            br#"{"query":"FORGET sha256:684c6c9bda818630a870119d0726e4d242ed537af061658ef6f3acb158a2c67d"}"#,
3000            None,
3001            None,
3002        );
3003        let body = String::from_utf8_lossy(&r.2).to_string();
3004        assert!(
3005            body.contains("--no-destructive-ops") || r.0.starts_with("401"),
3006            "destruction must stay disabled: {body}"
3007        );
3008    }
3009}
3010
3011#[cfg(test)]
3012mod run_api_tests {
3013    use super::UiServer;
3014    use areev_cal::AreevFacade;
3015    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
3016    use areev_core::types::{Fact, Grain, Tool, ToolKind, Workflow};
3017    use areev_store::Areev;
3018    use std::sync::Arc;
3019
3020    /// A server whose file holds a PARKED run (Client-gated approve node) —
3021    /// the HITL queue's fixture. Returns (server, ask id).
3022    fn parked_server() -> (UiServer, String) {
3023        std::env::set_var("AREEV_RUN_OFFICER_TOK", "officer-secret");
3024        std::env::set_var("AREEV_RUN_STARTER_TOK", "starter-secret");
3025        let dir = tempfile::tempdir().unwrap();
3026        let path = dir.path().join("t.db");
3027        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
3028        for (who, what) in [
3029            ("user:officer", "read,run.respond ON ops"),
3030            ("user:starter", "read ON ops"),
3031        ] {
3032            store
3033                .add(&Fact::new(who, REL_PERMITS, what).namespace(AUTHZ_NS).created_at(900))
3034                .unwrap();
3035        }
3036        std::mem::forget(dir);
3037        let facade = Arc::new(AreevFacade::with_session(store, Some("ops".into()), None));
3038
3039        // Seed + run the plan to the park with a scripted runner.
3040        let (wf, _g, _a) = facade
3041            .with_store(|m| {
3042                let greet = Tool::new("greet")
3043                    .kind(ToolKind::Definition)
3044                    .tool_description("t")
3045                    .created_at(500)
3046                    .namespace("ops");
3047                let gh = m.add(&greet)?;
3048                let approve = Tool::new("approve")
3049                    .kind(ToolKind::Definition)
3050                    .tool_description("human approves")
3051                    .executor_kind(areev_core::types::ExecutorKind::Client)
3052                    .created_at(501)
3053                    .namespace("ops");
3054                let ah = m.add(&approve)?;
3055                let wf = Workflow::new(vec!["greet".into(), "approve".into()])
3056                    .edge("greet", "approve")
3057                    .bind("greet", &gh.to_hex())
3058                    .bind("approve", &ah.to_hex())
3059                    .created_at(502)
3060                    .namespace("ops");
3061                let wh = m.add(&wf)?;
3062                Ok::<_, areev_core::error::AreevError>((wh, gh, ah))
3063            })
3064            .unwrap();
3065        struct Ok1;
3066        impl areev_run::HostToolExecutor for Ok1 {
3067            fn execute(
3068                &self,
3069                t: &str,
3070                _h: &str,
3071                _i: &serde_json::Value,
3072                _k: &str,
3073            ) -> areev_run::ExecResult {
3074                areev_run::ExecResult::Ok(serde_json::json!({t.to_string(): true}))
3075            }
3076        }
3077        let runner = areev_run::Runner {
3078            facade: Arc::clone(&facade),
3079            clock: Arc::new(areev_run::ScriptedClock::new(
3080                (0..100).map(|i| 1_758_000_000_000 + i * 10).collect(),
3081            )),
3082            executor: Arc::new(Ok1),
3083            llm: None,
3084            observer: None,
3085            ns: "ops".into(),
3086            principal: "user:starter".into(),
3087        };
3088        let session = runner
3089            .start(&wf, "hitl-1", serde_json::json!({}), &areev_run::RunOptions {
3090                workers: 1,
3091                ..Default::default()
3092            })
3093            .unwrap();
3094        let areev_run::RunSession::Parked { envelope, .. } = session else {
3095            panic!("expected park")
3096        };
3097        let ask = envelope["asks"][0]["tool_call_id"].as_str().unwrap().to_string();
3098
3099        // Rebuild a facade-owning server over the SAME file is impossible
3100        // (single writer) — hand the server the same Arc'd facade via the
3101        // Arc-aware constructor path: UiServer::new takes AreevFacade, so
3102        // we build the server FIRST in real deployments; here we reuse the
3103        // internal Arc through a second UiServer field write. Instead:
3104        // drop the runner (facade Arc count drops) and unwrap.
3105        drop(runner);
3106        let facade = Arc::try_unwrap(facade).unwrap_or_else(|_| panic!("facade still shared"));
3107        let map = CredentialMap::from_json(
3108            r#"{"version":1,"tokens":[
3109                {"env":"AREEV_RUN_OFFICER_TOK","principal":"user:officer"},
3110                {"env":"AREEV_RUN_STARTER_TOK","principal":"user:starter"}
3111            ]}"#,
3112        )
3113        .unwrap();
3114        let server = UiServer::new(facade, "test".into())
3115            .with_auth("shared-console-secret".into())
3116            .with_credentials(map);
3117        (server, ask)
3118    }
3119
3120    fn body(run_id: &str, ask: &str) -> Vec<u8> {
3121        serde_json::json!({"run_id": run_id, "tool_call_id": ask, "result": {"approved": true}})
3122            .to_string()
3123            .into_bytes()
3124    }
3125
3126    /// #165: `/api/run/list` is scoped and paged on the server, and says
3127    /// its total and whether it truncated. Twenty older runs in a quiet
3128    /// namespace behind forty newer ones in a busy one is exactly the
3129    /// shape under which the old fixed newest-50 page, filtered
3130    /// client-side, showed the quiet tenant as having no runs.
3131    #[test]
3132    fn run_list_is_scoped_and_paged_server_side() {
3133        let dir = tempfile::tempdir().unwrap();
3134        let path = dir.path().join("t.db");
3135        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
3136        for i in 0..60u32 {
3137            let (id, ns) = if i < 20 {
3138                (format!("quiet-{i}"), "tenant.quiet")
3139            } else {
3140                (format!("busy-{i}"), "tenant.busy")
3141            };
3142            let mut f = Fact::new(&format!("run:{id}"), "mg:harness", "00")
3143                .namespace(areev_core::authz::HARNESS_NS)
3144                .created_at(1_000 + i64::from(i));
3145            f.common.extra_fields.insert("run_id".into(), serde_json::json!(id));
3146            f.common.extra_fields.insert("run_ns".into(), serde_json::json!(ns));
3147            store.add(&f).unwrap();
3148        }
3149        std::mem::forget(dir);
3150        let s = UiServer::new(AreevFacade::with_session(store, Some("ops".into()), None), "test".into());
3151        let page = |query: &str| -> serde_json::Value {
3152            let r = s.route("GET", &format!("/api/run/list{query}"), b"", None, None);
3153            assert!(r.0.starts_with("200"), "{} {}", r.0, String::from_utf8_lossy(&r.2));
3154            serde_json::from_slice(&r.2).unwrap()
3155        };
3156        let rows = |v: &serde_json::Value| v["runs"].as_array().unwrap().clone();
3157
3158        // The default page: newest fifty of sixty, and it SAYS so.
3159        let all = page("");
3160        assert_eq!(rows(&all).len(), 50);
3161        assert_eq!(all["total"], 60);
3162        assert_eq!(all["truncated"], true);
3163        assert_eq!(rows(&all).iter().filter(|r| r["ns"] == "tenant.quiet").count(), 10);
3164
3165        // Scoped: the whole quiet tenant, no truncation, nothing else.
3166        let quiet = page("?ns=tenant.quiet");
3167        assert_eq!(quiet["total"], 20);
3168        assert_eq!(quiet["truncated"], false);
3169        assert_eq!(rows(&quiet).len(), 20);
3170        assert!(rows(&quiet).iter().all(|r| r["ns"] == "tenant.quiet"), "{quiet}");
3171
3172        // A prefix scope, paged to the end.
3173        let tail = page("?ns=tenant.*&limit=10&offset=55");
3174        assert_eq!(tail["total"], 60);
3175        assert_eq!(rows(&tail).len(), 5);
3176        assert_eq!(tail["truncated"], false);
3177        assert_eq!((tail["offset"].as_u64(), tail["limit"].as_u64()), (Some(55), Some(10)));
3178
3179        // `*` is unscoped; an absurd limit is clamped rather than honored.
3180        assert_eq!(page("?ns=*")["total"], 60);
3181        assert_eq!(page("?limit=100000")["limit"], 500);
3182
3183        // A row from before the namespace stamp is not known to be in any
3184        // scope: excluded from a scoped read and COUNTED, present unscoped.
3185        s.facade
3186            .with_store(|m| {
3187                let mut f = Fact::new("run:old", "mg:harness", "00")
3188                    .namespace(areev_core::authz::HARNESS_NS)
3189                    .created_at(1);
3190                f.common.extra_fields.insert("run_id".into(), serde_json::json!("old"));
3191                m.add(&f)
3192            })
3193            .unwrap();
3194        let quiet = page("?ns=tenant.quiet");
3195        assert_eq!(quiet["total"], 20, "scoping stays exact: {quiet}");
3196        assert_eq!(quiet["unattributed"], 1, "and says what it left out: {quiet}");
3197        let unscoped = page("");
3198        assert_eq!(unscoped["total"], 61);
3199        assert_eq!(unscoped["unattributed"], 0);
3200    }
3201
3202    #[test]
3203    fn shared_token_approvals_are_refused_and_principals_approve() {
3204        let (s, ask) = parked_server();
3205
3206        // The HITL queue is visible.
3207        let r = s.route("GET", "/api/run/list", b"", Some("shared-console-secret"), None);
3208        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
3209        let r = s.route(
3210            "GET",
3211            "/api/run/inspect?run_id=hitl-1",
3212            b"",
3213            Some("shared-console-secret"),
3214            None,
3215        );
3216        assert!(String::from_utf8_lossy(&r.2).contains(&ask), "ask visible in inspect");
3217
3218        // 1. The SHARED console secret cannot approve — identity is the point.
3219        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("shared-console-secret"), None);
3220        assert!(r.0.starts_with("403"), "shared-token approval must refuse: {}", r.0);
3221
3222        // 2. The STARTER's own credential cannot approve their own run
3223        //    (separation of duties, enforced by the runtime).
3224        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("starter-secret"), None);
3225        let text = String::from_utf8_lossy(&r.2).to_string();
3226        assert!(text.contains("responder") || text.contains("RUN-E012"), "{text}");
3227
3228        // 3. The officer's principal-bound credential approves.
3229        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("officer-secret"), None);
3230        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
3231        assert!(String::from_utf8_lossy(&r.2).contains("user:officer"));
3232
3233        // 4. The kill switch keeps its low bar: shared token may cancel.
3234        let r = s.route(
3235            "POST",
3236            "/api/run/cancel",
3237            br#"{"run_id":"hitl-1","because":"test brake"}"#,
3238            Some("shared-console-secret"),
3239            None,
3240        );
3241        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
3242    }
3243
3244    /// [A0] The approval trust floor. `user:officer` holds `run.respond ON
3245    /// ops` in the FILE, so the grants are identical whichever way the
3246    /// identity arrives — which is exactly the point. What differs is the
3247    /// PROOF: a credential-map token is a per-principal secret; an SSO header
3248    /// is trusted via one shared, fleet-wide proxy secret that lets its
3249    /// holder assert any approver. The default refuses the weaker proof.
3250    #[test]
3251    fn proxy_asserted_identities_cannot_approve_by_default() {
3252        let (s, ask) = parked_server();
3253        let s = s.with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>);
3254
3255        // The SSO identity is a GRANTED principal and still cannot approve.
3256        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), None, Some("user:officer"));
3257        assert!(
3258            r.0.starts_with("403"),
3259            "proxy-asserted approval must refuse by default: {} {}",
3260            r.0,
3261            String::from_utf8_lossy(&r.2)
3262        );
3263        let text = String::from_utf8_lossy(&r.2).to_string();
3264        assert!(
3265            text.contains("--sso-approvals"),
3266            "the refusal must name the flag that lifts it: {text}"
3267        );
3268
3269        // Reviewing is unaffected — SSO identities keep every read.
3270        let r = s.route("GET", "/api/run/list", b"", None, Some("user:officer"));
3271        assert!(r.0.starts_with("200"), "SSO identities may still review: {}", r.0);
3272
3273        // And the SAME principal, proven by its own credential, approves.
3274        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("officer-secret"), None);
3275        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
3276    }
3277
3278    /// [A0] `--sso-approvals allow` is the operator accepting that trade-off
3279    /// explicitly. Nothing else changes: the same identity, the same file
3280    /// grants, the same runtime separation-of-duties check behind it.
3281    #[test]
3282    fn sso_approvals_allow_opts_in_to_proxy_asserted_approvals() {
3283        let (s, ask) = parked_server();
3284        let s = s
3285            .with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>)
3286            .with_sso_approvals(true);
3287
3288        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), None, Some("user:officer"));
3289        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
3290        assert!(String::from_utf8_lossy(&r.2).contains("user:officer"));
3291    }
3292
3293    /// [A2] Groups → principals, so SSO scales without a grant grain per
3294    /// person — and the precedence that makes it safe: an identity with its
3295    /// own grants outranks its group, so adding a groups header can never
3296    /// narrow someone who already had rights.
3297    #[test]
3298    fn groups_resolve_to_principals_but_never_outrank_an_identity() {
3299        let (s, _ask) = parked_server();
3300        // `user:officer` is granted in the file; `role:reviewer` is not a
3301        // credential, only a group target.
3302        let map = CredentialMap::from_json(
3303            r#"{"version":1,
3304                "tokens":[{"env":"AREEV_RUN_OFFICER_TOK","principal":"user:officer","id":"off"}],
3305                "groups":{"Engineering":"user:officer"}}"#,
3306        )
3307        .unwrap();
3308        let s = s
3309            .with_credentials(map)
3310            .with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>)
3311            .with_sso_groups_header("x-forwarded-groups");
3312
3313        // An UNGRANTED identity in a mapped group inherits the group's
3314        // principal — the whole point of the feature.
3315        let r = s.route_with_groups(
3316            "GET",
3317            "/api/whoami",
3318            b"",
3319            None,
3320            Some("user:newhire@example.com"),
3321            Some("platform,Engineering"),
3322        );
3323        let text = String::from_utf8_lossy(&r.2).to_string();
3324        assert!(text.contains("user:officer"), "group should resolve: {text}");
3325        assert!(text.contains(r#""identity_source":"sso-group""#), "{text}");
3326
3327        // Case-insensitive: directories are inconsistent, and a mapping that
3328        // misses on case would fail OPEN into the identity's own (empty)
3329        // grants.
3330        let r = s.route_with_groups(
3331            "GET", "/api/whoami", b"", None, Some("user:newhire@example.com"), Some("ENGINEERING"),
3332        );
3333        assert!(String::from_utf8_lossy(&r.2).contains("user:officer"));
3334
3335        // An identity that IS granted keeps its own principal, group or not.
3336        let r = s.route_with_groups(
3337            "GET", "/api/whoami", b"", None, Some("user:officer"), Some("Engineering"),
3338        );
3339        let text = String::from_utf8_lossy(&r.2).to_string();
3340        assert!(text.contains(r#""identity_source":"sso""#), "identity outranks group: {text}");
3341
3342        // An unmapped group resolves to nothing and the identity stands.
3343        let r = s.route_with_groups(
3344            "GET", "/api/whoami", b"", None, Some("user:newhire@example.com"), Some("sales"),
3345        );
3346        assert!(String::from_utf8_lossy(&r.2).contains("user:newhire@example.com"));
3347    }
3348
3349    /// [A2] A role is not an approver. This refusal has no flag of its own —
3350    /// `--sso-approvals allow` does not lift it — because an audit record
3351    /// reading "role:eng approved" names nobody who can be asked why.
3352    #[test]
3353    fn group_derived_principals_can_never_approve() {
3354        let (s, ask) = parked_server();
3355        let map = CredentialMap::from_json(
3356            r#"{"version":1,
3357                "tokens":[{"env":"AREEV_RUN_OFFICER_TOK","principal":"user:officer","id":"off"}],
3358                "groups":{"approvers":"user:officer"}}"#,
3359        )
3360        .unwrap();
3361        let s = s
3362            .with_credentials(map)
3363            .with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>)
3364            .with_sso_groups_header("x-forwarded-groups")
3365            // Even with the A0 opt-in explicitly granted.
3366            .with_sso_approvals(true);
3367
3368        let r = s.route_with_groups(
3369            "POST",
3370            "/api/run/respond",
3371            &body("hitl-1", &ask),
3372            None,
3373            Some("user:newhire@example.com"),
3374            Some("approvers"),
3375        );
3376        assert!(r.0.starts_with("403"), "{} {}", r.0, String::from_utf8_lossy(&r.2));
3377        let text = String::from_utf8_lossy(&r.2).to_string();
3378        assert!(text.contains("role"), "the refusal must say why: {text}");
3379    }
3380
3381    /// [A2] The prefix keeps IdP-sourced principals visibly distinct from
3382    /// local ones everywhere they land.
3383    #[test]
3384    fn the_principal_prefix_is_stamped_on_proxy_asserted_identities() {
3385        let (s, _ask) = parked_server();
3386        let s = s
3387            .with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>)
3388            .with_sso_principal_prefix("sso:");
3389
3390        let r = s.route("GET", "/api/whoami", b"", None, Some("pat@example.com"));
3391        assert!(String::from_utf8_lossy(&r.2).contains("sso:pat@example.com"), "{}", String::from_utf8_lossy(&r.2));
3392
3393        // Idempotent: an identity the proxy already prefixed is not
3394        // double-stamped into a different principal than the grant names.
3395        let r = s.route("GET", "/api/whoami", b"", None, Some("sso:pat@example.com"));
3396        let text = String::from_utf8_lossy(&r.2).to_string();
3397        assert!(text.contains("sso:pat@example.com"), "{text}");
3398        assert!(!text.contains("sso:sso:"), "must not double-stamp: {text}");
3399    }
3400
3401    /// [A0] `whoami` tells an approver where they stand BEFORE they try to
3402    /// approve — a console that only discovers this at the 403 is a console
3403    /// that discovers it mid-incident.
3404    #[test]
3405    fn whoami_reports_identity_provenance_and_approval_capability() {
3406        let (s, _ask) = parked_server();
3407        let s = s.with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>);
3408
3409        let r = s.route("GET", "/api/whoami", b"", None, Some("user:officer"));
3410        let text = String::from_utf8_lossy(&r.2).to_string();
3411        assert!(text.contains(r#""identity_source":"sso""#), "{text}");
3412        assert!(text.contains(r#""may_approve":false"#), "{text}");
3413
3414        let r = s.route("GET", "/api/whoami", b"", Some("officer-secret"), None);
3415        let text = String::from_utf8_lossy(&r.2).to_string();
3416        assert!(text.contains(r#""identity_source":"credential""#), "{text}");
3417        assert!(text.contains(r#""may_approve":true"#), "{text}");
3418    }
3419}
3420
3421#[cfg(test)]
3422mod memory_scoped_token_tests {
3423    use super::UiServer;
3424    use areev_cal::AreevFacade;
3425    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
3426    use areev_core::types::{Fact, Grain};
3427    use areev_store::Areev;
3428
3429    /// The enterprise-plane rule: one auth file, per-memory token
3430    /// scopes — a token listed for memory A is an UNKNOWN token on
3431    /// memory B's server.
3432    #[test]
3433    fn memory_scoped_tokens_do_not_cross_memories() {
3434        std::env::set_var("AREEV_SCOPED_TOK", "scoped-secret");
3435        let map_json = r#"{"version":1,"tokens":[
3436            {"env":"AREEV_SCOPED_TOK","principal":"agent:sync","memories":["memory-a"]}
3437        ]}"#;
3438        let server_for = |label: &str| {
3439            let dir = tempfile::tempdir().unwrap();
3440            let mut store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3441            store
3442                .add(
3443                    &Fact::new("agent:sync", REL_PERMITS, "read,write ON caller")
3444                        .namespace(AUTHZ_NS)
3445                        .created_at(1_000),
3446                )
3447                .unwrap();
3448            store
3449                .add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(2_000))
3450                .unwrap();
3451            std::mem::forget(dir);
3452            let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3453            UiServer::new(facade, label.into())
3454                .with_credentials(CredentialMap::from_json(map_json).unwrap())
3455        };
3456        const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
3457
3458        // On memory-a the token authenticates and its grants let the write
3459        // through (no authorization refusal in the CAL payload).
3460        let a = server_for("memory-a");
3461        let r = a.route("POST", "/api/cal", WRITE, Some("scoped-secret"), None);
3462        let text = String::from_utf8_lossy(&r.2).to_string();
3463        assert!(r.0.starts_with("200") && !text.contains("AUT-E001"), "{text}");
3464
3465        // On memory-b the SAME token is an unknown credential: the request
3466        // runs as anonymous and the write is refused (AUT-E001 rides the
3467        // CAL payload — the console surfaces statement results in-band).
3468        let b = server_for("memory-b");
3469        let r = b.route("POST", "/api/cal", WRITE, Some("scoped-secret"), None);
3470        let text = String::from_utf8_lossy(&r.2).to_string();
3471        assert!(
3472            text.contains("AUT-E001") && text.contains("anonymous"),
3473            "scoped token must not cross memories: {text}"
3474        );
3475
3476        // An auth file with an EMPTY memories scope refuses to load.
3477        assert!(CredentialMap::from_json(
3478            r#"{"version":1,"tokens":[{"env":"AREEV_SCOPED_TOK","principal":"x","memories":[]}]}"#
3479        )
3480        .is_err());
3481    }
3482}
3483
3484#[cfg(all(test, feature = "tls"))]
3485mod tls_tests {
3486    use super::UiServer;
3487    use areev_cal::AreevFacade;
3488    use areev_store::Areev;
3489    use std::io::{Read, Write};
3490
3491    fn self_signed(dir: &std::path::Path) -> Option<(String, String)> {
3492        let cert = dir.join("cert.pem");
3493        let key = dir.join("key.pem");
3494        let status = std::process::Command::new("openssl")
3495            .args([
3496                "req", "-x509", "-newkey", "rsa:2048", "-nodes",
3497                "-keyout", key.to_str().unwrap(), "-out", cert.to_str().unwrap(),
3498                "-days", "1", "-subj", "/CN=localhost",
3499                "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1",
3500                "-addext", "basicConstraints=critical,CA:FALSE",
3501            ])
3502            .stdout(std::process::Stdio::null())
3503            .stderr(std::process::Stdio::null())
3504            .status();
3505        match status {
3506            Ok(s) if s.success() => Some((
3507                cert.to_str().unwrap().to_string(),
3508                key.to_str().unwrap().to_string(),
3509            )),
3510            _ => None, // no openssl on this host: the CI leg covers it
3511        }
3512    }
3513
3514    /// The §3.2 gate: a TLS round-trip succeeds, and a PLAINTEXT client on
3515    /// the same listener is refused (no silent downgrade).
3516    #[test]
3517    fn tls_round_trip_and_no_plaintext_downgrade() {
3518        let dir = tempfile::tempdir().unwrap();
3519        let Some((cert, key)) = self_signed(dir.path()) else {
3520            eprintln!("skipping: no openssl binary");
3521            return;
3522        };
3523        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3524        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3525        let server = UiServer::new(facade, "tls-test".into())
3526            .with_tls(&cert, &key)
3527            .unwrap();
3528        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3529        let addr = listener.local_addr().unwrap();
3530        let handle = std::thread::spawn(move || {
3531            // Two connections: the TLS client, then the plaintext prober.
3532            for _ in 0..2 {
3533                if let Ok((s, _)) = listener.accept() {
3534                    let _ = server.handle(s);
3535                }
3536            }
3537        });
3538
3539        // 1. TLS round-trip: trust exactly our self-signed cert.
3540        let mut roots = rustls::RootCertStore::empty();
3541        {
3542            use rustls::pki_types::pem::PemObject;
3543            for c in rustls::pki_types::CertificateDer::pem_file_iter(&cert).unwrap() {
3544                roots.add(c.unwrap()).unwrap();
3545            }
3546        }
3547        let config = std::sync::Arc::new(
3548            rustls::ClientConfig::builder()
3549                .with_root_certificates(roots)
3550                .with_no_client_auth(),
3551        );
3552        let name = rustls::pki_types::ServerName::try_from("localhost").unwrap();
3553        let session = rustls::ClientConnection::new(config, name).unwrap();
3554        let tcp = std::net::TcpStream::connect(addr).unwrap();
3555        let mut tls = rustls::StreamOwned::new(session, tcp);
3556        tls.write_all(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")
3557            .unwrap();
3558        let mut response = String::new();
3559        let _ = tls.read_to_string(&mut response);
3560        assert!(response.starts_with("HTTP/1.1 200"), "{}", &response[..response.len().min(120)]);
3561        assert!(response.contains("Areev"), "console served over TLS");
3562
3563        // 2. No downgrade: plaintext HTTP on the TLS listener gets a
3564        // handshake failure, never a page.
3565        let mut plain = std::net::TcpStream::connect(addr).unwrap();
3566        plain
3567            .write_all(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")
3568            .unwrap();
3569        let mut buf = Vec::new();
3570        let _ = plain.read_to_end(&mut buf);
3571        let text = String::from_utf8_lossy(&buf);
3572        assert!(
3573            !text.contains("HTTP/1.1 200"),
3574            "plaintext must not be served on a TLS listener: {text}"
3575        );
3576        handle.join().unwrap();
3577    }
3578
3579    /// `with_tls` composes with `with_auth` — `with_auth` only sets the
3580    /// token/auth_all fields, not the connection layer, so an authenticated
3581    /// console terminates TLS identically to an open one. Pins the CLI
3582    /// wiring that lets `areev ui --token-env VAR --tls-cert ... --tls-key
3583    /// ...` work, not just `areev ui --tls-cert ...`.
3584    #[test]
3585    fn an_authenticated_console_terminates_tls_the_same_way() {
3586        let dir = tempfile::tempdir().unwrap();
3587        let Some((cert, key)) = self_signed(dir.path()) else {
3588            eprintln!("skipping: no openssl binary");
3589            return;
3590        };
3591        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3592        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3593        let server = UiServer::new(facade, "auth-tls-test".into())
3594            .with_auth("console-token".into())
3595            .with_tls(&cert, &key)
3596            .unwrap();
3597        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3598        let addr = listener.local_addr().unwrap();
3599        let handle = std::thread::spawn(move || {
3600            if let Ok((s, _)) = listener.accept() {
3601                let _ = server.handle(s);
3602            }
3603        });
3604
3605        let mut roots = rustls::RootCertStore::empty();
3606        {
3607            use rustls::pki_types::pem::PemObject;
3608            for c in rustls::pki_types::CertificateDer::pem_file_iter(&cert).unwrap() {
3609                roots.add(c.unwrap()).unwrap();
3610            }
3611        }
3612        let config = std::sync::Arc::new(
3613            rustls::ClientConfig::builder()
3614                .with_root_certificates(roots)
3615                .with_no_client_auth(),
3616        );
3617        let name = rustls::pki_types::ServerName::try_from("localhost").unwrap();
3618        let session = rustls::ClientConnection::new(config, name).unwrap();
3619        let tcp = std::net::TcpStream::connect(addr).unwrap();
3620        let mut tls = rustls::StreamOwned::new(session, tcp);
3621        tls.write_all(
3622            b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\
3623              Authorization: Bearer console-token\r\nConnection: close\r\n\r\n",
3624        )
3625        .unwrap();
3626        let mut response = String::new();
3627        let _ = tls.read_to_string(&mut response);
3628        assert!(
3629            response.starts_with("HTTP/1.1 200"),
3630            "an authenticated console should terminate TLS like an open one: {}",
3631            &response[..response.len().min(120)]
3632        );
3633        handle.join().unwrap();
3634    }
3635}
3636
3637#[cfg(test)]
3638mod sso_tests {
3639    use super::UiServer;
3640    use areev_cal::AreevFacade;
3641    use areev_core::authz::{AUTHZ_NS, REL_PERMITS};
3642    use areev_core::types::{Fact, Grain};
3643    use areev_store::Areev;
3644    use std::io::{Read, Write};
3645
3646    const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
3647
3648    fn sso_server() -> UiServer {
3649        sso_server_with("proxy-secret", None)
3650    }
3651
3652    /// The same server mid-rotation: `proxy-secret` deployed, `next` incoming.
3653    fn sso_server_rotating(next: Option<&str>) -> UiServer {
3654        sso_server_with("proxy-secret", next)
3655    }
3656
3657    fn sso_server_with(secret: &str, next: Option<&str>) -> UiServer {
3658        let dir = tempfile::tempdir().unwrap();
3659        let mut store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3660        store
3661            .add(
3662                &Fact::new("user:pat@example.com", REL_PERMITS, "read,write ON caller")
3663                    .namespace(AUTHZ_NS)
3664                    .created_at(1_000),
3665            )
3666            .unwrap();
3667        std::mem::forget(dir);
3668        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3669        UiServer::new(facade, "sso-test".into())
3670            .with_sso_rotating("x-forwarded-user", secret, next)
3671    }
3672
3673    fn post(server: &UiServer, extra_headers: &str) -> String {
3674        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3675        let addr = listener.local_addr().unwrap();
3676        std::thread::scope(|scope| {
3677            scope.spawn(|| {
3678                if let Ok((s, _)) = listener.accept() {
3679                    let _ = server.handle(s);
3680                }
3681            });
3682            let mut c = std::net::TcpStream::connect(addr).unwrap();
3683            let req = format!(
3684                "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",
3685                WRITE.len()
3686            );
3687            c.write_all(req.as_bytes()).unwrap();
3688            c.write_all(WRITE).unwrap();
3689            let mut out = String::new();
3690            let _ = c.read_to_string(&mut out);
3691            out
3692        })
3693    }
3694
3695    /// The §3.3 gate: a proxy-proven identity lands as a named actor whose
3696    /// FILE grants decide; a forged identity header without the proxy
3697    /// secret is ignored (the write is refused as anonymous).
3698    #[test]
3699    fn proxied_identity_works_and_forged_headers_are_ignored() {
3700        let server = sso_server();
3701
3702        // 1. Proxy-proven: identity + secret → the granted principal writes.
3703        let ok = post(
3704            &server,
3705            "X-Forwarded-User: user:pat@example.com\r\nX-Areev-Proxy-Secret: proxy-secret\r\n",
3706        );
3707        assert!(ok.contains("HTTP/1.1 200"), "{}", &ok[..ok.len().min(200)]);
3708        assert!(!ok.contains("AUT-E001"), "granted principal must write: {ok}");
3709
3710        // 2. Forged: the identity header WITHOUT the secret is ignored — the
3711        // request is anonymous and the write refuses.
3712        let forged = post(&server, "X-Forwarded-User: user:pat@example.com\r\n");
3713        assert!(
3714            forged.contains("anonymous") || forged.contains("401"),
3715            "forged identity must not authenticate: {forged}"
3716        );
3717
3718        // 3. Wrong secret: same refusal (constant-time compare, same path).
3719        let wrong = post(
3720            &server,
3721            "X-Forwarded-User: user:pat@example.com\r\nX-Areev-Proxy-Secret: guess\r\n",
3722        );
3723        assert!(
3724            wrong.contains("anonymous") || wrong.contains("401"),
3725            "wrong proxy secret must not authenticate: {wrong}"
3726        );
3727    }
3728
3729    /// [A2] The proxy secret proves the PROXY. It does not make whatever the
3730    /// proxy forwarded well-formed — and an identity lands in immutable,
3731    /// replicating audit grains, so a malformed one outlives its request.
3732    #[test]
3733    fn malformed_identities_are_rejected_even_with_a_valid_proxy_secret() {
3734        assert_eq!(
3735            super::sanitize_sso_identity("  user:pat@example.com  ").as_deref(),
3736            Some("user:pat@example.com"),
3737            "surrounding whitespace is trimmed, not rejected"
3738        );
3739
3740        // CR/LF would smuggle a second line into every log and audit record.
3741        assert!(super::sanitize_sso_identity("user:a\r\nX-Admin: true").is_none());
3742        assert!(super::sanitize_sso_identity("user:a\tb").is_none());
3743        // Internal whitespace would make "user: a" and "user:a" two audit
3744        // identities for one person.
3745        assert!(super::sanitize_sso_identity("user a").is_none());
3746        assert!(super::sanitize_sso_identity("").is_none());
3747        assert!(super::sanitize_sso_identity(&"x".repeat(129)).is_none());
3748        // Reserved: an audit line must never be ambiguous between a vouched
3749        // person and the console's own floor/ceiling principals.
3750        assert!(super::sanitize_sso_identity("anonymous").is_none());
3751        assert!(super::sanitize_sso_identity("user:console").is_none());
3752    }
3753
3754    /// [A2] A rejected identity is treated as an ABSENT one — the request
3755    /// degrades to anonymous rather than the console refusing to serve, so a
3756    /// misconfigured proxy cannot take the console down.
3757    #[test]
3758    fn a_rejected_identity_degrades_to_anonymous_rather_than_erroring() {
3759        let server = sso_server();
3760        let out = post(
3761            &server,
3762            "X-Forwarded-User: anonymous\r\nX-Areev-Proxy-Secret: proxy-secret\r\n",
3763        );
3764        assert!(
3765            out.contains("anonymous") || out.contains("401"),
3766            "a reserved name must not authenticate: {out}"
3767        );
3768        assert!(!out.contains("HTTP/1.1 500"), "and must not error: {out}");
3769    }
3770
3771    /// The rotation window (#79): while two secrets are configured, either
3772    /// proves the proxy — so the fleet moves over one node at a time instead
3773    /// of atomically, which is the only way an impersonation-grade credential
3774    /// gets rotated without an outage or a gap.
3775    #[test]
3776    fn both_secrets_authenticate_during_a_rotation_window() {
3777        let server = sso_server_rotating(Some("new-secret"));
3778        let id = "X-Forwarded-User: user:pat@example.com\r\n";
3779
3780        for secret in ["proxy-secret", "new-secret"] {
3781            let out = post(&server, &format!("{id}X-Areev-Proxy-Secret: {secret}\r\n"));
3782            assert!(out.contains("HTTP/1.1 200"), "{secret} rejected: {out}");
3783            assert!(!out.contains("AUT-E001"), "{secret} must authenticate: {out}");
3784        }
3785
3786        // The window widens what proves the proxy, never what a proved
3787        // identity may do, and never to a third value.
3788        let wrong = post(&server, &format!("{id}X-Areev-Proxy-Secret: guess\r\n"));
3789        assert!(
3790            wrong.contains("anonymous") || wrong.contains("401"),
3791            "an unrelated secret must still be refused mid-rotation: {wrong}"
3792        );
3793    }
3794
3795    /// Closing the window is what actually retires the old credential — the
3796    /// step the runbook exists to make sure nobody skips.
3797    #[test]
3798    fn the_retired_secret_stops_working_once_the_window_closes() {
3799        // Rotation complete: the new value is now the only one deployed.
3800        let server = sso_server_with("new-secret", None);
3801        let id = "X-Forwarded-User: user:pat@example.com\r\n";
3802
3803        let ok = post(&server, &format!("{id}X-Areev-Proxy-Secret: new-secret\r\n"));
3804        assert!(ok.contains("HTTP/1.1 200"), "{ok}");
3805        assert!(!ok.contains("AUT-E001"), "the promoted secret must authenticate: {ok}");
3806
3807        let old = post(&server, &format!("{id}X-Areev-Proxy-Secret: proxy-secret\r\n"));
3808        assert!(
3809            old.contains("anonymous") || old.contains("401"),
3810            "the retired secret must stop working: {old}"
3811        );
3812    }
3813
3814    #[test]
3815    #[should_panic(expected = "must differ")]
3816    fn rotating_to_the_same_value_is_refused() {
3817        // A rotation that deploys the same value twice did not happen, and it
3818        // would read as "both live" in every log and status line.
3819        let _ = sso_server_rotating(Some("proxy-secret"));
3820    }
3821
3822    use crate::CONSOLE_HTML;
3823    use std::collections::BTreeSet;
3824
3825    /// Every `<section class="page" id="page-X">` must be named in the one
3826    /// array in `render()` that clears `hidden`, and every sidebar
3827    /// `data-page="X"` must have such a section.
3828    ///
3829    /// The console's page sections ship `hidden` in the markup, so a page is
3830    /// visible only if `render()` un-hides it. The Triggers tab shipped
3831    /// missing from that array: `renderTriggers()` filled `#trgBody` on every
3832    /// render, the nav item highlighted, the hash routed — and the section
3833    /// stayed `hidden` while every other page was hidden too, so the tab
3834    /// showed a blank pane. Nothing else in the file could catch it: the
3835    /// omission is a *missing* string, not a wrong one.
3836    #[test]
3837    fn every_console_page_is_in_the_visibility_list() {
3838        fn all(hay: &str, open: &str) -> BTreeSet<String> {
3839            let mut out = BTreeSet::new();
3840            let mut rest = hay;
3841            while let Some(i) = rest.find(open) {
3842                rest = &rest[i + open.len()..];
3843                let end = rest.find('"').expect("unterminated attribute");
3844                out.insert(rest[..end].to_string());
3845                rest = &rest[end..];
3846            }
3847            out
3848        }
3849
3850        let sections = all(CONSOLE_HTML, "id=\"page-");
3851        let nav = all(CONSOLE_HTML, "data-page=\"");
3852        for want in ["workflows", "runs", "tools"] {
3853            assert!(sections.contains(want), "the {want} section itself went missing");
3854        }
3855        // Triggers deliberately have no page: a trigger points AT a plan and is
3856        // only legible next to it, so they render in the workflow canvas's own
3857        // lane. The old deep link must still land somewhere real.
3858        assert!(!sections.contains("triggers"), "triggers belong on the canvas, not on a page");
3859        assert!(
3860            CONSOLE_HTML.contains("if (head === 'triggers')"),
3861            "#triggers must still route somewhere — a removed page is not a dead bookmark"
3862        );
3863
3864        // The single array in render() that drives `.hidden`.
3865        let head = "for (const p of [";
3866        let i = CONSOLE_HTML.find(head).expect("render()'s page-visibility loop");
3867        let tail = &CONSOLE_HTML[i + head.len()..];
3868        let j = tail.find(']').expect("unterminated page array");
3869        let listed: BTreeSet<String> = tail[..j]
3870            .split(',')
3871            .map(|t| t.trim().trim_matches('\'').to_string())
3872            .filter(|t| !t.is_empty())
3873            .collect();
3874
3875        assert_eq!(
3876            sections, listed,
3877            "page sections and render()'s visibility list disagree; a section missing \
3878             from the list renders into a pane that never un-hides"
3879        );
3880        let orphan: Vec<_> = nav.difference(&sections).collect();
3881        assert!(orphan.is_empty(), "nav items with no page section: {orphan:?}");
3882    }
3883}
3884
3885/// Issue #124: the console must never disclose the password half of a
3886/// Postgres DSN, at any of its three display surfaces, while the RAW label
3887/// keeps working as the credential map's `memories` comparison key.
3888#[cfg(test)]
3889mod dsn_redaction_tests {
3890    use super::UiServer;
3891    use areev_cal::AreevFacade;
3892    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
3893    use areev_core::types::{Fact, Grain};
3894    use areev_store::Areev;
3895
3896    const DSN: &str = "postgresql://u:SUPERSECRET@h:5432/d?sslmode=require";
3897
3898    fn server() -> UiServer {
3899        let dir = tempfile::tempdir().unwrap();
3900        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3901        std::mem::forget(dir);
3902        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3903        UiServer::new(facade, DSN.to_string())
3904    }
3905
3906    fn text(r: &(&str, &str, Vec<u8>)) -> String {
3907        String::from_utf8_lossy(&r.2).to_string()
3908    }
3909
3910    #[test]
3911    fn stats_config_and_html_redact_the_dsn_password_but_keep_the_host() {
3912        let s = server();
3913        for (method, path) in [("GET", "/api/stats"), ("GET", "/api/config"), ("GET", "/")] {
3914            let r = s.route(method, path, b"", None, None);
3915            let body = text(&r);
3916            assert!(!body.contains("SUPERSECRET"), "{path} leaked the password: {body}");
3917            assert!(body.contains("h:5432"), "{path} redacted more than the password: {body}");
3918        }
3919    }
3920
3921    /// Redaction is DISPLAY ONLY: a credential map's `memories` entry is
3922    /// documented as the raw `--db` value, and it must still resolve —
3923    /// proving the redacted form never leaked into the auth-comparison
3924    /// path (`resolve_for_memory`'s exact string compare).
3925    #[test]
3926    fn credential_map_memories_entry_still_matches_the_raw_dsn() {
3927        std::env::set_var("AREEV_DSN_TOK", "dsn-scoped-secret");
3928        let map_json = format!(
3929            r#"{{"version":1,"tokens":[{{"env":"AREEV_DSN_TOK","principal":"agent:sync","memories":["{DSN}"]}}]}}"#
3930        );
3931        let dir = tempfile::tempdir().unwrap();
3932        let mut store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3933        store
3934            .add(
3935                &Fact::new("agent:sync", REL_PERMITS, "read,write ON caller")
3936                    .namespace(AUTHZ_NS)
3937                    .created_at(1_000),
3938            )
3939            .unwrap();
3940        std::mem::forget(dir);
3941        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3942        let s = UiServer::new(facade, DSN.to_string())
3943            .with_credentials(CredentialMap::from_json(&map_json).unwrap());
3944
3945        const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
3946        let r = s.route("POST", "/api/cal", WRITE, Some("dsn-scoped-secret"), None);
3947        let body = text(&r);
3948        assert!(r.0.starts_with("200") && !body.contains("AUT-E001"), "{body}");
3949    }
3950}
3951
3952/// Issue #125: `--allow-origin` lets an exact origin's cross-origin POSTs
3953/// through, without weakening the check for anyone else — no wildcards, no
3954/// suffix/subdomain matching. The Origin header is parsed in
3955/// `handle_request` (not `route`), so these go over a real socket.
3956#[cfg(test)]
3957mod origin_tests {
3958    use super::UiServer;
3959    use areev_cal::AreevFacade;
3960    use areev_store::Areev;
3961    use std::io::{Read, Write};
3962
3963    fn server() -> UiServer {
3964        let dir = tempfile::tempdir().unwrap();
3965        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
3966        std::mem::forget(dir);
3967        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
3968        UiServer::new(facade, "origin-test".into())
3969    }
3970
3971    /// POST a read-only CAL query (works token-less on an open console) with
3972    /// an optional `Origin` header, returning the raw HTTP response text.
3973    fn post_with_origin(server: &UiServer, origin: Option<&str>) -> String {
3974        let body: &[u8] = br#"{"query":"RECALL facts WHERE subject = \"acme\""}"#;
3975        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3976        let addr = listener.local_addr().unwrap();
3977        std::thread::scope(|scope| {
3978            scope.spawn(|| {
3979                if let Ok((s, _)) = listener.accept() {
3980                    let _ = server.handle(s);
3981                }
3982            });
3983            let mut c = std::net::TcpStream::connect(addr).unwrap();
3984            let origin_header = origin.map(|o| format!("Origin: {o}\r\n")).unwrap_or_default();
3985            let req = format!(
3986                "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",
3987                body.len()
3988            );
3989            c.write_all(req.as_bytes()).unwrap();
3990            c.write_all(body).unwrap();
3991            let mut out = String::new();
3992            let _ = c.read_to_string(&mut out);
3993            out
3994        })
3995    }
3996
3997    #[test]
3998    fn matching_allowed_origin_is_accepted() {
3999        let s = server().allow_origin("https://console.example.com");
4000        let r = post_with_origin(&s, Some("https://console.example.com"));
4001        assert!(r.contains("HTTP/1.1 200"), "{r}");
4002    }
4003
4004    #[test]
4005    fn non_matching_origin_is_still_rejected() {
4006        let s = server().allow_origin("https://console.example.com");
4007        let r = post_with_origin(&s, Some("https://not-allowed.example.com"));
4008        assert!(r.contains("403"), "{r}");
4009        assert!(r.contains("cross-origin request rejected"), "{r}");
4010    }
4011
4012    #[test]
4013    fn a_subdomain_of_an_allowed_origin_is_rejected_not_matched() {
4014        // The allowlist entry is the console's real origin; a lookalike
4015        // subdomain must not be accepted by suffix matching.
4016        let s = server().allow_origin("https://console.example.com");
4017        let r = post_with_origin(&s, Some("https://evil-console.example.com"));
4018        assert!(r.contains("403"), "{r}");
4019    }
4020
4021    #[test]
4022    fn loopback_origin_still_works_with_no_allowlist_set() {
4023        let s = server();
4024        let r = post_with_origin(&s, Some("http://127.0.0.1:7437"));
4025        assert!(r.contains("HTTP/1.1 200"), "{r}");
4026    }
4027
4028    #[test]
4029    fn no_origin_header_still_works() {
4030        let s = server();
4031        let r = post_with_origin(&s, None);
4032        assert!(r.contains("HTTP/1.1 200"), "{r}");
4033    }
4034
4035    #[test]
4036    fn matching_origin_differing_only_in_case_and_trailing_slash_is_accepted() {
4037        let s = server().allow_origin("https://console.example.com");
4038        let r = post_with_origin(&s, Some("HTTPS://Console.Example.com/"));
4039        assert!(r.contains("HTTP/1.1 200"), "{r}");
4040    }
4041}
4042
4043/// Issue #126: repeated bad credentials from one source IP are COUNTED and
4044/// LOGGED in a stable, greppable shape — but never delayed or locked out
4045/// in-process (`serve` is a strictly serial accept loop; see
4046/// `note_auth_failure`'s doc comment for why a sleep here would itself be a
4047/// denial-of-service lever). A request that never presented a credential at
4048/// all has nothing to fail and is never counted.
4049/// [A3] Native OIDC at the request level: cookies, the `/auth/*` endpoints,
4050/// and the approval rules an IdP-proven identity is subject to.
4051#[cfg(all(test, feature = "oidc"))]
4052mod oidc_route_tests {
4053    use super::{cookie_value, oidc, UiServer};
4054    use areev_cal::AreevFacade;
4055    use areev_core::authz::{AUTHZ_NS, REL_PERMITS};
4056    use areev_core::types::{Fact, Grain};
4057    use areev_store::Areev;
4058
4059    fn cfg() -> oidc::OidcConfig {
4060        oidc::OidcConfig {
4061            issuer: "https://idp.example.com".into(),
4062            client_id: "console".into(),
4063            client_secret: "s3cr3t".into(),
4064            redirect_uri: "https://console.example.com/auth/callback".into(),
4065            scopes: "openid email".into(),
4066            principal_claim: "email".into(),
4067            principal_prefix: None,
4068        }
4069    }
4070
4071    /// A cookie header is attacker-influenced: any script on any same-site
4072    /// origin can set cookies. A prefix or substring match would let a decoy
4073    /// shadow the real session.
4074    #[test]
4075    fn cookie_lookup_is_exact_on_the_name() {
4076        let h = "theme=dark; areev_session=real; other=x";
4077        assert_eq!(cookie_value(h, "areev_session").as_deref(), Some("real"));
4078        // A decoy whose name merely CONTAINS the real one must not match.
4079        let decoy = "areev_session_decoy=evil; areev_session=real";
4080        assert_eq!(cookie_value(decoy, "areev_session").as_deref(), Some("real"));
4081        let only_decoy = "xareev_session=evil; areev_sessionx=evil2";
4082        assert!(cookie_value(only_decoy, "areev_session").is_none());
4083        assert!(cookie_value("", "areev_session").is_none());
4084    }
4085
4086    /// `/auth/login` redirects to the IdP and stores nothing in the browser;
4087    /// `/auth/logout` clears the cookie AND drops the server-side session.
4088    #[test]
4089    fn the_auth_endpoints_redirect_and_manage_the_cookie() {
4090        let dir = tempfile::tempdir().unwrap();
4091        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
4092        std::mem::forget(dir);
4093        let facade = AreevFacade::with_session(store, Some("ops".into()), None);
4094        let provider = oidc::OidcProvider::with_test_session(cfg(), "sid-1", "user:pat");
4095        let s = UiServer::new(facade, "oidc-test".into()).with_oidc(provider);
4096
4097        // login → 302 to the IdP, and no Set-Cookie (nothing to remember yet).
4098        let (status, extra, _) = s.oidc_route("GET", "/auth/login", None);
4099        assert!(status.starts_with("302"), "{status}");
4100        assert!(extra.contains("Location: https://idp.example.com/authorize"), "{extra}");
4101        assert!(!extra.contains("Set-Cookie"), "{extra}");
4102        assert!(extra.contains("Cache-Control: no-store"), "a redirect carrying state must not cache: {extra}");
4103
4104        // The session works before logout...
4105        assert!(s.oidc_principal(Some("areev_session=sid-1")).is_some());
4106
4107        // ...and logout clears the browser copy AND invalidates server-side.
4108        let (status, extra, _) =
4109            s.oidc_route("POST", "/auth/logout", Some("areev_session=sid-1"));
4110        assert!(status.starts_with("302"), "{status}");
4111        assert!(extra.contains("Max-Age=0"), "{extra}");
4112        assert!(extra.contains("HttpOnly"), "{extra}");
4113        assert!(extra.contains("SameSite=Strict"), "{extra}");
4114        assert!(
4115            s.oidc_principal(Some("areev_session=sid-1")).is_none(),
4116            "logout must invalidate the session, not just the browser's copy"
4117        );
4118
4119        // A callback with no code surfaces the IdP's own error.
4120        let (status, _, body) =
4121            s.oidc_route("GET", "/auth/callback?error=access_denied", None);
4122        assert!(status.starts_with("400"), "{status}");
4123        assert!(body.contains("access_denied"), "{body}");
4124    }
4125
4126    /// The cookie is `HttpOnly` + `SameSite=Strict`, and `Secure` exactly
4127    /// when the redirect URI is https — a loopback console over plain http
4128    /// must still be able to log in.
4129    #[test]
4130    fn the_session_cookie_is_httponly_strict_and_secure_only_over_https() {
4131        let mk = |redirect: &str| {
4132            let dir = tempfile::tempdir().unwrap();
4133            let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
4134            std::mem::forget(dir);
4135            let facade = AreevFacade::with_session(store, Some("ops".into()), None);
4136            let mut c = cfg();
4137            c.redirect_uri = redirect.into();
4138            let p = oidc::OidcProvider::with_test_session(c, "sid", "user:pat");
4139            UiServer::new(facade, "t".into()).with_oidc(p)
4140        };
4141
4142        let https = mk("https://console.example.com/auth/callback");
4143        let (_, extra, _) = https.oidc_route("GET", "/auth/logout", None);
4144        assert!(extra.contains("; Secure"), "https deployment must set Secure: {extra}");
4145
4146        let http = mk("http://127.0.0.1:7437/auth/callback");
4147        let (_, extra, _) = http.oidc_route("GET", "/auth/logout", None);
4148        assert!(!extra.contains("; Secure"), "loopback http must not set Secure: {extra}");
4149        // The other two are unconditional.
4150        assert!(extra.contains("HttpOnly") && extra.contains("SameSite=Strict"), "{extra}");
4151    }
4152
4153    /// The point of the whole feature: an OIDC-proven identity MAY approve,
4154    /// and `--sso-approvals` (which governs the header path) does not touch
4155    /// it. A signature verified against the issuer's key set is a stronger
4156    /// claim than a shared proxy secret, so it gets the stronger right.
4157    #[test]
4158    fn an_oidc_principal_may_approve_regardless_of_sso_approvals() {
4159        let dir = tempfile::tempdir().unwrap();
4160        let path = dir.path().join("t.db");
4161        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
4162        store
4163            .add(
4164                &Fact::new("user:pat", REL_PERMITS, "read,run.respond ON ops")
4165                    .namespace(AUTHZ_NS)
4166                    .created_at(900),
4167            )
4168            .unwrap();
4169        std::mem::forget(dir);
4170        let facade = AreevFacade::with_session(store, Some("ops".into()), None);
4171        let provider = oidc::OidcProvider::with_test_session(cfg(), "sid-1", "user:pat");
4172        let s = UiServer::new(facade, "oidc-test".into())
4173            .with_oidc(provider)
4174            // The A0 default, explicitly: SSO headers may NOT approve.
4175            .with_sso_approvals(false);
4176
4177        let r = s.route_full("GET", "/api/whoami", b"", None, None, None, Some("user:pat"));
4178        let text = String::from_utf8_lossy(&r.2).to_string();
4179        assert!(text.contains(r#""identity_source":"oidc""#), "{text}");
4180        assert!(
4181            text.contains(r#""may_approve":true"#),
4182            "an IdP-proven identity is exactly what --sso-approvals exists to \
4183             substitute for; it must not be caught by that refusal: {text}"
4184        );
4185        assert!(text.contains("user:pat"), "{text}");
4186    }
4187}
4188
4189#[cfg(test)]
4190mod auth_failure_tracking_tests {
4191    use super::UiServer;
4192    use areev_cal::AreevFacade;
4193    use areev_store::Areev;
4194    use std::io::{Read, Write};
4195    use std::net::IpAddr;
4196
4197    const LOCALHOST: IpAddr = IpAddr::V4(std::net::Ipv4Addr::LOCALHOST);
4198
4199    fn server() -> UiServer {
4200        let dir = tempfile::tempdir().unwrap();
4201        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
4202        std::mem::forget(dir);
4203        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
4204        UiServer::new(facade, "auth-failure-test".into()).with_auth("right-token".into())
4205    }
4206
4207    /// GET `/` with an optional `Authorization: Bearer` header, over a real
4208    /// socket (the counter hooks `handle_request`, not `route`).
4209    fn get_root(server: &UiServer, bearer: Option<&str>) -> String {
4210        let auth_header = bearer
4211            .map(|t| format!("Authorization: Bearer {t}\r\n"))
4212            .unwrap_or_default();
4213        get_root_with(server, &auth_header)
4214    }
4215
4216    /// `GET /` with arbitrary extra headers, over a real socket (the counter
4217    /// hooks `handle_request`, not `route`).
4218    fn get_root_with(server: &UiServer, extra_headers: &str) -> String {
4219        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4220        let addr = listener.local_addr().unwrap();
4221        std::thread::scope(|scope| {
4222            scope.spawn(|| {
4223                if let Ok((s, _)) = listener.accept() {
4224                    let _ = server.handle(s);
4225                }
4226            });
4227            let mut c = std::net::TcpStream::connect(addr).unwrap();
4228            let req = format!("GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n{extra_headers}Connection: close\r\n\r\n");
4229            c.write_all(req.as_bytes()).unwrap();
4230            let mut out = String::new();
4231            let _ = c.read_to_string(&mut out);
4232            out
4233        })
4234    }
4235
4236    #[test]
4237    fn a_bare_request_is_401_but_not_counted() {
4238        let s = server();
4239        // No credential presented at all: 401 (auth_all guards every
4240        // request), but nothing was attempted, so it must not be counted —
4241        // a token-less probe is not an attack attempt.
4242        let bare = get_root(&s, None);
4243        assert!(bare.contains("HTTP/1.1 401"), "{bare}");
4244        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 0, "a bare request has nothing to fail");
4245    }
4246
4247    #[test]
4248    fn a_wrong_token_is_401_and_is_counted() {
4249        let s = server();
4250        let wrong = get_root(&s, Some("guess"));
4251        assert!(wrong.contains("HTTP/1.1 401"), "{wrong}");
4252        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 1);
4253
4254        let wrong_again = get_root(&s, Some("guess"));
4255        assert!(wrong_again.contains("HTTP/1.1 401"), "{wrong_again}");
4256        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 2, "consecutive failures accumulate");
4257    }
4258
4259    #[test]
4260    fn a_right_token_after_a_streak_succeeds_immediately_and_resets_it() {
4261        let s = server();
4262        for _ in 0..5 {
4263            let r = get_root(&s, Some("guess"));
4264            assert!(r.contains("HTTP/1.1 401"), "{r}");
4265        }
4266        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 5);
4267
4268        // The right token succeeds on the very next request — there is no
4269        // in-process DELAY at any streak length, and below
4270        // MAX_CONSECUTIVE_AUTH_FAILURES no rejection either, so an operator
4271        // who fat-fingers a pasted token is never locked out.
4272        let ok = get_root(&s, Some("right-token"));
4273        assert!(ok.contains("HTTP/1.1 200"), "{ok}");
4274        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 0, "success resets the streak");
4275
4276        // The next wrong guess starts a fresh streak at 1, not 6.
4277        let r = get_root(&s, Some("guess"));
4278        assert!(r.contains("HTTP/1.1 401"), "{r}");
4279        assert_eq!(s.auth_failure_count_for_test(LOCALHOST), 1);
4280    }
4281
4282    /// [A1] Behind a trusted proxy every request shares ONE source address,
4283    /// so a per-IP lockout would let one attacker's bad guesses refuse every
4284    /// user behind it — a self-inflicted outage in the deployment we
4285    /// recommend. A proxy-proven request is exempt; throttling there belongs
4286    /// to the proxy, like TLS and the IdP handshake.
4287    #[test]
4288    fn a_proxy_proven_request_is_never_locked_out() {
4289        let dir = tempfile::tempdir().unwrap();
4290        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
4291        std::mem::forget(dir);
4292        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
4293        let s = UiServer::new(facade, "proxy-test".into())
4294            .with_auth("right-token".into())
4295            .with_sso_rotating("x-forwarded-user", "proxy-secret", None::<String>);
4296
4297        // Burn well past the threshold with wrong bearer tokens, but all
4298        // arriving through the proxy (valid proxy secret on every request).
4299        for _ in 0..(super::MAX_CONSECUTIVE_AUTH_FAILURES + 5) {
4300            let _ = get_root_with(
4301                &s,
4302                "Authorization: Bearer guess\r\nX-Areev-Proxy-Secret: proxy-secret\r\n",
4303            );
4304        }
4305        // A legitimate user behind the same proxy is still served.
4306        let ok = get_root_with(
4307            &s,
4308            "Authorization: Bearer right-token\r\nX-Areev-Proxy-Secret: proxy-secret\r\n",
4309        );
4310        assert!(ok.contains("HTTP/1.1 200"), "proxy-borne traffic must not be locked out: {ok}");
4311    }
4312
4313    /// [A1] Past the threshold the console stops answering credential-bearing
4314    /// requests from that source — refusing, never sleeping, because a serial
4315    /// accept loop makes a sleep a denial-of-service lever for everyone else.
4316    #[test]
4317    fn a_long_streak_is_refused_with_429_until_it_goes_idle() {
4318        let s = server();
4319        for i in 0..super::MAX_CONSECUTIVE_AUTH_FAILURES {
4320            let r = get_root(&s, Some("guess"));
4321            assert!(r.contains("HTTP/1.1 401"), "attempt {i} should still be a 401: {r}");
4322        }
4323
4324        // The next credential-bearing request is refused before routing.
4325        let blocked = get_root(&s, Some("guess"));
4326        assert!(blocked.contains("HTTP/1.1 429"), "{blocked}");
4327        assert!(blocked.contains("Retry-After:"), "a 429 must say when: {blocked}");
4328
4329        // The brake is on the SOURCE, not on the credential: even the right
4330        // token is refused while the streak stands. That is the intended
4331        // trade — an attacker who has burned an IP cannot then race a guess
4332        // through — and it is why the streak expires on its own.
4333        let right = get_root(&s, Some("right-token"));
4334        assert!(right.contains("HTTP/1.1 429"), "{right}");
4335
4336        // A credential-LESS request is untouched: it was never counted, so it
4337        // must not be blocked either. The console page still serves its 401
4338        // challenge, which is what lets a browser prompt for a fresh login.
4339        let bare = get_root(&s, None);
4340        assert!(bare.contains("HTTP/1.1 401"), "{bare}");
4341    }
4342}