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
17const CONSOLE_HTML: &str = include_str!("console.html");
18
19/// Per-connection read/write timeout — bounds slow-client (slowloris) attacks.
20const READ_TIMEOUT_SECS: u64 = 15;
21/// Hard ceiling on bytes read from one connection (1 MiB body cap + headroom
22/// for the request line and headers). Bounds memory against oversized requests.
23const MAX_CONN_BYTES: u64 = (1 << 20) + (128 << 10);
24/// Cap on total header bytes and header count per request.
25const MAX_HEADER_BYTES: usize = 64 * 1024;
26const MAX_HEADERS: usize = 100;
27/// Total wall-clock deadline for reading + handling one request. A per-read
28/// timeout cannot bound a slow-drip client (each byte resets it), so a watchdog
29/// shuts the socket down at this deadline.
30const REQUEST_DEADLINE_SECS: u64 = 30;
31
32
33/// One accepted connection: plaintext, or TLS when the server was built
34/// with the `tls` feature and configured with a certificate. The raw
35/// socket handle stays available for timeouts and the watchdog shutdown;
36/// all request/response bytes flow through this wrapper. A plaintext
37/// client hitting a TLS listener fails the handshake — there is no
38/// downgrade path by construction.
39enum Conn {
40    Plain(TcpStream),
41    #[cfg(feature = "tls")]
42    Tls(Box<rustls::StreamOwned<rustls::ServerConnection, TcpStream>>),
43}
44
45impl Read for Conn {
46    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
47        match self {
48            Conn::Plain(s) => s.read(buf),
49            #[cfg(feature = "tls")]
50            Conn::Tls(s) => s.read(buf),
51        }
52    }
53}
54
55impl Write for Conn {
56    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
57        match self {
58            Conn::Plain(s) => s.write(buf),
59            #[cfg(feature = "tls")]
60            Conn::Tls(s) => s.write(buf),
61        }
62    }
63    fn flush(&mut self) -> std::io::Result<()> {
64        match self {
65            Conn::Plain(s) => s.flush(),
66            #[cfg(feature = "tls")]
67            Conn::Tls(s) => s.flush(),
68        }
69    }
70}
71
72pub struct UiServer {
73    facade: std::sync::Arc<AreevFacade>,
74    executor: CalExecutor,
75    db_label: String,
76    /// Shared secret required for access when set. In hub mode it guards only
77    /// mutating/sync endpoints (`Bearer`); in console-auth mode (`auth_all`) it
78    /// guards every request via `Bearer` **or** HTTP `Basic` (password = token).
79    token: Option<String>,
80    /// When true, *every* request requires the token — the console page, all
81    /// reads, and all writes — and a `401` carries `WWW-Authenticate: Basic` so
82    /// browsers prompt. Set by [`UiServer::with_auth`]; hub mode leaves it off.
83    auth_all: bool,
84    /// Directory for received segments (areevd hub mode).
85    segment_dir: Option<String>,
86    /// When false (the default), reject any request whose `Host` header is not
87    /// loopback — the standard DNS-rebinding defense for a localhost service.
88    /// Set true only when the operator intentionally serves to other hosts
89    /// (CLI `--allow-remote`), where a non-loopback `Host` is expected.
90    allow_remote: bool,
91    /// Host loop policy (§6.2) applied to the `/api/loop/*` engine — the
92    /// same `loop-policy.json` the CLI takes (`areev ui --policy`). Absent →
93    /// the closed default: nothing auto-applies, nothing is denied. Host
94    /// config, never persisted in the memory file.
95    loop_policy: Option<areev_loop::Policy>,
96    /// Multi-principal mode (`areev ui --auth areev-auth.json`): a credential
97    /// map resolving bearer/Basic tokens to principal names. Rights come
98    /// from the FILE's own grant grains — the map holds no policy and no
99    /// raw secrets. Unauthenticated requests run as `anonymous`
100    /// (read-only unless the file grants more). It changes *who* a request
101    /// is, never *whether* the shared `--token-env` secret is required: when
102    /// both are configured the secret keeps its contract (implied admin, and
103    /// still demanded on the requests it guards).
104    credentials: Option<areev_core::authz::CredentialMap>,
105    /// Whether destructive CAL is permitted, kept alongside the executor so
106    /// every builder can rebuild it without clobbering the others' settings.
107    allow_destructive_ops: bool,
108    /// Native TLS (the recorded dependency exception; `tls` cargo feature).
109    /// None = plaintext — the documented default is a TLS-terminating proxy.
110    #[cfg(feature = "tls")]
111    tls_config: Option<std::sync::Arc<rustls::ServerConfig>>,
112    /// SSO v0 — trusted-header auth (`areev ui --sso-header X-Forwarded-User
113    /// --sso-secret-env VAR`): an authenticating proxy does OIDC/SAML and
114    /// forwards the identity in this header. Honored ONLY when the request
115    /// also carries the proxy shared secret in `x-areev-proxy-secret` —
116    /// otherwise identity headers are attacker-controlled input and are
117    /// ignored entirely. Rights still come from the FILE's grant grains.
118    sso_header: Option<String>,
119    sso_secret: Option<String>,
120}
121
122/// Per-request principal binding. The server handles one request at a
123/// time, so rebinding the shared facade for the request's duration is
124/// race-free; the guard restores the owner default on drop — including on
125/// panic — so a failed handler can never leak a stray principal into the
126/// next request.
127struct RequestBinding<'a> {
128    facade: &'a AreevFacade,
129}
130
131impl<'a> RequestBinding<'a> {
132    fn bind(
133        facade: &'a AreevFacade,
134        map: &areev_core::authz::CredentialMap,
135        bearer: Option<&str>,
136        memory: &str,
137    ) -> Self {
138        // Memory-scoped resolution: a credential whose `memories` list
139        // excludes THIS memory is indistinguishable from an unknown token.
140        let principal =
141            bearer.and_then(|t| map.resolve_for_memory(t, memory).ok().map(str::to_string));
142        match principal {
143            Some(p) => {
144                if facade.bind_principal(&p).is_err() {
145                    // A store failure reading grants fails toward LESS
146                    // privilege, never more.
147                    Self::bind_anonymous(facade);
148                }
149            }
150            None => Self::bind_anonymous(facade),
151        }
152        RequestBinding { facade }
153    }
154
155    /// `anonymous` = a read-only baseline plus whatever the file explicitly
156    /// grants the `anonymous` principal — the formalized version of the old
157    /// token-less read-only console.
158    /// Bind a proxy-proven SSO identity directly (no credential map row
159    /// needed — the IdP said who this is; the FILE says what they may do).
160    fn bind_identity(facade: &'a AreevFacade, principal: &str) -> Self {
161        if facade.bind_principal(principal).is_err() {
162            Self::bind_anonymous(facade);
163        }
164        RequestBinding { facade }
165    }
166
167    fn bind_anonymous(facade: &AreevFacade) {
168        use areev_core::authz::{AuthzSet, Grant, Verb};
169        let mut grants = facade
170            .with_store(|m| m.authz_grants("anonymous"))
171            .unwrap_or_default();
172        grants.push(Grant { verbs: vec![Verb::Read], namespaces: vec!["*".to_string()] });
173        facade.bind(AuthzSet::restricted("anonymous", grants));
174    }
175}
176
177impl Drop for RequestBinding<'_> {
178    fn drop(&mut self) {
179        self.facade
180            .bind(areev_core::authz::AuthzSet::owner("user:console"));
181    }
182}
183
184impl UiServer {
185    pub fn new(facade: AreevFacade, db_label: String) -> Self {
186        UiServer {
187            facade: std::sync::Arc::new(facade),
188            executor: CalExecutor::new(CalExecutorConfig::default())
189                .with_governance(std::sync::Arc::new(areev_loop_adapter::LoopGovernance::new())),
190            db_label,
191            token: None,
192            auth_all: false,
193            segment_dir: None,
194            allow_remote: false,
195            loop_policy: None,
196            credentials: None,
197            allow_destructive_ops: CalExecutorConfig::default().allow_destructive_ops,
198            #[cfg(feature = "tls")]
199            tls_config: None,
200            sso_header: None,
201            sso_secret: None,
202        }
203    }
204
205    /// Enable trusted-header SSO (v0). `header` names the identity header
206    /// the authenticating proxy forwards; `secret` is the proxy's shared
207    /// secret, demanded in `x-areev-proxy-secret` on every SSO request.
208    pub fn with_sso(mut self, header: impl Into<String>, secret: impl Into<String>) -> Self {
209        let header = header.into();
210        let secret = secret.into();
211        // An empty proxy secret would let `x-areev-proxy-secret:` (empty)
212        // prove any identity — refuse loudly at the library boundary too,
213        // not just in the CLI.
214        assert!(
215            !header.trim().is_empty() && !secret.trim().is_empty(),
216            "with_sso requires a non-empty header name and proxy secret"
217        );
218        self.sso_header = Some(header.to_ascii_lowercase());
219        self.sso_secret = Some(secret);
220        self
221    }
222
223    /// Rebuild the executor from the current gate settings. Every builder
224    /// that touches the CAL surface goes through here so `--no-destructive-ops`
225    /// and `--policy` compose instead of clobbering each other's config —
226    /// and the governance host survives every rebuild. (Same shape as
227    /// `areev-mcp`'s; building `CalExecutorConfig::default()` in one builder
228    /// silently re-enabled destruction configured off by another.)
229    fn rebuild_executor(&mut self) {
230        self.executor = CalExecutor::new(CalExecutorConfig {
231            allow_destructive_ops: self.allow_destructive_ops,
232            ..CalExecutorConfig::default()
233        })
234        .with_governance(std::sync::Arc::new(match &self.loop_policy {
235            Some(p) => areev_loop_adapter::LoopGovernance::with_policy(p.clone()),
236            None => areev_loop_adapter::LoopGovernance::new(),
237        }));
238    }
239
240    /// Multi-principal mode: attach the credential map (`areev-auth.json`).
241    /// Tokens resolve to principal names; rights come from the memory
242    /// file's own grant grains; unauthenticated requests run as
243    /// `anonymous`. See `docs/cal-reference.md` §9.
244    pub fn with_credentials(mut self, map: areev_core::authz::CredentialMap) -> Self {
245        self.credentials = Some(map);
246        self
247    }
248
249    /// Attach a host loop policy to the console's loop routes, so a
250    /// console-triggered run honors the same auto-apply grants, denies, and
251    /// severity floors as `areev loop run --policy`.
252    pub fn with_loop_policy(mut self, policy: areev_loop::Policy) -> Self {
253        self.loop_policy = Some(policy);
254        // The CAL surface's governance host honors the same policy.
255        self.rebuild_executor();
256        self
257    }
258
259    /// May this request's session read the raw sync surface? A segment is a
260    /// whole-memory op-log export, so it takes `read` on every namespace —
261    /// a principal granted read on one namespace must not be able to pull
262    /// the file wholesale through `/api/segment`. Owner sessions (every
263    /// non-credential-map deployment) pass unchanged.
264    fn session_may_sync(&self) -> bool {
265        self.facade
266            .authz()
267            .allows(areev_core::authz::Verb::Read, "*")
268    }
269
270    /// The loop engine for a request: builtins + the host policy when one
271    /// was attached.
272    fn engine(&self) -> Engine {
273        match &self.loop_policy {
274            Some(p) => Engine::with_builtins().with_policy(p.clone()),
275            None => Engine::with_builtins(),
276        }
277    }
278
279    /// Accept requests whose `Host` header is non-loopback. Off by default so
280    /// the loopback console is protected against DNS-rebinding reads even when
281    /// unauthenticated; the CLI enables it under `--allow-remote`.
282    pub fn allow_remote(mut self, yes: bool) -> Self {
283        self.allow_remote = yes;
284        self
285    }
286
287    /// Require a shared secret on **every** request (the console page, reads,
288    /// and writes). Browsers authenticate through the native `Basic` prompt
289    /// (any username; password = `token`); scripts may send `Authorization:
290    /// Bearer <token>`. Use this to serve the console to more than a single
291    /// trusted local operator. Pair with a TLS-terminating proxy for non-local
292    /// exposure — the token crosses the wire in the clear otherwise.
293    pub fn with_auth(mut self, token: String) -> Self {
294        // An empty token would authenticate `Authorization: Bearer ` (the
295        // empty credential) as the OWNER — refuse at the library boundary,
296        // not just in the CLI's --token-env validation.
297        assert!(
298            !token.trim().is_empty(),
299            "with_auth requires a non-empty token"
300        );
301        self.token = Some(token);
302        self.auth_all = true;
303        self
304    }
305
306    /// Permit or forbid destructive CAL (`FORGET <hash>`) from the query
307    /// console. Enabled by default; pass `false` to serve a read-only console.
308    /// Since the plain console is unauthenticated, disabling this is the safe
309    /// choice when the console is exposed beyond a trusted local operator.
310    pub fn allow_destructive_ops(mut self, allow: bool) -> Self {
311        self.allow_destructive_ops = allow;
312        self.rebuild_executor();
313        self
314    }
315
316    /// areevd mode: require `Authorization: Bearer <token>` on POST
317    /// endpoints and accept segment push/pull under `dir`.
318    pub fn into_hub(mut self, token: Option<String>, dir: &str) -> std::io::Result<Self> {
319        std::fs::create_dir_all(dir)?;
320        self.token = token;
321        self.segment_dir = Some(dir.to_string());
322        // The hub is a network service (segment push/pull from other nodes), so
323        // non-loopback Hosts are expected — writes stay bearer-gated.
324        self.allow_remote = true;
325        Ok(self)
326    }
327
328    /// Bind and return the listener (lets callers learn the ephemeral port).
329    pub fn bind(addr: &str) -> std::io::Result<TcpListener> {
330        TcpListener::bind(addr)
331    }
332
333    /// Serve forever on an already-bound listener.
334    pub fn serve(&self, listener: TcpListener) -> std::io::Result<()> {
335        for stream in listener.incoming() {
336            match stream {
337                Ok(s) => {
338                    if let Err(e) = self.handle(s) {
339                        eprintln!("areev ui: request error: {e}");
340                    }
341                }
342                Err(e) => eprintln!("areev ui: accept error: {e}"),
343            }
344        }
345        Ok(())
346    }
347
348    /// Configure native TLS from PEM files (`tls` cargo feature). The
349    /// documented default remains a TLS-terminating proxy; this is for
350    /// deployments with nowhere to put one (edge boxes, appliances).
351    #[cfg(feature = "tls")]
352    pub fn with_tls(mut self, cert_pem: &str, key_pem: &str) -> std::io::Result<Self> {
353        use rustls::pki_types::pem::PemObject;
354        let pem_err =
355            |e: rustls::pki_types::pem::Error| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string());
356        let certs: Vec<rustls::pki_types::CertificateDer<'static>> =
357            rustls::pki_types::CertificateDer::pem_file_iter(cert_pem)
358                .map_err(pem_err)?
359                .collect::<Result<_, _>>()
360                .map_err(pem_err)?;
361        let key =
362            rustls::pki_types::PrivateKeyDer::from_pem_file(key_pem).map_err(pem_err)?;
363        let config = rustls::ServerConfig::builder()
364            .with_no_client_auth()
365            .with_single_cert(certs, key)
366            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;
367        self.tls_config = Some(std::sync::Arc::new(config));
368        Ok(self)
369    }
370
371    /// Wrap an accepted socket per the TLS posture. The handshake happens
372    /// lazily on first read/write; a plaintext client fails it loudly.
373    fn wrap(&self, stream: TcpStream) -> std::io::Result<Conn> {
374        #[cfg(feature = "tls")]
375        if let Some(config) = &self.tls_config {
376            let session = rustls::ServerConnection::new(std::sync::Arc::clone(config))
377                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;
378            return Ok(Conn::Tls(Box::new(rustls::StreamOwned::new(session, stream))));
379        }
380        Ok(Conn::Plain(stream))
381    }
382
383    fn handle(&self, stream: TcpStream) -> std::io::Result<()> {
384        // The server handles one connection at a time, so a single slow-drip
385        // client could otherwise hold it open indefinitely (a per-read timeout
386        // resets on every byte). A watchdog thread enforces a hard wall-clock
387        // deadline by shutting the socket down; it is unparked and joined the
388        // instant the request completes, so it adds no latency in the fast path.
389        let watchdog_stream = stream.try_clone()?;
390        let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
391        let watchdog_done = std::sync::Arc::clone(&done);
392        let watchdog = std::thread::spawn(move || {
393            std::thread::park_timeout(Duration::from_secs(REQUEST_DEADLINE_SECS));
394            if !watchdog_done.load(std::sync::atomic::Ordering::Acquire) {
395                let _ = watchdog_stream.shutdown(std::net::Shutdown::Both);
396            }
397        });
398        let raw = stream.try_clone()?;
399        let conn = self.wrap(stream)?;
400        let result = self.handle_request(&raw, conn);
401        done.store(true, std::sync::atomic::Ordering::Release);
402        watchdog.thread().unpark();
403        let _ = watchdog.join();
404        result
405    }
406
407    fn handle_request(&self, raw: &TcpStream, mut conn: Conn) -> std::io::Result<()> {
408        // Bound slow clients (slowloris) and total bytes read from the
409        // connection so a malicious client cannot stall the server or exhaust
410        // memory with an oversized request line / headers / body. The
411        // timeouts sit on the RAW socket, so they bound TLS handshakes too.
412        raw.set_read_timeout(Some(Duration::from_secs(READ_TIMEOUT_SECS)))?;
413        raw.set_write_timeout(Some(Duration::from_secs(READ_TIMEOUT_SECS)))?;
414        let mut reader = BufReader::new((&mut conn).take(MAX_CONN_BYTES));
415        let mut request_line = String::new();
416        reader.read_line(&mut request_line)?;
417        let mut parts = request_line.split_whitespace();
418        let method = parts.next().unwrap_or("").to_string();
419        let path = parts.next().unwrap_or("/").to_string();
420
421        // headers → content-length + authorization + origin + host
422        let mut content_length = 0usize;
423        let mut bearer: Option<String> = None;
424        let mut origin: Option<String> = None;
425        let mut host: Option<String> = None;
426        let mut sso_identity_raw: Option<String> = None;
427        let mut proxy_secret: Option<String> = None;
428        let mut header_bytes = 0usize;
429        let mut header_count = 0usize;
430        loop {
431            let mut line = String::new();
432            let n = reader.read_line(&mut line)?;
433            if n == 0 {
434                break; // EOF / connection closed by peer
435            }
436            header_bytes += n;
437            header_count += 1;
438            if header_bytes > MAX_HEADER_BYTES || header_count > MAX_HEADERS {
439                return Err(std::io::Error::new(
440                    std::io::ErrorKind::InvalidData,
441                    "request headers too large",
442                ));
443            }
444            let l = line.trim();
445            if l.is_empty() {
446                break;
447            }
448            let low = l.to_ascii_lowercase();
449            if let Some(v) = low.strip_prefix("content-length:") {
450                content_length = v.trim().parse().unwrap_or(0);
451            }
452            if let Some(v) = low.strip_prefix("origin:") {
453                origin = Some(v.trim().to_string());
454            }
455            if let Some(v) = low.strip_prefix("host:") {
456                host = Some(v.trim().to_string());
457            }
458            if let Some(v) = low.strip_prefix("x-areev-proxy-secret:") {
459                // Secrets are compared, never logged; the lowercased copy is
460                // wrong for comparison, so re-slice the original line.
461                let _ = v;
462                if let Some((_, orig)) = l.split_once(':') {
463                    proxy_secret = Some(orig.trim().to_string());
464                }
465            }
466            if let Some(h) = &self.sso_header {
467                if low.starts_with(&format!("{h}:")) {
468                    if let Some((_, orig)) = l.split_once(':') {
469                        sso_identity_raw = Some(orig.trim().to_string());
470                    }
471                }
472            }
473            if low.starts_with("authorization:") {
474                if let Some((_, v)) = l.split_once(':') {
475                    let v = v.trim();
476                    // Accept `Bearer <token>` (scripts/CLI) or HTTP `Basic`
477                    // (browsers, via the native login prompt). For Basic the
478                    // credential is base64(user:pass) and the token is the
479                    // password; the username is ignored.
480                    bearer = if let Some(t) =
481                        v.strip_prefix("Bearer ").or_else(|| v.strip_prefix("bearer "))
482                    {
483                        Some(t.trim().to_string())
484                    } else if let Some(b64) =
485                        v.strip_prefix("Basic ").or_else(|| v.strip_prefix("basic "))
486                    {
487                        basic_auth_password(b64.trim())
488                    } else {
489                        Some(v.to_string())
490                    };
491                }
492            }
493        }
494        // DNS-rebinding defense: a browser tricked into pointing an attacker
495        // domain at 127.0.0.1 sends that domain in the Host header. Unless the
496        // operator opted into remote serving, reject any non-loopback Host on
497        // *every* method (the Origin check below only covers POST, so this is
498        // what stops a drive-by page from reading memory over GET). A missing
499        // Host (bare HTTP/1.0, some CLI clients) passes, mirroring Origin.
500        if !self.allow_remote && host.as_deref().is_some_and(|h| !host_is_local(h)) {
501            let payload = br#"{"ok":false,"error":"non-loopback Host rejected (use --allow-remote to serve remotely)"}"#;
502            drop(reader);
503            let mut out = conn;
504            write!(
505                out,
506                "HTTP/1.1 403 Forbidden\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
507                payload.len()
508            )?;
509            out.write_all(payload)?;
510            return out.flush();
511        }
512
513        let mut body = vec![0u8; content_length.min(1 << 20)];
514        if content_length > 0 {
515            reader.read_exact(&mut body)?;
516        }
517
518        // Cross-origin drive-by protection: browsers attach an Origin header
519        // to cross-site requests. Only loopback pages (the console itself)
520        // may mutate; curl/CLI clients send no Origin and pass through.
521        if method == "POST" && origin.as_deref().is_some_and(|o| !origin_is_local(o)) {
522            let payload = br#"{"ok":false,"error":"cross-origin request rejected"}"#;
523            drop(reader);
524            let mut out = conn;
525            write!(
526                out,
527                "HTTP/1.1 403 Forbidden\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
528                payload.len()
529            )?;
530            out.write_all(payload)?;
531            return out.flush();
532        }
533
534        // The identity header is TRUSTED only when the proxy proved itself
535        // (constant-time secret check). A forged header without the secret
536        // is silently ignored — the request proceeds as whatever its other
537        // credentials make it.
538        let sso_identity: Option<String> = match (&self.sso_secret, proxy_secret, sso_identity_raw) {
539            (Some(expected), Some(presented), Some(id))
540                if ct_eq(expected.as_bytes(), presented.as_bytes())
541                    && !id.trim().is_empty() =>
542            {
543                Some(id)
544            }
545            _ => None,
546        };
547        let (status, ctype, payload) =
548            self.route(&method, &path, &body, bearer.as_deref(), sso_identity.as_deref());
549        // On a console-auth 401, challenge with Basic so browsers show the
550        // native login prompt (any username; password = token).
551        let auth_challenge = if self.auth_all && status.starts_with("401") {
552            "WWW-Authenticate: Basic realm=\"Areev console\", charset=\"UTF-8\"\r\n"
553        } else {
554            ""
555        };
556        drop(reader);
557        let mut out = conn;
558        write!(
559            out,
560            "HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\n{auth_challenge}Content-Length: {}\r\nConnection: close\r\n\r\n",
561            payload.len()
562        )?;
563        out.write_all(&payload)?;
564        out.flush()
565    }
566
567    /// The runtime driver for the /api/run/* surface. The console never
568    /// EXECUTES tools (list/inspect read; respond/cancel journal) — the
569    /// executor is a refusing stub, present only to satisfy the driver
570    /// shape.
571    fn runner(&self, principal: &str) -> areev_run::Runner {
572        struct NoExec;
573        impl areev_run::HostToolExecutor for NoExec {
574            fn execute(
575                &self,
576                tool_name: &str,
577                _h: &str,
578                _i: &Value,
579                _k: &str,
580            ) -> areev_run::ExecResult {
581                areev_run::ExecResult::Err {
582                    cause: areev_run::FailCause::ExecutorError,
583                    detail: format!("the console does not execute tools ('{tool_name}')"),
584                }
585            }
586        }
587        areev_run::Runner {
588            facade: std::sync::Arc::clone(&self.facade),
589            clock: std::sync::Arc::new(areev_run::SystemClock),
590            executor: std::sync::Arc::new(NoExec),
591            llm: None,
592            observer: None,
593            ns: self
594                .facade
595                .default_namespace()
596                .unwrap_or("shared")
597                .to_string(),
598            principal: principal.to_string(),
599        }
600    }
601
602    fn route(
603        &self,
604        method: &str,
605        path: &str,
606        body: &[u8],
607        bearer: Option<&str>,
608        sso_identity: Option<&str>,
609    ) -> (&'static str, &'static str, Vec<u8>) {
610        // Auth: console-auth mode (`auth_all`) guards every request; hub mode
611        // guards only mutating + sync endpoints. The credential arrives as a
612        // Bearer token or an HTTP Basic password (see `handle_request`).
613        //
614        // A credential map changes WHO a request is, not WHETHER the shared
615        // secret is required. When both are configured, a map token
616        // authenticates as its principal, the shared secret authenticates as
617        // the implied admin (`docs/cal-all-you-need-proposal.md` §5.2b), and
618        // anything else is refused — an attached map must never silently
619        // downgrade a `--token-env` console to an open `anonymous` one.
620        let mut shared_secret_ok = false;
621        if let Some(tok) = &self.token {
622            let guarded = self.auth_all || method == "POST" || path.starts_with("/api/segment");
623            shared_secret_ok = bearer.is_some_and(|b| ct_eq(b.as_bytes(), tok.as_bytes()));
624            let known = shared_secret_ok
625                || sso_identity.is_some()
626                || match (&self.credentials, bearer) {
627                    (Some(map), Some(b)) => map.resolve_for_memory(b, &self.db_label).is_ok(),
628                    _ => false,
629                };
630            if guarded && !known {
631                return ("401 Unauthorized", "application/json",
632                        br#"{"ok":false,"error":"authentication required"}"#.to_vec());
633            }
634        } else if self.credentials.is_none() && sso_identity.is_none() && method == "POST" {
635            // §5.7: token-less `areev ui` is read-only. The ONLY POST allowed is
636            // a read-only CAL statement; every write (any loop mutation, an
637            // ADD/SUPERSEDE/FORGET CAL batch, etc.) requires --token-env. This
638            // closes the bypass where a local process could execute a
639            // proposal's CAL directly and skip the review queue.
640            let base = path.split_once('?').map(|(p, _)| p).unwrap_or(path);
641            let allowed = base == "/api/cal" && cal_body_is_read_only(body);
642            if !allowed {
643                return ("401 Unauthorized", "application/json",
644                        br#"{"ok":false,"error":"read-only console: restart areev ui with --token-env VAR to enable writes"}"#.to_vec());
645            }
646        }
647
648        // Credential-map mode: resolve this request's principal and bind
649        // the facade for the request's duration (the guard restores the
650        // owner default on drop). Every verb check downstream — CAL,
651        // loop scopes, the run gate below — now answers for THIS caller.
652        // A request authenticated by the shared secret keeps the owner
653        // session that secret has always carried.
654        let _session = match (&self.credentials, shared_secret_ok) {
655            (Some(map), false) => Some(RequestBinding::bind(&self.facade, map, bearer, &self.db_label)),
656            _ => None,
657        };
658        // The request's resolved PRINCIPAL identity — Some only when a
659        // per-principal credential authenticated it. The shared secret and
660        // anonymous access deliberately resolve to None: approvals need an
661        // identity, and "whoever holds the console token" is not one.
662        let mut request_principal: Option<String> = match (&self.credentials, shared_secret_ok, bearer)
663        {
664            (Some(map), false, Some(b)) => map.resolve_for_memory(b, &self.db_label).ok().map(str::to_string),
665            _ => None,
666        };
667        // SSO v0: a proxy-proven identity becomes the request principal when
668        // no bearer credential resolved one (machines keep tokens; SSO is
669        // for humans behind the proxy). Rights come from the file's grants.
670        let _sso_session = match (&request_principal, sso_identity, shared_secret_ok) {
671            (None, Some(identity), false) => {
672                request_principal = Some(identity.to_string());
673                Some(RequestBinding::bind_identity(&self.facade, identity))
674            }
675            _ => None,
676        };
677
678        let (path, query) = match path.split_once('?') {
679            Some((p, q)) => (p, q),
680            None => (path, ""),
681        };
682        let q = |key: &str| -> Option<String> {
683            query.split('&').find_map(|kv| {
684                let (k, v) = kv.split_once('=')?;
685                (k == key).then(|| urldecode(v))
686            })
687        };
688        match (method, path) {
689            ("GET", "/") => (
690                "200 OK",
691                "text/html; charset=utf-8",
692                CONSOLE_HTML
693                    .replace("{{DB}}", &html_escape(&self.db_label))
694                    .into_bytes(),
695            ),
696            ("POST", "/api/cal") => {
697                let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
698                let queryt = req.get("query").and_then(|v| v.as_str()).unwrap_or("");
699                match self.executor.execute(queryt, &*self.facade) {
700                    Ok(res) => ok_json(json!({
701                        "ok": true,
702                        "result": res.result,
703                        "warnings": res.warnings,
704                        "statement": res.metadata.statement_type,
705                        "elapsed_ms": res.metadata.execution_time_ms,
706                    })),
707                    Err(e) => {
708                        // Structured error: code + span + hint let the console
709                        // point at the offending token instead of just quoting.
710                        let mut err = json!({
711                            "ok": false,
712                            "error": e.sanitize_for_client(),
713                            "code": e.code(),
714                        });
715                        if let Some(sp) = e.span() {
716                            err["span"] = json!({
717                                "start": sp.start, "end": sp.end,
718                                "line": sp.line, "col": sp.col,
719                            });
720                        }
721                        if let Some(hint) = e.suggestion() {
722                            err["suggestion"] = json!(hint);
723                        }
724                        ok_json(err)
725                    }
726                }
727            }
728            ("GET", "/api/stats") => {
729                let stats = self.facade.with_store(|m| m.stats());
730                match stats {
731                    Ok(s) => ok_json(json!({
732                        "db": self.db_label,
733                        "grains": s.grains, "current": s.current,
734                        "triples": s.triples, "terms": s.terms,
735                        "ops": s.ops, "events_indexed": s.events_indexed,
736                    })),
737                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
738                }
739            }
740            ("GET", "/api/log") => {
741                let since: i64 = q("since").and_then(|v| v.parse().ok()).unwrap_or(0);
742                let limit: usize = q("limit").and_then(|v| v.parse().ok()).unwrap_or(100);
743                match self.facade.with_store(|m| m.changes_since(since, limit)) {
744                    Ok(ops) => {
745                        let rows: Vec<Value> = ops
746                            .iter()
747                            .map(|o| {
748                                json!({
749                                    "op_seq": o.op_seq, "hlc": o.hlc,
750                                    "op": match o.op { 1 => "add", 2 => "supersede", 3 => "forget", _ => "?" },
751                                    "hash": o.hash.to_hex(),
752                                })
753                            })
754                            .collect();
755                        ok_json(json!(rows))
756                    }
757                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
758                }
759            }
760            // Who am I: the principal this request is bound to. In
761            // credential-map mode this reflects the per-request binding;
762            // read-only and mode-agnostic.
763            ("GET", "/api/whoami") => {
764                let a = self.facade.authz();
765                ok_json(json!({
766                    "ok": true,
767                    "principal": a.principal(),
768                    "owner": a.is_owner(),
769                    "mode": if self.credentials.is_some() { "credentials" }
770                            else if self.token.is_some() { "token" }
771                            else { "open" },
772                }))
773            }
774            ("GET", "/api/config") => {
775                // Read-only observability: the *effective* per-process
776                // configuration. Nothing here is persisted in the .db —
777                // the file holds data only; these values are supplied by
778                // the host at open time.
779                let cfg = self.executor.config();
780                let (index_text, embedder_dim, declared_embed, mut warnings) =
781                    self.facade.with_store(|m| {
782                        (
783                            m.index_text_enabled(),
784                            m.embedder_dim(),
785                            m.declared_embedding().map(|(mm, d)| (mm.to_string(), d)),
786                            m.open_warnings().to_vec(),
787                        )
788                    });
789                if let Some((m, d)) = &declared_embed {
790                    if embedder_dim.is_none() {
791                        warnings.push(format!(
792                            "vector leg dormant: file expects {m}@{d}, no embedding backend installed"
793                        ));
794                    }
795                }
796                // Saved queries and templates the file carries that this build
797                // cannot load. Same class of thing as an open warning — the
798                // file and the host disagree — so it belongs in the same list.
799                warnings.extend(self.facade.meta_warnings());
800                ok_json(json!({
801                    "ok": true,
802                    "db": self.db_label,
803                    "warnings": warnings,
804                    "file": {
805                        "text_index": index_text,
806                        "embedding": declared_embed.map(|(m, d)| json!({"model": m, "dim": d})),
807                    },
808                    "session": {
809                        "namespace": self.facade.session_namespace(),
810                        "mounts": self.facade.mount_aliases(),
811                    },
812                    "store": {
813                        "index_text": index_text,
814                        "embedder": embedder_dim.map(|d| json!({"dim": d})),
815                    },
816                    "recall": {
817                        "fusion": "rrf",
818                        "rrf_k0": areev_store::RRF_K0,
819                        "overfetch_factor": AreevFacade::RECALL_OVERFETCH,
820                        "legs": {
821                            "structural": true,
822                            "bm25": index_text,
823                            "vector": embedder_dim.is_some(),
824                        },
825                    },
826                    "executor": {
827                        "max_limit": cfg.max_limit,
828                        "default_limit": cfg.default_limit,
829                        "tier1_writes": cfg.tier1_enabled,
830                        "namespace_override": cfg.namespace_override,
831                        "user_id_override": cfg.user_id_override,
832                    },
833                    "server": {
834                        "hub_mode": self.segment_dir.is_some(),
835                        "auth_required": self.token.is_some(),
836                        // true = every request is authenticated (console-auth);
837                        // false with auth_required = hub mode (writes/sync only).
838                        "auth_all": self.auth_all,
839                        "segment_dir": self.segment_dir,
840                    },
841                    "persistence": "per-process (host-supplied at open) — not stored in the .db",
842                }))
843            }
844            ("GET", "/api/browse") => {
845                // Browse-without-queries: the tail of the op-log joined with
846                // grain summaries, newest first. Supersession and tombstone
847                // status are resolved within the returned window so the
848                // console can dim/strike them (grains are never mutated —
849                // this reads the index + immutable blobs only).
850                let limit: i64 = q("limit")
851                    .and_then(|v| v.parse().ok())
852                    .unwrap_or(500)
853                    .clamp(1, 2000);
854                let built = self.facade.with_store(|m| -> Result<(i64, Vec<Value>), String> {
855                    let total = m.stats().map_err(|e| e.to_string())?.ops as i64;
856                    let after = (total - limit).max(0);
857                    let ops = m.changes_since(after, limit as usize).map_err(|e| e.to_string())?;
858                    let mut rows: Vec<Value> = Vec::with_capacity(ops.len());
859                    let mut idx: std::collections::HashMap<String, usize> =
860                        std::collections::HashMap::new();
861                    for o in &ops {
862                        let hex = o.hash.to_hex();
863                        let op_name = match o.op { 1 => "add", 2 => "supersede", 3 => "forget", _ => "?" };
864                        if o.op == 3 {
865                            // tombstone: flag the earlier row if it is in the
866                            // window, else emit a stub (blob is already gone).
867                            match idx.get(&hex) {
868                                Some(&i) => { rows[i]["forgotten"] = json!(true); }
869                                None => rows.push(json!({
870                                    "hash": hex, "op_seq": o.op_seq, "hlc": o.hlc,
871                                    "op": op_name, "forgotten": true,
872                                })),
873                            }
874                            continue;
875                        }
876                        // A SUPERSEDE logs two ops for the new grain (add +
877                        // supersede) — merge them into one row, keeping the
878                        // later op label.
879                        if let Some(&i) = idx.get(&hex) {
880                            rows[i]["op"] = json!(op_name);
881                            rows[i]["op_seq"] = json!(o.op_seq);
882                            rows[i]["hlc"] = json!(o.hlc);
883                            continue;
884                        }
885                        let mut row = json!({
886                            "hash": hex, "op_seq": o.op_seq, "hlc": o.hlc, "op": op_name,
887                        });
888                        match m.get(&o.hash) {
889                            Ok(g) => {
890                                row["type"] = json!(format!("{:?}", g.grain_type).to_lowercase());
891                                row["fields"] = serde_json::to_value(&g.fields).unwrap_or(Value::Null);
892                            }
893                            // erased since (forget op outside the window)
894                            Err(_) => { row["missing"] = json!(true); }
895                        }
896                        idx.insert(hex, rows.len());
897                        rows.push(row);
898                    }
899                    // A supersede op's grain points at its predecessor via
900                    // derived_from; mark the predecessor if it is in-window.
901                    let marks: Vec<(String, String)> = rows.iter()
902                        .filter(|r| r["op"] == "supersede")
903                        .filter_map(|r| {
904                            let old = r["fields"].get("derived_from")?.as_str()?;
905                            Some((old.to_string(), r["hash"].as_str()?.to_string()))
906                        })
907                        .collect();
908                    for (old, newer) in marks {
909                        if let Some(&i) = idx.get(&old) {
910                            rows[i]["superseded_by"] = json!(newer);
911                        }
912                    }
913                    rows.reverse();
914                    Ok((total, rows))
915                });
916                // Scope the browse to the session namespace, the way CAL
917                // already scopes recall. Without this the rail lists entities
918                // (`john`, `bob`) that every query on this console then reports
919                // as missing, because the two disagree about what is in view.
920                // Rows we cannot attribute — tombstone stubs, grains erased
921                // since — are kept: dropping them would hide an erasure.
922                let built = built.map(|(total, rows)| {
923                    let Some(ns) = self.facade.session_namespace() else {
924                        return (total, rows);
925                    };
926                    let kept = rows
927                        .into_iter()
928                        .filter(|r| {
929                            r["fields"]
930                                .get("namespace")
931                                .and_then(Value::as_str)
932                                .is_none_or(|got| got == ns)
933                        })
934                        .collect();
935                    (total, kept)
936                });
937                match built {
938                    Ok((total, rows)) => ok_json(json!({"ok": true, "total_ops": total, "grains": rows})),
939                    Err(e) => ok_json(json!({"ok": false, "error": e})),
940                }
941            }
942            ("GET", "/api/grain") => {
943                let hash = q("hash").unwrap_or_default();
944                match areev_core::error::Hash::from_hex(&hash)
945                    .and_then(|h| self.facade.get(&h))
946                {
947                    Ok(g) => ok_json(json!({
948                        "hash": g.hash.to_hex(),
949                        "type": format!("{:?}", g.grain_type).to_lowercase(),
950                        "fields": g.fields,
951                    })),
952                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
953                }
954            }
955            ("GET", "/api/verify") => match self.facade.with_store(|m| m.verify()) {
956                Ok(r) => ok_json(json!({
957                    "integrity": r.integrity, "grains": r.grains,
958                    "hash_mismatches": r.hash_mismatches, "undecodable": r.undecodable,
959                })),
960                Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
961            },
962            ("POST", "/api/segment") => {
963                // A pushed segment is imported straight into the live store,
964                // so it is a write — and one that never crosses the facade's
965                // verb checks. Gate it on the bound session's `write`, or a
966                // principal with no write grant could add grains here that
967                // `POST /api/cal` refuses it.
968                if let Err(e) = self
969                    .facade
970                    .authz()
971                    .check(areev_core::authz::Verb::Write, "*")
972                {
973                    return ("403 Forbidden", "application/json",
974                            json!({"ok": false, "error": e.to_string()}).to_string().into_bytes());
975                }
976                // push: body = raw MGB1 bundle; applied immediately + archived
977                let Some(dir) = &self.segment_dir else {
978                    return ("400 Bad Request", "application/json",
979                            br#"{"ok":false,"error":"not in hub mode"}"#.to_vec());
980                };
981                let name = q("name").unwrap_or_else(|| format!("push-{}.mgb", now_label()));
982                let Some(safe) = safe_segment_name(&name) else {
983                    return ("400 Bad Request", "application/json",
984                            br#"{"ok":false,"error":"invalid segment name"}"#.to_vec());
985                };
986                let path = format!("{dir}/{safe}");
987                if std::fs::write(&path, body).is_err() {
988                    return ("500 Internal Server Error", "application/json",
989                            br#"{"ok":false,"error":"write failed"}"#.to_vec());
990                }
991                match self.facade.with_store(|m| m.import_bundle(&path)) {
992                    Ok(st) => ok_json(json!({"ok": true, "applied": st.applied, "skipped": st.skipped, "stored": safe})),
993                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
994                }
995            }
996            ("GET", "/api/segments") | ("GET", "/api/segment") if !self.session_may_sync() => (
997                "403 Forbidden",
998                "application/json",
999                br#"{"ok":false,"error":"AUT-E001: this session lacks read on the whole memory"}"#.to_vec(),
1000            ),
1001            ("GET", "/api/segments") => {
1002                let Some(dir) = &self.segment_dir else {
1003                    return ok_json(json!([]));
1004                };
1005                let mut names: Vec<String> = std::fs::read_dir(dir)
1006                    .map(|d| d.filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().to_string()))
1007                        .filter(|n| n.ends_with(".mgb")).collect())
1008                    .unwrap_or_default();
1009                names.sort();
1010                ok_json(json!(names))
1011            }
1012            ("GET", "/api/segment") => {
1013                let Some(dir) = &self.segment_dir else {
1014                    return ("400 Bad Request", "application/json", b"{}".to_vec());
1015                };
1016                let name = q("name").unwrap_or_default();
1017                let Some(safe) = safe_segment_name(&name) else {
1018                    return ("400 Bad Request", "application/json",
1019                            br#"{"ok":false,"error":"invalid segment name"}"#.to_vec());
1020                };
1021                match std::fs::read(format!("{dir}/{safe}")) {
1022                    Ok(b) => ("200 OK", "application/octet-stream", b),
1023                    Err(_) => ("404 Not Found", "application/json",
1024                               br#"{"ok":false,"error":"no such segment"}"#.to_vec()),
1025                }
1026            }
1027            // ── Areev Loop API (§5.4) — GETs are reads (token-less OK); the POST
1028            //    mutations are guarded above (token-less → 401). ────────────
1029            // ── /api/run/*: the governed runtime's console surface ──
1030            ("GET", "/api/run/list") => {
1031                let runner = self.runner("console:read");
1032                match runner.recent_runs(50) {
1033                    Ok(ids) => {
1034                        let rows: Vec<Value> = ids
1035                            .iter()
1036                            .map(|id| {
1037                                let outcome = self.facade.with_store(|m| {
1038                                    m.recent(
1039                                        "agent:harness",
1040                                        Some(areev_core::types::GrainType::Observation),
1041                                        4096,
1042                                    )
1043                                })
1044                                .ok()
1045                                .and_then(|rows| {
1046                                    rows.into_iter().find(|g| {
1047                                        g.get_str("run_id") == Some(id.as_str())
1048                                            && g.get_str("observation_kind")
1049                                                == Some("run_outcome")
1050                                    })
1051                                });
1052                                serde_json::json!({
1053                                    "run_id": id,
1054                                    "outcome": outcome.as_ref().and_then(|g| g.get_str("object")).unwrap_or("open"),
1055                                })
1056                            })
1057                            .collect();
1058                        ok_json(serde_json::json!({"ok": true, "runs": rows}))
1059                    }
1060                    Err(e) => run_api_err(&e.to_string()),
1061                }
1062            }
1063            ("GET", "/api/run/inspect") => {
1064                let Some(run_id) = q("run_id") else {
1065                    return run_api_err("run_id required");
1066                };
1067                let manifest = self
1068                    .facade
1069                    .with_store(|m| areev_run::RunManifest::load(m, &run_id));
1070                let manifest = match manifest {
1071                    Ok(m) => m,
1072                    Err(e) => return run_api_err(&e.to_string()),
1073                };
1074                let ns = self.facade.default_namespace().unwrap_or("shared").to_string();
1075                let view = self
1076                    .facade
1077                    .with_store(|m| areev_run::journal::load(m, &ns, &run_id));
1078                let (checkpoints, entries, scheduler) = match view {
1079                    Ok(v) => {
1080                        let sched = v
1081                            .checkpoints
1082                            .last()
1083                            .map(|c| c.scheduler.clone())
1084                            .unwrap_or(Value::Null);
1085                        (v.checkpoints.len(), v.entries.len(), sched)
1086                    }
1087                    Err(_) => (0, 0, Value::Null),
1088                };
1089                ok_json(serde_json::json!({
1090                    "ok": true,
1091                    "run_id": run_id,
1092                    "plan_hash": manifest.plan_hash,
1093                    "principal": manifest.principal,
1094                    "checkpoints": checkpoints,
1095                    "journal_entries": entries,
1096                    "spent": scheduler.get("spent"),
1097                    "pending_asks": scheduler.get("pending_asks"),
1098                }))
1099            }
1100            ("POST", "/api/run/respond") => {
1101                // [R3] SHARED-TOKEN APPROVALS ARE REFUSED: an approval whose
1102                // "identity" is a console-wide secret voids the
1103                // approver-identity edge of the provenance chain. Only a
1104                // per-principal credential (areev ui --auth) may respond.
1105                let Some(responder) = request_principal.clone() else {
1106                    return ("403 Forbidden", "application/json",
1107                        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());
1108                };
1109                let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1110                let (Some(run_id), Some(ask)) = (
1111                    req.get("run_id").and_then(Value::as_str),
1112                    req.get("tool_call_id").and_then(Value::as_str),
1113                ) else {
1114                    return run_api_err("run_id and tool_call_id required");
1115                };
1116                let result = req.get("result").cloned().unwrap_or(Value::Null);
1117                let is_error = req.get("is_error").and_then(Value::as_bool).unwrap_or(false);
1118                let runner = self.runner(&responder);
1119                match runner.respond(run_id, ask, result, is_error, &responder) {
1120                    Ok(()) => ok_json(serde_json::json!({
1121                        "ok": true, "responded": ask, "responder": responder,
1122                        "note": "resume the run to spend the compute",
1123                    })),
1124                    Err(e) => run_api_err(&e.to_string()),
1125                }
1126            }
1127            ("POST", "/api/run/cancel") => {
1128                // The kill switch keeps its LOW bar: any authenticated POST
1129                // may brake a run (the identity label still records who).
1130                let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1131                let Some(run_id) = req.get("run_id").and_then(Value::as_str) else {
1132                    return run_api_err("run_id required");
1133                };
1134                let because = req.get("because").and_then(Value::as_str).unwrap_or("canceled via console");
1135                let who = request_principal.clone().unwrap_or_else(|| "console:shared".into());
1136                let runner = self.runner(&who);
1137                match runner.cancel(run_id, &who, because) {
1138                    Ok(()) => ok_json(serde_json::json!({"ok": true, "canceled": run_id})),
1139                    Err(e) => run_api_err(&e.to_string()),
1140                }
1141            }
1142            ("GET", "/api/loop/recommendations") => {
1143                let status = q("status").and_then(|s| status_from_str(&s));
1144                let sub = BorrowedSubstrate::new(&self.facade);
1145                match self.engine().recommendations(&sub, status) {
1146                    Ok(recs) => ok_json(json!({
1147                        "ok": true,
1148                        "recommendations": recs.iter().map(rec_json).collect::<Vec<_>>(),
1149                    })),
1150                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1151                }
1152            }
1153            ("GET", "/api/loop/health") => {
1154                let sub = BorrowedSubstrate::new(&self.facade);
1155                match self.engine().health(&sub, now_ms()) {
1156                    Ok(h) => ok_json(json!({"ok": true, "health": h})),
1157                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1158                }
1159            }
1160            ("GET", "/api/loop/outcomes") => {
1161                let sub = BorrowedSubstrate::new(&self.facade);
1162                match self.engine().outcomes(&sub) {
1163                    Ok(o) => ok_json(json!({"ok": true, "outcomes": o})),
1164                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1165                }
1166            }
1167            ("GET", "/api/loop/analyzers") => {
1168                // Effective settings (manifest merged with the file-config), so
1169                // the Setup view renders accurate on/off state and floors.
1170                let sub = BorrowedSubstrate::new(&self.facade);
1171                match self.engine().analyzer_settings(&sub) {
1172                    Ok(list) => ok_json(json!({"ok": true, "analyzers": list})),
1173                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1174                }
1175            }
1176            ("GET", "/api/loop/telemetry") => {
1177                // Recall-telemetry rollups for the Sessions view. A read — open
1178                // in read-only mode like the other loop GETs.
1179                let mode = self.facade.with_store(|m| m.telemetry_mode());
1180                if mode == areev_store::TelemetryMode::Off {
1181                    ok_json(json!({"ok": true, "enabled": false}))
1182                } else {
1183                    let access = self.facade.with_store(|m| m.telemetry_access_stats(None));
1184                    let queries = self.facade.with_store(|m| m.telemetry_query_stats(None));
1185                    let budget = self.facade.with_store(|m| m.telemetry_budget_stats());
1186                    match (access, queries, budget) {
1187                        (Ok(mut a), Ok(mut q), Ok(b)) => {
1188                            // Most-recalled first; recurring-gap questions first.
1189                            a.sort_by_key(|x| std::cmp::Reverse(x.recall_count));
1190                            a.truncate(200);
1191                            q.sort_by_key(|x| std::cmp::Reverse(x.run_count));
1192                            q.truncate(200);
1193                            ok_json(json!({
1194                                "ok": true,
1195                                "enabled": true,
1196                                "mode": mode.as_str(),
1197                                "access": a.iter().map(|x| json!({
1198                                    "hash": x.hash, "recall_count": x.recall_count, "last_ms": x.last_ms,
1199                                })).collect::<Vec<_>>(),
1200                                "queries": q.iter().map(|x| json!({
1201                                    "sample": x.sample, "run_count": x.run_count,
1202                                    "empty_count": x.empty_count,
1203                                })).collect::<Vec<_>>(),
1204                                "budget": {
1205                                    "sample_count": b.sample_count,
1206                                    "overflow_count": b.overflow_count,
1207                                },
1208                            }))
1209                        }
1210                        _ => ok_json(json!({"ok": false, "error": "telemetry read failed"})),
1211                    }
1212                }
1213            }
1214            ("POST", "/api/loop/run") => {
1215                let authz = self.facade.authz();
1216                if !authz.is_owner()
1217                    && !authz.allows(areev_core::authz::Verb::LoopRun, areev_loop::LOOP_NS)
1218                {
1219                    return ("403 Forbidden", "application/json",
1220                            br#"{"ok":false,"error":"AUT-E001: this session lacks loop.run"}"#.to_vec());
1221                }
1222                let mut sub = BorrowedSubstrate::new(&self.facade);
1223                // The trigger is recorded as co-creator on LLM/external
1224                // findings, so the same principal cannot later approve them.
1225                // In credential-map mode the actor IS the bound principal —
1226                // a request cannot claim an identity.
1227                let actor = if self.credentials.is_some() {
1228                    authz.principal().to_string()
1229                } else {
1230                    serde_json::from_slice::<Value>(body)
1231                        .ok()
1232                        .and_then(|v| v.get("actor").and_then(Value::as_str).map(str::to_string))
1233                        .unwrap_or_else(|| "user:console".to_string())
1234                };
1235                let opts = RunOptions { triggering_actor: Some(actor), ..Default::default() };
1236                match self.engine().run(&mut sub, &opts, now_ms()) {
1237                    Ok(res) => ok_json(json!({"ok": true, "run": res})),
1238                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1239                }
1240            }
1241            ("POST", "/api/loop/review") => self.loop_review(body),
1242            ("POST", "/api/loop/apply") => self.loop_apply(body),
1243            ("POST", "/api/loop/rollback") => self.loop_rollback(body),
1244            ("POST", "/api/loop/config") => self.loop_config(body),
1245            _ => (
1246                "404 Not Found",
1247                "application/json",
1248                br#"{"ok":false,"error":"not found"}"#.to_vec(),
1249            ),
1250        }
1251    }
1252
1253    /// The console session's scopes derive from its grants (an owner
1254    /// session — today's only mode — holds all of them); actor
1255    /// `user:console` unless overridden, observer derived from the actor
1256    /// label, never from request text.
1257    fn loop_review(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
1258        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1259        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
1260        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
1261        let bound = self.facade.authz();
1262        let actor = if self.credentials.is_some() {
1263            bound.principal().to_string()
1264        } else {
1265            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
1266        };
1267        let actor = actor.as_str();
1268        let decision = if req.get("decision").and_then(Value::as_str) == Some("reject") {
1269            Decision::Reject
1270        } else {
1271            Decision::Approve
1272        };
1273        let mut sub = BorrowedSubstrate::new(&self.facade);
1274        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
1275        let observer = areev_loop_adapter::observer_for_principal(actor);
1276        match self.engine().review(
1277            &mut sub, hash, decision, actor, observer, &scopes, because, now_ms(),
1278        ) {
1279            Ok(()) => ok_json(json!({"ok": true})),
1280            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1281        }
1282    }
1283
1284    fn loop_apply(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
1285        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1286        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
1287        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
1288        let bound = self.facade.authz();
1289        let actor = if self.credentials.is_some() {
1290            bound.principal().to_string()
1291        } else {
1292            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
1293        };
1294        let actor = actor.as_str();
1295        let allow_destructive = req.get("allow_destructive").and_then(Value::as_bool).unwrap_or(false);
1296        let mut sub = BorrowedSubstrate::new(&self.facade);
1297        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
1298        let observer = areev_loop_adapter::observer_for_principal(actor);
1299        match self.engine().apply(
1300            &mut sub, hash, actor, observer, &scopes, because, allow_destructive, now_ms(),
1301        ) {
1302            Ok(applied) => ok_json(json!({"ok": true, "rollbackable": applied.rollbackable})),
1303            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1304        }
1305    }
1306
1307    fn loop_rollback(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
1308        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1309        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
1310        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
1311        let bound = self.facade.authz();
1312        let actor = if self.credentials.is_some() {
1313            bound.principal().to_string()
1314        } else {
1315            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
1316        };
1317        let actor = actor.as_str();
1318        let mut sub = BorrowedSubstrate::new(&self.facade);
1319        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
1320        let observer = areev_loop_adapter::observer_for_principal(actor);
1321        match self.engine().rollback(
1322            &mut sub, hash, actor, observer, &scopes, because, now_ms(),
1323        ) {
1324            Ok(()) => ok_json(json!({"ok": true})),
1325            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1326        }
1327    }
1328
1329    /// Edit one analyzer's file-config from the Setup view. The body is
1330    /// `{analyzer_id, enabled?, severity_floor?, clear_floor?, params?,
1331    /// namespaces?}`; absent fields are left unchanged. The console holds all
1332    /// scopes (local root of trust), so `Admin` is satisfied; an unknown
1333    /// analyzer or bad param is a structured `ok:false` (not a 500).
1334    fn loop_config(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
1335        let id = serde_json::from_slice::<Value>(body)
1336            .ok()
1337            .and_then(|v| v.get("analyzer_id").and_then(Value::as_str).map(str::to_string))
1338            .unwrap_or_default();
1339        // The update reads the same body; the extra `analyzer_id` key is ignored.
1340        let update: areev_loop::AnalyzerConfigUpdate = serde_json::from_slice(body).unwrap_or_default();
1341        let mut sub = BorrowedSubstrate::new(&self.facade);
1342        match self.engine().set_analyzer_config(&mut sub, &id, update, &areev_loop_adapter::scopes_for(&self.facade.authz())) {
1343            Ok(cfg) => ok_json(json!({"ok": true, "config": cfg})),
1344            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1345        }
1346    }
1347}
1348
1349/// True when a `host[:port]` (or `[ipv6]:port`) authority names a loopback
1350/// host. Shared by the Origin drive-by check and the Host-header
1351/// (DNS-rebinding) check.
1352fn host_is_local(host_port: &str) -> bool {
1353    let host = if let Some(h) = host_port.strip_prefix('[') {
1354        h.split(']').next().unwrap_or("")
1355    } else {
1356        host_port.split(':').next().unwrap_or("")
1357    };
1358    matches!(host, "127.0.0.1" | "localhost" | "::1")
1359}
1360
1361/// True when an Origin header names a loopback host (any port, http/https).
1362fn origin_is_local(origin: &str) -> bool {
1363    let rest = origin
1364        .strip_prefix("http://")
1365        .or_else(|| origin.strip_prefix("https://"));
1366    let Some(rest) = rest else { return false };
1367    let host_port = rest.split('/').next().unwrap_or("");
1368    host_is_local(host_port)
1369}
1370
1371fn now_label() -> String {
1372    format!("{}", std::time::SystemTime::now()
1373        .duration_since(std::time::UNIX_EPOCH)
1374        .map(|d| d.as_millis())
1375        .unwrap_or(0))
1376}
1377
1378fn ok_json(v: Value) -> (&'static str, &'static str, Vec<u8>) {
1379    ("200 OK", "application/json", v.to_string().into_bytes())
1380}
1381
1382fn run_api_err(msg: &str) -> (&'static str, &'static str, Vec<u8>) {
1383    (
1384        "400 Bad Request",
1385        "application/json",
1386        serde_json::json!({"ok": false, "error": msg}).to_string().into_bytes(),
1387    )
1388}
1389
1390/// True when a `POST /api/cal` body is a read-only statement. Classification
1391/// is delegated to `areev-cal`'s exhaustive [`areev_cal::classify`] module —
1392/// the single source of truth — so grammar growth cannot desynchronize this
1393/// gate (a keyword sniff lived here before and would have silently
1394/// misclassified any new statement). Fail closed: unparseable text is not
1395/// read-only.
1396fn cal_body_is_read_only(body: &[u8]) -> bool {
1397    let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1398    let q = req.get("query").and_then(Value::as_str).unwrap_or("");
1399    areev_cal::classify::query_is_read_only(q)
1400}
1401
1402fn status_from_str(s: &str) -> Option<RecStatus> {
1403    match s {
1404        "pending" => Some(RecStatus::Pending),
1405        "approved" => Some(RecStatus::Approved),
1406        "rejected" => Some(RecStatus::Rejected),
1407        "applied" => Some(RecStatus::Applied),
1408        "rolled_back" => Some(RecStatus::RolledBack),
1409        "expired" => Some(RecStatus::Expired),
1410        _ => None, // includes "all"
1411    }
1412}
1413
1414fn rec_json(r: &areev_loop::Recommendation) -> Value {
1415    json!({
1416        "hash": r.hash,
1417        "status": r.status.as_str(),
1418        "severity": r.severity.as_str(),
1419        "analyzer": r.analyzer,
1420        "summary": r.summary.render(),
1421        "target_ref": r.target_ref,
1422        "destructive": r.destructive,
1423        "rollbackable": r.rollbackable,
1424        "evidence": r.evidence,
1425    })
1426}
1427
1428fn urldecode(s: &str) -> String {
1429    let mut out = Vec::new();
1430    let b = s.as_bytes();
1431    let mut i = 0;
1432    while i < b.len() {
1433        match b[i] {
1434            b'%' if i + 2 < b.len() + 1 && i + 2 < b.len() + 1 => {
1435                if i + 2 < b.len() + 1 && i + 2 < b.len() {
1436                    let hex = std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or("");
1437                    if let Ok(v) = u8::from_str_radix(hex, 16) {
1438                        out.push(v);
1439                        i += 3;
1440                        continue;
1441                    }
1442                }
1443                out.push(b[i]);
1444                i += 1;
1445            }
1446            b'+' => {
1447                out.push(b' ');
1448                i += 1;
1449            }
1450            c => {
1451                out.push(c);
1452                i += 1;
1453            }
1454        }
1455    }
1456    String::from_utf8_lossy(&out).to_string()
1457}
1458
1459fn html_escape(s: &str) -> String {
1460    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
1461}
1462
1463/// Constant-time byte comparison — avoids leaking the bearer token through
1464/// response timing. A length mismatch fails fast (token length is not secret).
1465fn ct_eq(a: &[u8], b: &[u8]) -> bool {
1466    if a.len() != b.len() {
1467        return false;
1468    }
1469    let mut diff = 0u8;
1470    for (x, y) in a.iter().zip(b.iter()) {
1471        diff |= x ^ y;
1472    }
1473    diff == 0
1474}
1475
1476/// Decode standard base64 (RFC 4648), enough for HTTP Basic credentials.
1477/// Hand-rolled to keep the server dependency-free. Returns `None` on any
1478/// invalid character or truncated input.
1479fn base64_decode(s: &str) -> Option<Vec<u8>> {
1480    fn val(c: u8) -> Option<u32> {
1481        match c {
1482            b'A'..=b'Z' => Some((c - b'A') as u32),
1483            b'a'..=b'z' => Some((c - b'a' + 26) as u32),
1484            b'0'..=b'9' => Some((c - b'0' + 52) as u32),
1485            b'+' => Some(62),
1486            b'/' => Some(63),
1487            _ => None,
1488        }
1489    }
1490    let s = s.trim().trim_end_matches('=');
1491    let mut out = Vec::with_capacity(s.len() * 3 / 4);
1492    let (mut acc, mut bits) = (0u32, 0u32);
1493    for &c in s.as_bytes() {
1494        acc = (acc << 6) | val(c)?;
1495        bits += 6;
1496        if bits >= 8 {
1497            bits -= 8;
1498            out.push((acc >> bits) as u8);
1499        }
1500    }
1501    Some(out)
1502}
1503
1504/// Extract the password from an HTTP Basic credential (`base64("user:pass")`).
1505/// The console ignores the username and treats the password as the token.
1506/// Returns `None` if the value is not valid base64/UTF-8 or has no `:`.
1507fn basic_auth_password(b64: &str) -> Option<String> {
1508    let text = String::from_utf8(base64_decode(b64)?).ok()?;
1509    text.split_once(':').map(|(_user, pass)| pass.to_string())
1510}
1511
1512/// Sanitize a client-supplied segment name into a single safe filename.
1513/// Strips anything outside `[A-Za-z0-9-._]`, then requires the result to be
1514/// exactly one normal path component — rejecting empty names, `.`/`..`, and
1515/// path separators so a push/pull cannot escape the segment directory.
1516fn safe_segment_name(name: &str) -> Option<String> {
1517    let safe: String = name
1518        .chars()
1519        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_'))
1520        .collect();
1521    if safe.is_empty() || safe.len() > 128 {
1522        return None;
1523    }
1524    let mut comps = std::path::Path::new(&safe).components();
1525    match (comps.next(), comps.next()) {
1526        (Some(std::path::Component::Normal(c)), None) if c.to_str() == Some(safe.as_str()) => {
1527            Some(safe)
1528        }
1529        _ => None,
1530    }
1531}
1532
1533#[cfg(test)]
1534mod loop_route_tests {
1535    use super::UiServer;
1536    use areev_cal::AreevFacade;
1537    use areev_core::types::{Fact, Grain};
1538    use areev_store::Areev;
1539
1540    fn server(auth: Option<&str>) -> UiServer {
1541        let dir = tempfile::tempdir().unwrap();
1542        let path = dir.path().join("t.db");
1543        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
1544        // Two identical facts → a duplicate-consolidation recommendation.
1545        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller")).unwrap();
1546        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller")).unwrap();
1547        std::mem::forget(dir); // keep the file alive for the server's lifetime
1548        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
1549        let s = UiServer::new(facade, "test".into());
1550        match auth {
1551            Some(t) => s.with_auth(t.to_string()),
1552            None => s,
1553        }
1554    }
1555
1556    fn text(r: &(&str, &str, Vec<u8>)) -> String {
1557        String::from_utf8_lossy(&r.2).to_string()
1558    }
1559
1560    #[test]
1561    fn token_less_console_is_read_only() {
1562        let s = server(None);
1563        // A loop mutation (run) is a write → 401.
1564        assert!(s.route("POST", "/api/loop/run", b"{}", None, None).0.starts_with("401"));
1565        // A write CAL → 401.
1566        let w = s.route("POST", "/api/cal", br#"{"query":"ADD fact SET subject=\"x\""}"#, None, None);
1567        assert!(w.0.starts_with("401"), "write CAL must be 401: {}", text(&w));
1568        // A read CAL → 200.
1569        let r = s.route("POST", "/api/cal", br#"{"query":"RECALL facts WHERE subject = \"acme\""}"#, None, None);
1570        assert!(r.0.starts_with("200"), "read CAL allowed: {}", text(&r));
1571        // Areev Loop reads stay open token-less.
1572        assert!(s.route("GET", "/api/loop/recommendations", b"", None, None).0.starts_with("200"));
1573    }
1574
1575    #[test]
1576    fn telemetry_endpoint_is_an_open_read() {
1577        let s = server(None);
1578        let r = s.route("GET", "/api/loop/telemetry", b"", None, None);
1579        assert!(r.0.starts_with("200"), "telemetry read open: {}", text(&r));
1580        let body = text(&r);
1581        assert!(body.contains("\"ok\":true"), "{body}");
1582        // The test store opens bare (telemetry off) → enabled:false.
1583        assert!(body.contains("\"enabled\":false"), "{body}");
1584    }
1585
1586    #[test]
1587    fn authenticated_run_review_apply_roundtrip() {
1588        let s = server(Some("tok"));
1589        let run = s.route("POST", "/api/loop/run", b"{}", Some("tok"), None);
1590        assert!(run.0.starts_with("200"), "run: {}", text(&run));
1591        assert!(text(&run).contains("\"ran\""));
1592
1593        let list = s.route("GET", "/api/loop/recommendations?status=pending", b"", Some("tok"), None);
1594        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
1595        let recs = v["recommendations"].as_array().unwrap();
1596        assert!(!recs.is_empty(), "at least one recommendation");
1597        let hash = recs[0]["hash"].as_str().unwrap().to_string();
1598
1599        let rev = s.route(
1600            "POST",
1601            "/api/loop/review",
1602            format!(r#"{{"hash":"{hash}","decision":"approve","because":"ok"}}"#).as_bytes(),
1603            Some("tok"),
1604            None,
1605        );
1606        assert!(text(&rev).contains("\"ok\":true"), "review: {}", text(&rev));
1607
1608        let ap = s.route(
1609            "POST",
1610            "/api/loop/apply",
1611            format!(r#"{{"hash":"{hash}","because":"go"}}"#).as_bytes(),
1612            Some("tok"),
1613            None,
1614        );
1615        assert!(text(&ap).contains("\"ok\":true"), "apply: {}", text(&ap));
1616    }
1617
1618    #[test]
1619    fn config_edit_toggles_analyzer_via_console() {
1620        let s = server(Some("tok"));
1621        // Token-less write → 401 (guarded like every POST).
1622        assert!(s.route("POST", "/api/loop/config", b"{}", None, None).0.starts_with("401"));
1623
1624        // Read the analyzers; pick one that is on by default.
1625        let list = s.route("GET", "/api/loop/analyzers", b"", Some("tok"), None);
1626        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
1627        let id = v["analyzers"]
1628            .as_array()
1629            .unwrap()
1630            .iter()
1631            .find(|x| x["enabled"] == true)
1632            .expect("some analyzer is on")["id"]
1633            .as_str()
1634            .unwrap()
1635            .to_string();
1636
1637        // Disable it via the console endpoint.
1638        let post = s.route(
1639            "POST",
1640            "/api/loop/config",
1641            format!(r#"{{"analyzer_id":"{id}","enabled":false}}"#).as_bytes(),
1642            Some("tok"),
1643            None,
1644        );
1645        assert!(text(&post).contains("\"ok\":true"), "config: {}", text(&post));
1646
1647        // It reads back disabled.
1648        let list2 = s.route("GET", "/api/loop/analyzers", b"", Some("tok"), None);
1649        let v2: serde_json::Value = serde_json::from_slice(&list2.2).unwrap();
1650        let now = v2["analyzers"]
1651            .as_array()
1652            .unwrap()
1653            .iter()
1654            .find(|x| x["id"] == id.as_str())
1655            .unwrap();
1656        assert_eq!(now["enabled"], false, "toggled off and persisted");
1657    }
1658
1659    #[test]
1660    fn self_approval_surfaces_lop_code() {
1661        let s = server(Some("tok"));
1662        s.route("POST", "/api/loop/run", b"{}", Some("tok"), None);
1663        let list = s.route("GET", "/api/loop/recommendations?status=pending", b"", Some("tok"), None);
1664        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
1665        let rec = &v["recommendations"].as_array().unwrap()[0];
1666        let hash = rec["hash"].as_str().unwrap();
1667        let analyzer = rec["analyzer"].as_str().unwrap();
1668        let creator = format!("engine:{analyzer}");
1669        // The engine actor approving its own proposal is blocked.
1670        let rev = s.route(
1671            "POST",
1672            "/api/loop/review",
1673            format!(r#"{{"hash":"{hash}","decision":"approve","because":"self","actor":"{creator}"}}"#).as_bytes(),
1674            Some("tok"),
1675            None,
1676        );
1677        assert!(text(&rev).contains("LOP-E021"), "self-approval blocked: {}", text(&rev));
1678    }
1679}
1680
1681#[cfg(test)]
1682mod security_tests {
1683    use super::{base64_decode, basic_auth_password, ct_eq, safe_segment_name};
1684
1685    #[test]
1686    fn ct_eq_matches_only_equal() {
1687        assert!(ct_eq(b"secret-token", b"secret-token"));
1688        assert!(!ct_eq(b"secret-token", b"secret-toker"));
1689        assert!(!ct_eq(b"secret", b"secret-token")); // length mismatch
1690        assert!(ct_eq(b"", b""));
1691    }
1692
1693    #[test]
1694    fn base64_decode_roundtrips_known_vectors() {
1695        // RFC 4648 test vectors (with and without padding).
1696        assert_eq!(base64_decode("").unwrap(), b"");
1697        assert_eq!(base64_decode("Zg==").unwrap(), b"f");
1698        assert_eq!(base64_decode("Zm8=").unwrap(), b"fo");
1699        assert_eq!(base64_decode("Zm9v").unwrap(), b"foo");
1700        assert_eq!(base64_decode("Zm9vYmFy").unwrap(), b"foobar");
1701        // padding is optional for us
1702        assert_eq!(base64_decode("Zg").unwrap(), b"f");
1703        // invalid characters are rejected
1704        assert!(base64_decode("****").is_none());
1705    }
1706
1707    #[test]
1708    fn basic_auth_extracts_password_ignoring_username() {
1709        // base64("areev:s3cret") and base64(":s3cret") both yield the token.
1710        assert_eq!(basic_auth_password("ZGVqYTpzM2NyZXQ=").as_deref(), Some("s3cret"));
1711        assert_eq!(basic_auth_password("OnMzY3JldA==").as_deref(), Some("s3cret"));
1712        // a password may itself contain ':' — only the first ':' splits.
1713        // base64("u:a:b") -> "a:b"
1714        assert_eq!(basic_auth_password("dTphOmI=").as_deref(), Some("a:b"));
1715        // no ':' at all → not a valid Basic credential
1716        assert_eq!(basic_auth_password("bm9jb2xvbg=="), None); // "nocolon"
1717        assert_eq!(basic_auth_password("****"), None); // not base64
1718    }
1719
1720    #[test]
1721    fn safe_segment_name_blocks_traversal() {
1722        assert_eq!(safe_segment_name("push-123.mgb").as_deref(), Some("push-123.mgb"));
1723        assert_eq!(safe_segment_name(".."), None);
1724        assert_eq!(safe_segment_name("."), None);
1725        assert_eq!(safe_segment_name(""), None);
1726        // Separators are stripped, so any accepted name is a single component
1727        // that cannot escape the segment directory.
1728        for probe in ["../../etc/passwd", "/etc/passwd", "a/../b", "foo/bar"] {
1729            if let Some(s) = safe_segment_name(probe) {
1730                assert!(!s.contains('/') && s != ".." && s != ".", "unsafe: {s}");
1731            }
1732        }
1733    }
1734}
1735
1736#[cfg(test)]
1737mod credential_route_tests {
1738    use super::UiServer;
1739    use areev_cal::AreevFacade;
1740    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
1741    use areev_core::types::{Fact, Grain};
1742    use areev_store::Areev;
1743
1744    /// A server in credential-map mode: two env-referenced tokens, rights
1745    /// seeded as grant grains in the file itself.
1746    fn server() -> UiServer {
1747        std::env::set_var("AREEV_TEST_READER_TOK", "reader-secret");
1748        std::env::set_var("AREEV_TEST_WRITER_TOK", "writer-secret");
1749        let dir = tempfile::tempdir().unwrap();
1750        let path = dir.path().join("t.db");
1751        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
1752        store
1753            .add(&Fact::new("user:reader", REL_PERMITS, "read ON *").namespace(AUTHZ_NS).created_at(1_000))
1754            .unwrap();
1755        store
1756            .add(
1757                &Fact::new("agent:writer", REL_PERMITS, "read,write ON caller")
1758                    .namespace(AUTHZ_NS)
1759                    .created_at(2_000),
1760            )
1761            .unwrap();
1762        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(3_000)).unwrap();
1763        std::mem::forget(dir);
1764        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
1765        let map = CredentialMap::from_json(
1766            r#"{"version":1,"tokens":[
1767                {"env":"AREEV_TEST_READER_TOK","principal":"user:reader"},
1768                {"env":"AREEV_TEST_WRITER_TOK","principal":"agent:writer"}
1769            ]}"#,
1770        )
1771        .unwrap();
1772        UiServer::new(facade, "test".into()).with_credentials(map)
1773    }
1774
1775    fn text(r: &(&str, &str, Vec<u8>)) -> String {
1776        String::from_utf8_lossy(&r.2).to_string()
1777    }
1778
1779    const READ: &[u8] = br#"{"query":"RECALL facts WHERE subject = \"acme\""}"#;
1780    const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
1781
1782    #[test]
1783    fn tokens_bind_principals_and_verbs_decide() {
1784        let s = server();
1785
1786        // The reader reads…
1787        let r = s.route("POST", "/api/cal", READ, Some("reader-secret"), None);
1788        assert!(r.0.starts_with("200"), "{}", text(&r));
1789        assert!(text(&r).contains("grains"));
1790        // …and cannot write.
1791        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
1792        assert!(text(&w).contains("AUT-E001"), "reader write must be refused: {}", text(&w));
1793
1794        // The writer writes.
1795        let w = s.route("POST", "/api/cal", WRITE, Some("writer-secret"), None);
1796        assert!(text(&w).contains("added"), "writer write must land: {}", text(&w));
1797
1798        // Sequential isolation: the very next reader request is still
1799        // read-only — nothing leaked from the writer's binding.
1800        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
1801        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
1802    }
1803
1804    #[test]
1805    fn anonymous_is_read_only_and_loop_run_is_verb_gated() {
1806        let s = server();
1807        // No token → anonymous: reads work…
1808        let r = s.route("POST", "/api/cal", READ, None, None);
1809        assert!(r.0.starts_with("200"), "{}", text(&r));
1810        assert!(text(&r).contains("grains"));
1811        // …writes are verb-refused…
1812        let w = s.route("POST", "/api/cal", WRITE, None, None);
1813        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
1814        // …and an unknown token is anonymous too, never an escalation.
1815        let w = s.route("POST", "/api/cal", WRITE, Some("stolen-guess"), None);
1816        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
1817
1818        // The analysis trigger needs loop.run — anonymous gets 403.
1819        let run = s.route("POST", "/api/loop/run", b"{}", None, None);
1820        assert!(run.0.starts_with("403"), "{}", text(&run));
1821    }
1822
1823    #[test]
1824    fn whoami_reports_the_bound_principal() {
1825        let s = server();
1826        let r = s.route("GET", "/api/whoami", b"", Some("reader-secret"), None);
1827        assert!(text(&r).contains("user:reader"), "{}", text(&r));
1828        assert!(text(&r).contains("credentials"));
1829        let r = s.route("GET", "/api/whoami", b"", None, None);
1830        assert!(text(&r).contains("anonymous"), "{}", text(&r));
1831    }
1832
1833    /// A credential map must not silently disable `--token-env`. Attaching
1834    /// one changes WHO a request is; the operator who also asked for a
1835    /// shared secret still gets authentication on every request.
1836    #[test]
1837    fn a_credential_map_does_not_disable_the_shared_secret() {
1838        let s = server().with_auth("console-token".into());
1839
1840        // No credential at all: refused, not dropped to `anonymous`.
1841        let r = s.route("POST", "/api/cal", READ, None, None);
1842        assert!(r.0.starts_with("401"), "{}", text(&r));
1843        let page = s.route("GET", "/", b"", None, None);
1844        assert!(page.0.starts_with("401"), "the console page is guarded too");
1845        // An unrecognized token is refused rather than downgraded.
1846        let r = s.route("POST", "/api/cal", READ, Some("stolen-guess"), None);
1847        assert!(r.0.starts_with("401"), "{}", text(&r));
1848
1849        // A map token still binds its principal and its verbs still decide.
1850        let r = s.route("POST", "/api/cal", READ, Some("reader-secret"), None);
1851        assert!(r.0.starts_with("200"), "{}", text(&r));
1852        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
1853        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
1854
1855        // The shared secret is the implied admin (docs/cal-all-you-need
1856        // -proposal.md §5.2b) — it keeps the owner session it always had.
1857        let w = s.route("POST", "/api/cal", WRITE, Some("console-token"), None);
1858        assert!(text(&w).contains("added"), "{}", text(&w));
1859    }
1860
1861    /// `RUN LOOP` through CAL is gated exactly as `POST /api/loop/run` is —
1862    /// otherwise the CAL surface is a way around the HTTP gate.
1863    #[test]
1864    fn run_loop_via_cal_is_verb_gated_like_the_route() {
1865        let s = server();
1866        let run = s.route("POST", "/api/loop/run", b"{}", None, None);
1867        assert!(run.0.starts_with("403"), "{}", text(&run));
1868        let cal = s.route("POST", "/api/cal", br#"{"query":"RUN LOOP"}"#, None, None);
1869        assert!(
1870            text(&cal).contains("AUT-E001"),
1871            "anonymous must not run the loop through CAL either: {}",
1872            text(&cal)
1873        );
1874    }
1875}
1876
1877#[cfg(test)]
1878mod builder_tests {
1879    use super::UiServer;
1880    use areev_cal::AreevFacade;
1881    use areev_store::Areev;
1882
1883    fn server() -> UiServer {
1884        let dir = tempfile::tempdir().unwrap();
1885        let path = dir.path().join("t.db");
1886        let store = Areev::open(path.to_str().unwrap()).unwrap();
1887        std::mem::forget(dir);
1888        UiServer::new(AreevFacade::with_session(store, Some("caller".into()), None), "t".into())
1889    }
1890
1891    /// `areev ui --no-destructive-ops --policy FILE` calls these in this
1892    /// order. A later builder must not re-enable destruction the operator
1893    /// turned off — the console was announced as read-only.
1894    #[test]
1895    fn attaching_a_loop_policy_preserves_the_destructive_cap() {
1896        let s = server()
1897            .allow_destructive_ops(false)
1898            .with_loop_policy(areev_loop::Policy::default());
1899        let r = s.route(
1900            "POST",
1901            "/api/cal",
1902            br#"{"query":"FORGET sha256:684c6c9bda818630a870119d0726e4d242ed537af061658ef6f3acb158a2c67d"}"#,
1903            None,
1904            None,
1905        );
1906        let body = String::from_utf8_lossy(&r.2).to_string();
1907        assert!(
1908            body.contains("--no-destructive-ops") || r.0.starts_with("401"),
1909            "destruction must stay disabled: {body}"
1910        );
1911    }
1912}
1913
1914#[cfg(test)]
1915mod run_api_tests {
1916    use super::UiServer;
1917    use areev_cal::AreevFacade;
1918    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
1919    use areev_core::types::{Fact, Grain, Tool, ToolKind, Workflow};
1920    use areev_store::Areev;
1921    use std::sync::Arc;
1922
1923    /// A server whose file holds a PARKED run (Client-gated approve node) —
1924    /// the HITL queue's fixture. Returns (server, ask id).
1925    fn parked_server() -> (UiServer, String) {
1926        std::env::set_var("AREEV_RUN_OFFICER_TOK", "officer-secret");
1927        std::env::set_var("AREEV_RUN_STARTER_TOK", "starter-secret");
1928        let dir = tempfile::tempdir().unwrap();
1929        let path = dir.path().join("t.db");
1930        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
1931        for (who, what) in [
1932            ("user:officer", "read,run.respond ON ops"),
1933            ("user:starter", "read ON ops"),
1934        ] {
1935            store
1936                .add(&Fact::new(who, REL_PERMITS, what).namespace(AUTHZ_NS).created_at(900))
1937                .unwrap();
1938        }
1939        std::mem::forget(dir);
1940        let facade = Arc::new(AreevFacade::with_session(store, Some("ops".into()), None));
1941
1942        // Seed + run the plan to the park with a scripted runner.
1943        let (wf, _g, _a) = facade
1944            .with_store(|m| {
1945                let greet = Tool::new("greet")
1946                    .kind(ToolKind::Definition)
1947                    .tool_description("t")
1948                    .created_at(500)
1949                    .namespace("ops");
1950                let gh = m.add(&greet)?;
1951                let approve = Tool::new("approve")
1952                    .kind(ToolKind::Definition)
1953                    .tool_description("human approves")
1954                    .executor_kind(areev_core::types::ExecutorKind::Client)
1955                    .created_at(501)
1956                    .namespace("ops");
1957                let ah = m.add(&approve)?;
1958                let wf = Workflow::new(vec!["greet".into(), "approve".into()])
1959                    .edge("greet", "approve")
1960                    .bind("greet", &gh.to_hex())
1961                    .bind("approve", &ah.to_hex())
1962                    .created_at(502)
1963                    .namespace("ops");
1964                let wh = m.add(&wf)?;
1965                Ok::<_, areev_core::error::AreevError>((wh, gh, ah))
1966            })
1967            .unwrap();
1968        struct Ok1;
1969        impl areev_run::HostToolExecutor for Ok1 {
1970            fn execute(
1971                &self,
1972                t: &str,
1973                _h: &str,
1974                _i: &serde_json::Value,
1975                _k: &str,
1976            ) -> areev_run::ExecResult {
1977                areev_run::ExecResult::Ok(serde_json::json!({t.to_string(): true}))
1978            }
1979        }
1980        let runner = areev_run::Runner {
1981            facade: Arc::clone(&facade),
1982            clock: Arc::new(areev_run::ScriptedClock::new(
1983                (0..100).map(|i| 1_758_000_000_000 + i * 10).collect(),
1984            )),
1985            executor: Arc::new(Ok1),
1986            llm: None,
1987            observer: None,
1988            ns: "ops".into(),
1989            principal: "user:starter".into(),
1990        };
1991        let session = runner
1992            .start(&wf, "hitl-1", serde_json::json!({}), &areev_run::RunOptions {
1993                workers: 1,
1994                ..Default::default()
1995            })
1996            .unwrap();
1997        let areev_run::RunSession::Parked { envelope, .. } = session else {
1998            panic!("expected park")
1999        };
2000        let ask = envelope["asks"][0]["tool_call_id"].as_str().unwrap().to_string();
2001
2002        // Rebuild a facade-owning server over the SAME file is impossible
2003        // (single writer) — hand the server the same Arc'd facade via the
2004        // Arc-aware constructor path: UiServer::new takes AreevFacade, so
2005        // we build the server FIRST in real deployments; here we reuse the
2006        // internal Arc through a second UiServer field write. Instead:
2007        // drop the runner (facade Arc count drops) and unwrap.
2008        drop(runner);
2009        let facade = Arc::try_unwrap(facade).unwrap_or_else(|_| panic!("facade still shared"));
2010        let map = CredentialMap::from_json(
2011            r#"{"version":1,"tokens":[
2012                {"env":"AREEV_RUN_OFFICER_TOK","principal":"user:officer"},
2013                {"env":"AREEV_RUN_STARTER_TOK","principal":"user:starter"}
2014            ]}"#,
2015        )
2016        .unwrap();
2017        let server = UiServer::new(facade, "test".into())
2018            .with_auth("shared-console-secret".into())
2019            .with_credentials(map);
2020        (server, ask)
2021    }
2022
2023    fn body(run_id: &str, ask: &str) -> Vec<u8> {
2024        serde_json::json!({"run_id": run_id, "tool_call_id": ask, "result": {"approved": true}})
2025            .to_string()
2026            .into_bytes()
2027    }
2028
2029    #[test]
2030    fn shared_token_approvals_are_refused_and_principals_approve() {
2031        let (s, ask) = parked_server();
2032
2033        // The HITL queue is visible.
2034        let r = s.route("GET", "/api/run/list", b"", Some("shared-console-secret"), None);
2035        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
2036        let r = s.route(
2037            "GET",
2038            "/api/run/inspect?run_id=hitl-1",
2039            b"",
2040            Some("shared-console-secret"),
2041            None,
2042        );
2043        assert!(String::from_utf8_lossy(&r.2).contains(&ask), "ask visible in inspect");
2044
2045        // 1. The SHARED console secret cannot approve — identity is the point.
2046        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("shared-console-secret"), None);
2047        assert!(r.0.starts_with("403"), "shared-token approval must refuse: {}", r.0);
2048
2049        // 2. The STARTER's own credential cannot approve their own run
2050        //    (separation of duties, enforced by the runtime).
2051        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("starter-secret"), None);
2052        let text = String::from_utf8_lossy(&r.2).to_string();
2053        assert!(text.contains("responder") || text.contains("RUN-E012"), "{text}");
2054
2055        // 3. The officer's principal-bound credential approves.
2056        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("officer-secret"), None);
2057        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
2058        assert!(String::from_utf8_lossy(&r.2).contains("user:officer"));
2059
2060        // 4. The kill switch keeps its low bar: shared token may cancel.
2061        let r = s.route(
2062            "POST",
2063            "/api/run/cancel",
2064            br#"{"run_id":"hitl-1","because":"test brake"}"#,
2065            Some("shared-console-secret"),
2066            None,
2067        );
2068        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
2069    }
2070}
2071
2072#[cfg(test)]
2073mod memory_scoped_token_tests {
2074    use super::UiServer;
2075    use areev_cal::AreevFacade;
2076    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
2077    use areev_core::types::{Fact, Grain};
2078    use areev_store::Areev;
2079
2080    /// The enterprise-plane hub rule: one auth file, per-memory token
2081    /// scopes — a token listed for memory A is an UNKNOWN token on
2082    /// memory B's server.
2083    #[test]
2084    fn memory_scoped_tokens_do_not_cross_memories() {
2085        std::env::set_var("AREEV_SCOPED_TOK", "scoped-secret");
2086        let map_json = r#"{"version":1,"tokens":[
2087            {"env":"AREEV_SCOPED_TOK","principal":"agent:sync","memories":["memory-a"]}
2088        ]}"#;
2089        let server_for = |label: &str| {
2090            let dir = tempfile::tempdir().unwrap();
2091            let mut store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
2092            store
2093                .add(
2094                    &Fact::new("agent:sync", REL_PERMITS, "read,write ON caller")
2095                        .namespace(AUTHZ_NS)
2096                        .created_at(1_000),
2097                )
2098                .unwrap();
2099            store
2100                .add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(2_000))
2101                .unwrap();
2102            std::mem::forget(dir);
2103            let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2104            UiServer::new(facade, label.into())
2105                .with_credentials(CredentialMap::from_json(map_json).unwrap())
2106        };
2107        const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
2108
2109        // On memory-a the token authenticates and its grants let the write
2110        // through (no authorization refusal in the CAL payload).
2111        let a = server_for("memory-a");
2112        let r = a.route("POST", "/api/cal", WRITE, Some("scoped-secret"), None);
2113        let text = String::from_utf8_lossy(&r.2).to_string();
2114        assert!(r.0.starts_with("200") && !text.contains("AUT-E001"), "{text}");
2115
2116        // On memory-b the SAME token is an unknown credential: the request
2117        // runs as anonymous and the write is refused (AUT-E001 rides the
2118        // CAL payload — the console surfaces statement results in-band).
2119        let b = server_for("memory-b");
2120        let r = b.route("POST", "/api/cal", WRITE, Some("scoped-secret"), None);
2121        let text = String::from_utf8_lossy(&r.2).to_string();
2122        assert!(
2123            text.contains("AUT-E001") && text.contains("anonymous"),
2124            "scoped token must not cross memories: {text}"
2125        );
2126
2127        // An auth file with an EMPTY memories scope refuses to load.
2128        assert!(CredentialMap::from_json(
2129            r#"{"version":1,"tokens":[{"env":"AREEV_SCOPED_TOK","principal":"x","memories":[]}]}"#
2130        )
2131        .is_err());
2132    }
2133}
2134
2135#[cfg(all(test, feature = "tls"))]
2136mod tls_tests {
2137    use super::UiServer;
2138    use areev_cal::AreevFacade;
2139    use areev_store::Areev;
2140    use std::io::{Read, Write};
2141
2142    fn self_signed(dir: &std::path::Path) -> Option<(String, String)> {
2143        let cert = dir.join("cert.pem");
2144        let key = dir.join("key.pem");
2145        let status = std::process::Command::new("openssl")
2146            .args([
2147                "req", "-x509", "-newkey", "rsa:2048", "-nodes",
2148                "-keyout", key.to_str().unwrap(), "-out", cert.to_str().unwrap(),
2149                "-days", "1", "-subj", "/CN=localhost",
2150                "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1",
2151                "-addext", "basicConstraints=critical,CA:FALSE",
2152            ])
2153            .stdout(std::process::Stdio::null())
2154            .stderr(std::process::Stdio::null())
2155            .status();
2156        match status {
2157            Ok(s) if s.success() => Some((
2158                cert.to_str().unwrap().to_string(),
2159                key.to_str().unwrap().to_string(),
2160            )),
2161            _ => None, // no openssl on this host: the CI leg covers it
2162        }
2163    }
2164
2165    /// The §3.2 gate: a TLS round-trip succeeds, and a PLAINTEXT client on
2166    /// the same listener is refused (no silent downgrade).
2167    #[test]
2168    fn tls_round_trip_and_no_plaintext_downgrade() {
2169        let dir = tempfile::tempdir().unwrap();
2170        let Some((cert, key)) = self_signed(dir.path()) else {
2171            eprintln!("skipping: no openssl binary");
2172            return;
2173        };
2174        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
2175        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2176        let server = UiServer::new(facade, "tls-test".into())
2177            .with_tls(&cert, &key)
2178            .unwrap();
2179        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2180        let addr = listener.local_addr().unwrap();
2181        let handle = std::thread::spawn(move || {
2182            // Two connections: the TLS client, then the plaintext prober.
2183            for _ in 0..2 {
2184                if let Ok((s, _)) = listener.accept() {
2185                    let _ = server.handle(s);
2186                }
2187            }
2188        });
2189
2190        // 1. TLS round-trip: trust exactly our self-signed cert.
2191        let mut roots = rustls::RootCertStore::empty();
2192        {
2193            use rustls::pki_types::pem::PemObject;
2194            for c in rustls::pki_types::CertificateDer::pem_file_iter(&cert).unwrap() {
2195                roots.add(c.unwrap()).unwrap();
2196            }
2197        }
2198        let config = std::sync::Arc::new(
2199            rustls::ClientConfig::builder()
2200                .with_root_certificates(roots)
2201                .with_no_client_auth(),
2202        );
2203        let name = rustls::pki_types::ServerName::try_from("localhost").unwrap();
2204        let session = rustls::ClientConnection::new(config, name).unwrap();
2205        let tcp = std::net::TcpStream::connect(addr).unwrap();
2206        let mut tls = rustls::StreamOwned::new(session, tcp);
2207        tls.write_all(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")
2208            .unwrap();
2209        let mut response = String::new();
2210        let _ = tls.read_to_string(&mut response);
2211        assert!(response.starts_with("HTTP/1.1 200"), "{}", &response[..response.len().min(120)]);
2212        assert!(response.contains("Areev"), "console served over TLS");
2213
2214        // 2. No downgrade: plaintext HTTP on the TLS listener gets a
2215        // handshake failure, never a page.
2216        let mut plain = std::net::TcpStream::connect(addr).unwrap();
2217        plain
2218            .write_all(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")
2219            .unwrap();
2220        let mut buf = Vec::new();
2221        let _ = plain.read_to_end(&mut buf);
2222        let text = String::from_utf8_lossy(&buf);
2223        assert!(
2224            !text.contains("HTTP/1.1 200"),
2225            "plaintext must not be served on a TLS listener: {text}"
2226        );
2227        handle.join().unwrap();
2228    }
2229}
2230
2231#[cfg(test)]
2232mod sso_tests {
2233    use super::UiServer;
2234    use areev_cal::AreevFacade;
2235    use areev_core::authz::{AUTHZ_NS, REL_PERMITS};
2236    use areev_core::types::{Fact, Grain};
2237    use areev_store::Areev;
2238    use std::io::{Read, Write};
2239
2240    const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
2241
2242    fn sso_server() -> UiServer {
2243        let dir = tempfile::tempdir().unwrap();
2244        let mut store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
2245        store
2246            .add(
2247                &Fact::new("user:pat@example.com", REL_PERMITS, "read,write ON caller")
2248                    .namespace(AUTHZ_NS)
2249                    .created_at(1_000),
2250            )
2251            .unwrap();
2252        std::mem::forget(dir);
2253        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2254        UiServer::new(facade, "sso-test".into()).with_sso("x-forwarded-user", "proxy-secret")
2255    }
2256
2257    fn post(server: &UiServer, extra_headers: &str) -> String {
2258        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2259        let addr = listener.local_addr().unwrap();
2260        std::thread::scope(|scope| {
2261            scope.spawn(|| {
2262                if let Ok((s, _)) = listener.accept() {
2263                    let _ = server.handle(s);
2264                }
2265            });
2266            let mut c = std::net::TcpStream::connect(addr).unwrap();
2267            let req = format!(
2268                "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",
2269                WRITE.len()
2270            );
2271            c.write_all(req.as_bytes()).unwrap();
2272            c.write_all(WRITE).unwrap();
2273            let mut out = String::new();
2274            let _ = c.read_to_string(&mut out);
2275            out
2276        })
2277    }
2278
2279    /// The §3.3 gate: a proxy-proven identity lands as a named actor whose
2280    /// FILE grants decide; a forged identity header without the proxy
2281    /// secret is ignored (the write is refused as anonymous).
2282    #[test]
2283    fn proxied_identity_works_and_forged_headers_are_ignored() {
2284        let server = sso_server();
2285
2286        // 1. Proxy-proven: identity + secret → the granted principal writes.
2287        let ok = post(
2288            &server,
2289            "X-Forwarded-User: user:pat@example.com\r\nX-Areev-Proxy-Secret: proxy-secret\r\n",
2290        );
2291        assert!(ok.contains("HTTP/1.1 200"), "{}", &ok[..ok.len().min(200)]);
2292        assert!(!ok.contains("AUT-E001"), "granted principal must write: {ok}");
2293
2294        // 2. Forged: the identity header WITHOUT the secret is ignored — the
2295        // request is anonymous and the write refuses.
2296        let forged = post(&server, "X-Forwarded-User: user:pat@example.com\r\n");
2297        assert!(
2298            forged.contains("anonymous") || forged.contains("401"),
2299            "forged identity must not authenticate: {forged}"
2300        );
2301
2302        // 3. Wrong secret: same refusal (constant-time compare, same path).
2303        let wrong = post(
2304            &server,
2305            "X-Forwarded-User: user:pat@example.com\r\nX-Areev-Proxy-Secret: guess\r\n",
2306        );
2307        assert!(
2308            wrong.contains("anonymous") || wrong.contains("401"),
2309            "wrong proxy secret must not authenticate: {wrong}"
2310        );
2311    }
2312}