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