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                // Anonymization observability (REQ-ANON-5: no policy is
801                // loud): declared per-ns modes, the host floor, and the
802                // audit counters. Modes only — never mappings or values.
803                let (anon_declared, anon_floor, anon_audit) = self.facade.with_store(|m| {
804                    (
805                        m.anon_declared(),
806                        m.anonymize_egress_floor(),
807                        m.anon_audit_counts(),
808                    )
809                });
810                let anonymization = json!({
811                    "policies": anon_declared
812                        .iter()
813                        .map(|(ns, mode)| json!({"ns": ns, "mode": mode}))
814                        .collect::<Vec<_>>(),
815                    "floor": anon_floor,
816                    "audit_counts": anon_audit
817                        .iter()
818                        .map(|(ns, cat, n)| json!({"ns": ns, "category": cat, "count": n}))
819                        .collect::<Vec<_>>(),
820                });
821                ok_json(json!({
822                    "ok": true,
823                    "db": self.db_label,
824                    "warnings": warnings,
825                    "anonymization": anonymization,
826                    "file": {
827                        "text_index": index_text,
828                        "embedding": declared_embed.map(|(m, d)| json!({"model": m, "dim": d})),
829                    },
830                    "session": {
831                        "namespace": self.facade.session_namespace(),
832                        "mounts": self.facade.mount_aliases(),
833                    },
834                    "store": {
835                        "index_text": index_text,
836                        "embedder": embedder_dim.map(|d| json!({"dim": d})),
837                    },
838                    "recall": {
839                        "fusion": "rrf",
840                        "rrf_k0": areev_store::RRF_K0,
841                        "overfetch_factor": AreevFacade::RECALL_OVERFETCH,
842                        "legs": {
843                            "structural": true,
844                            "bm25": index_text,
845                            "vector": embedder_dim.is_some(),
846                        },
847                    },
848                    "executor": {
849                        "max_limit": cfg.max_limit,
850                        "default_limit": cfg.default_limit,
851                        "tier1_writes": cfg.tier1_enabled,
852                        "namespace_override": cfg.namespace_override,
853                        "user_id_override": cfg.user_id_override,
854                    },
855                    "server": {
856                        "hub_mode": self.segment_dir.is_some(),
857                        "auth_required": self.token.is_some(),
858                        // true = every request is authenticated (console-auth);
859                        // false with auth_required = hub mode (writes/sync only).
860                        "auth_all": self.auth_all,
861                        "segment_dir": self.segment_dir,
862                    },
863                    "persistence": "per-process (host-supplied at open) — not stored in the .db",
864                }))
865            }
866            ("GET", "/api/browse") => {
867                // Browse-without-queries: the tail of the op-log joined with
868                // grain summaries, newest first. Supersession and tombstone
869                // status are resolved within the returned window so the
870                // console can dim/strike them (grains are never mutated —
871                // this reads the index + immutable blobs only).
872                let limit: i64 = q("limit")
873                    .and_then(|v| v.parse().ok())
874                    .unwrap_or(500)
875                    .clamp(1, 2000);
876                let built = self.facade.with_store(|m| -> Result<(i64, Vec<Value>), String> {
877                    let total = m.stats().map_err(|e| e.to_string())?.ops as i64;
878                    let after = (total - limit).max(0);
879                    let ops = m.changes_since(after, limit as usize).map_err(|e| e.to_string())?;
880                    let mut rows: Vec<Value> = Vec::with_capacity(ops.len());
881                    let mut idx: std::collections::HashMap<String, usize> =
882                        std::collections::HashMap::new();
883                    for o in &ops {
884                        let hex = o.hash.to_hex();
885                        let op_name = match o.op { 1 => "add", 2 => "supersede", 3 => "forget", _ => "?" };
886                        if o.op == 3 {
887                            // tombstone: flag the earlier row if it is in the
888                            // window, else emit a stub (blob is already gone).
889                            match idx.get(&hex) {
890                                Some(&i) => { rows[i]["forgotten"] = json!(true); }
891                                None => rows.push(json!({
892                                    "hash": hex, "op_seq": o.op_seq, "hlc": o.hlc,
893                                    "op": op_name, "forgotten": true,
894                                })),
895                            }
896                            continue;
897                        }
898                        // A SUPERSEDE logs two ops for the new grain (add +
899                        // supersede) — merge them into one row, keeping the
900                        // later op label.
901                        if let Some(&i) = idx.get(&hex) {
902                            rows[i]["op"] = json!(op_name);
903                            rows[i]["op_seq"] = json!(o.op_seq);
904                            rows[i]["hlc"] = json!(o.hlc);
905                            continue;
906                        }
907                        let mut row = json!({
908                            "hash": hex, "op_seq": o.op_seq, "hlc": o.hlc, "op": op_name,
909                        });
910                        match m.get(&o.hash) {
911                            Ok(g) => {
912                                row["type"] = json!(format!("{:?}", g.grain_type).to_lowercase());
913                                row["fields"] = serde_json::to_value(&g.fields).unwrap_or(Value::Null);
914                            }
915                            // erased since (forget op outside the window)
916                            Err(_) => { row["missing"] = json!(true); }
917                        }
918                        idx.insert(hex, rows.len());
919                        rows.push(row);
920                    }
921                    // A supersede op's grain points at its predecessor via
922                    // derived_from; mark the predecessor if it is in-window.
923                    let marks: Vec<(String, String)> = rows.iter()
924                        .filter(|r| r["op"] == "supersede")
925                        .filter_map(|r| {
926                            let old = r["fields"].get("derived_from")?.as_str()?;
927                            Some((old.to_string(), r["hash"].as_str()?.to_string()))
928                        })
929                        .collect();
930                    for (old, newer) in marks {
931                        if let Some(&i) = idx.get(&old) {
932                            rows[i]["superseded_by"] = json!(newer);
933                        }
934                    }
935                    rows.reverse();
936                    Ok((total, rows))
937                });
938                // Scope the browse to the session namespace, the way CAL
939                // already scopes recall. Without this the rail lists entities
940                // (`john`, `bob`) that every query on this console then reports
941                // as missing, because the two disagree about what is in view.
942                // Rows we cannot attribute — tombstone stubs, grains erased
943                // since — are kept: dropping them would hide an erasure.
944                let built = built.map(|(total, rows)| {
945                    let Some(ns) = self.facade.session_namespace() else {
946                        return (total, rows);
947                    };
948                    let kept = rows
949                        .into_iter()
950                        .filter(|r| {
951                            r["fields"]
952                                .get("namespace")
953                                .and_then(Value::as_str)
954                                .is_none_or(|got| got == ns)
955                        })
956                        .collect();
957                    (total, kept)
958                });
959                match built {
960                    Ok((total, rows)) => ok_json(json!({"ok": true, "total_ops": total, "grains": rows})),
961                    Err(e) => ok_json(json!({"ok": false, "error": e})),
962                }
963            }
964            ("GET", "/api/grain") => {
965                let hash = q("hash").unwrap_or_default();
966                match areev_core::error::Hash::from_hex(&hash)
967                    .and_then(|h| self.facade.get(&h))
968                {
969                    Ok(g) => ok_json(json!({
970                        "hash": g.hash.to_hex(),
971                        "type": format!("{:?}", g.grain_type).to_lowercase(),
972                        "fields": g.fields,
973                    })),
974                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
975                }
976            }
977            ("GET", "/api/anon/preview") => {
978                // "As the model sees it" (proposal §8.3): the grain rendered
979                // the way an egress boundary would show it, policy or not.
980                let hash = q("hash").unwrap_or_default();
981                match areev_core::error::Hash::from_hex(&hash)
982                    .and_then(|h| self.facade.with_store(|m| m.anon_preview(&h)))
983                {
984                    Ok(g) => ok_json(json!({
985                        "hash": g.hash.to_hex(),
986                        "type": format!("{:?}", g.grain_type).to_lowercase(),
987                        "fields": g.fields,
988                    })),
989                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
990                }
991            }
992            ("GET", "/api/verify") => match self.facade.with_store(|m| m.verify()) {
993                Ok(r) => ok_json(json!({
994                    "integrity": r.integrity, "grains": r.grains,
995                    "hash_mismatches": r.hash_mismatches, "undecodable": r.undecodable,
996                })),
997                Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
998            },
999            ("POST", "/api/segment") => {
1000                // A pushed segment is imported straight into the live store,
1001                // so it is a write — and one that never crosses the facade's
1002                // verb checks. Gate it on the bound session's `write`, or a
1003                // principal with no write grant could add grains here that
1004                // `POST /api/cal` refuses it.
1005                if let Err(e) = self
1006                    .facade
1007                    .authz()
1008                    .check(areev_core::authz::Verb::Write, "*")
1009                {
1010                    return ("403 Forbidden", "application/json",
1011                            json!({"ok": false, "error": e.to_string()}).to_string().into_bytes());
1012                }
1013                // push: body = raw MGB1 bundle; applied immediately + archived
1014                let Some(dir) = &self.segment_dir else {
1015                    return ("400 Bad Request", "application/json",
1016                            br#"{"ok":false,"error":"not in hub mode"}"#.to_vec());
1017                };
1018                let name = q("name").unwrap_or_else(|| format!("push-{}.mgb", now_label()));
1019                let Some(safe) = safe_segment_name(&name) else {
1020                    return ("400 Bad Request", "application/json",
1021                            br#"{"ok":false,"error":"invalid segment name"}"#.to_vec());
1022                };
1023                let path = format!("{dir}/{safe}");
1024                if std::fs::write(&path, body).is_err() {
1025                    return ("500 Internal Server Error", "application/json",
1026                            br#"{"ok":false,"error":"write failed"}"#.to_vec());
1027                }
1028                match self.facade.with_store(|m| m.import_bundle(&path)) {
1029                    Ok(st) => ok_json(json!({"ok": true, "applied": st.applied, "skipped": st.skipped, "stored": safe})),
1030                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
1031                }
1032            }
1033            ("GET", "/api/segments") | ("GET", "/api/segment") if !self.session_may_sync() => (
1034                "403 Forbidden",
1035                "application/json",
1036                br#"{"ok":false,"error":"AUT-E001: this session lacks read on the whole memory"}"#.to_vec(),
1037            ),
1038            ("GET", "/api/segments") => {
1039                let Some(dir) = &self.segment_dir else {
1040                    return ok_json(json!([]));
1041                };
1042                let mut names: Vec<String> = std::fs::read_dir(dir)
1043                    .map(|d| d.filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().to_string()))
1044                        .filter(|n| n.ends_with(".mgb")).collect())
1045                    .unwrap_or_default();
1046                names.sort();
1047                ok_json(json!(names))
1048            }
1049            ("GET", "/api/segment") => {
1050                let Some(dir) = &self.segment_dir else {
1051                    return ("400 Bad Request", "application/json", b"{}".to_vec());
1052                };
1053                let name = q("name").unwrap_or_default();
1054                let Some(safe) = safe_segment_name(&name) else {
1055                    return ("400 Bad Request", "application/json",
1056                            br#"{"ok":false,"error":"invalid segment name"}"#.to_vec());
1057                };
1058                match std::fs::read(format!("{dir}/{safe}")) {
1059                    Ok(b) => ("200 OK", "application/octet-stream", b),
1060                    Err(_) => ("404 Not Found", "application/json",
1061                               br#"{"ok":false,"error":"no such segment"}"#.to_vec()),
1062                }
1063            }
1064            // ── Areev Loop API (§5.4) — GETs are reads (token-less OK); the POST
1065            //    mutations are guarded above (token-less → 401). ────────────
1066            // ── /api/run/*: the governed runtime's console surface ──
1067            ("GET", "/api/run/list") => {
1068                let runner = self.runner("console:read");
1069                match runner.recent_runs(50) {
1070                    Ok(ids) => {
1071                        let rows: Vec<Value> = ids
1072                            .iter()
1073                            .map(|id| {
1074                                let outcome = self.facade.with_store(|m| {
1075                                    m.recent(
1076                                        "agent:harness",
1077                                        Some(areev_core::types::GrainType::Observation),
1078                                        4096,
1079                                    )
1080                                })
1081                                .ok()
1082                                .and_then(|rows| {
1083                                    rows.into_iter().find(|g| {
1084                                        g.get_str("run_id") == Some(id.as_str())
1085                                            && g.get_str("observation_kind")
1086                                                == Some("run_outcome")
1087                                    })
1088                                });
1089                                serde_json::json!({
1090                                    "run_id": id,
1091                                    "outcome": outcome.as_ref().and_then(|g| g.get_str("object")).unwrap_or("open"),
1092                                })
1093                            })
1094                            .collect();
1095                        ok_json(serde_json::json!({"ok": true, "runs": rows}))
1096                    }
1097                    Err(e) => run_api_err(&e.to_string()),
1098                }
1099            }
1100            ("GET", "/api/run/inspect") => {
1101                let Some(run_id) = q("run_id") else {
1102                    return run_api_err("run_id required");
1103                };
1104                let manifest = self
1105                    .facade
1106                    .with_store(|m| areev_run::RunManifest::load(m, &run_id));
1107                let manifest = match manifest {
1108                    Ok(m) => m,
1109                    Err(e) => return run_api_err(&e.to_string()),
1110                };
1111                let ns = self.facade.default_namespace().unwrap_or("shared").to_string();
1112                let view = self
1113                    .facade
1114                    .with_store(|m| areev_run::journal::load(m, &ns, &run_id));
1115                let (checkpoints, entries, scheduler) = match view {
1116                    Ok(v) => {
1117                        let sched = v
1118                            .checkpoints
1119                            .last()
1120                            .map(|c| c.scheduler.clone())
1121                            .unwrap_or(Value::Null);
1122                        (v.checkpoints.len(), v.entries.len(), sched)
1123                    }
1124                    Err(_) => (0, 0, Value::Null),
1125                };
1126                ok_json(serde_json::json!({
1127                    "ok": true,
1128                    "run_id": run_id,
1129                    "plan_hash": manifest.plan_hash,
1130                    "principal": manifest.principal,
1131                    "checkpoints": checkpoints,
1132                    "journal_entries": entries,
1133                    "spent": scheduler.get("spent"),
1134                    "pending_asks": scheduler.get("pending_asks"),
1135                }))
1136            }
1137            ("POST", "/api/run/respond") => {
1138                // [R3] SHARED-TOKEN APPROVALS ARE REFUSED: an approval whose
1139                // "identity" is a console-wide secret voids the
1140                // approver-identity edge of the provenance chain. Only a
1141                // per-principal credential (areev ui --auth) may respond.
1142                let Some(responder) = request_principal.clone() else {
1143                    return ("403 Forbidden", "application/json",
1144                        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());
1145                };
1146                let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1147                let (Some(run_id), Some(ask)) = (
1148                    req.get("run_id").and_then(Value::as_str),
1149                    req.get("tool_call_id").and_then(Value::as_str),
1150                ) else {
1151                    return run_api_err("run_id and tool_call_id required");
1152                };
1153                let result = req.get("result").cloned().unwrap_or(Value::Null);
1154                let is_error = req.get("is_error").and_then(Value::as_bool).unwrap_or(false);
1155                let runner = self.runner(&responder);
1156                match runner.respond(run_id, ask, result, is_error, &responder) {
1157                    Ok(()) => ok_json(serde_json::json!({
1158                        "ok": true, "responded": ask, "responder": responder,
1159                        "note": "resume the run to spend the compute",
1160                    })),
1161                    Err(e) => run_api_err(&e.to_string()),
1162                }
1163            }
1164            ("POST", "/api/run/cancel") => {
1165                // The kill switch keeps its LOW bar: any authenticated POST
1166                // may brake a run (the identity label still records who).
1167                let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1168                let Some(run_id) = req.get("run_id").and_then(Value::as_str) else {
1169                    return run_api_err("run_id required");
1170                };
1171                let because = req.get("because").and_then(Value::as_str).unwrap_or("canceled via console");
1172                let who = request_principal.clone().unwrap_or_else(|| "console:shared".into());
1173                let runner = self.runner(&who);
1174                match runner.cancel(run_id, &who, because) {
1175                    Ok(()) => ok_json(serde_json::json!({"ok": true, "canceled": run_id})),
1176                    Err(e) => run_api_err(&e.to_string()),
1177                }
1178            }
1179            ("GET", "/api/loop/recommendations") => {
1180                let status = q("status").and_then(|s| status_from_str(&s));
1181                let sub = BorrowedSubstrate::new(&self.facade);
1182                match self.engine().recommendations(&sub, status) {
1183                    Ok(recs) => ok_json(json!({
1184                        "ok": true,
1185                        "recommendations": recs.iter().map(rec_json).collect::<Vec<_>>(),
1186                    })),
1187                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1188                }
1189            }
1190            ("GET", "/api/loop/health") => {
1191                let sub = BorrowedSubstrate::new(&self.facade);
1192                match self.engine().health(&sub, now_ms()) {
1193                    Ok(h) => ok_json(json!({"ok": true, "health": h})),
1194                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1195                }
1196            }
1197            ("GET", "/api/loop/outcomes") => {
1198                let sub = BorrowedSubstrate::new(&self.facade);
1199                match self.engine().outcomes(&sub) {
1200                    Ok(o) => ok_json(json!({"ok": true, "outcomes": o})),
1201                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1202                }
1203            }
1204            ("GET", "/api/loop/analyzers") => {
1205                // Effective settings (manifest merged with the file-config), so
1206                // the Setup view renders accurate on/off state and floors.
1207                let sub = BorrowedSubstrate::new(&self.facade);
1208                match self.engine().analyzer_settings(&sub) {
1209                    Ok(list) => ok_json(json!({"ok": true, "analyzers": list})),
1210                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1211                }
1212            }
1213            ("GET", "/api/loop/telemetry") => {
1214                // Recall-telemetry rollups for the Sessions view. A read — open
1215                // in read-only mode like the other loop GETs.
1216                let mode = self.facade.with_store(|m| m.telemetry_mode());
1217                if mode == areev_store::TelemetryMode::Off {
1218                    ok_json(json!({"ok": true, "enabled": false}))
1219                } else {
1220                    let access = self.facade.with_store(|m| m.telemetry_access_stats(None));
1221                    let queries = self.facade.with_store(|m| m.telemetry_query_stats(None));
1222                    let budget = self.facade.with_store(|m| m.telemetry_budget_stats());
1223                    match (access, queries, budget) {
1224                        (Ok(mut a), Ok(mut q), Ok(b)) => {
1225                            // Most-recalled first; recurring-gap questions first.
1226                            a.sort_by_key(|x| std::cmp::Reverse(x.recall_count));
1227                            a.truncate(200);
1228                            q.sort_by_key(|x| std::cmp::Reverse(x.run_count));
1229                            q.truncate(200);
1230                            ok_json(json!({
1231                                "ok": true,
1232                                "enabled": true,
1233                                "mode": mode.as_str(),
1234                                "access": a.iter().map(|x| json!({
1235                                    "hash": x.hash, "recall_count": x.recall_count, "last_ms": x.last_ms,
1236                                })).collect::<Vec<_>>(),
1237                                "queries": q.iter().map(|x| json!({
1238                                    "sample": x.sample, "run_count": x.run_count,
1239                                    "empty_count": x.empty_count,
1240                                })).collect::<Vec<_>>(),
1241                                "budget": {
1242                                    "sample_count": b.sample_count,
1243                                    "overflow_count": b.overflow_count,
1244                                },
1245                            }))
1246                        }
1247                        _ => ok_json(json!({"ok": false, "error": "telemetry read failed"})),
1248                    }
1249                }
1250            }
1251            ("POST", "/api/loop/run") => {
1252                let authz = self.facade.authz();
1253                if !authz.is_owner()
1254                    && !authz.allows(areev_core::authz::Verb::LoopRun, areev_loop::LOOP_NS)
1255                {
1256                    return ("403 Forbidden", "application/json",
1257                            br#"{"ok":false,"error":"AUT-E001: this session lacks loop.run"}"#.to_vec());
1258                }
1259                let mut sub = BorrowedSubstrate::new(&self.facade);
1260                // The trigger is recorded as co-creator on LLM/external
1261                // findings, so the same principal cannot later approve them.
1262                // In credential-map mode the actor IS the bound principal —
1263                // a request cannot claim an identity.
1264                let actor = if self.credentials.is_some() {
1265                    authz.principal().to_string()
1266                } else {
1267                    serde_json::from_slice::<Value>(body)
1268                        .ok()
1269                        .and_then(|v| v.get("actor").and_then(Value::as_str).map(str::to_string))
1270                        .unwrap_or_else(|| "user:console".to_string())
1271                };
1272                let opts = RunOptions { triggering_actor: Some(actor), ..Default::default() };
1273                match self.engine().run(&mut sub, &opts, now_ms()) {
1274                    Ok(res) => ok_json(json!({"ok": true, "run": res})),
1275                    Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1276                }
1277            }
1278            ("POST", "/api/loop/review") => self.loop_review(body),
1279            ("POST", "/api/loop/apply") => self.loop_apply(body),
1280            ("POST", "/api/loop/rollback") => self.loop_rollback(body),
1281            ("POST", "/api/loop/config") => self.loop_config(body),
1282            ("POST", "/api/anon/config") => self.anon_config(body),
1283            _ => (
1284                "404 Not Found",
1285                "application/json",
1286                br#"{"ok":false,"error":"not found"}"#.to_vec(),
1287            ),
1288        }
1289    }
1290
1291    /// The console session's scopes derive from its grants (an owner
1292    /// session — today's only mode — holds all of them); actor
1293    /// `user:console` unless overridden, observer derived from the actor
1294    /// label, never from request text.
1295    fn loop_review(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
1296        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1297        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
1298        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
1299        let bound = self.facade.authz();
1300        let actor = if self.credentials.is_some() {
1301            bound.principal().to_string()
1302        } else {
1303            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
1304        };
1305        let actor = actor.as_str();
1306        let decision = if req.get("decision").and_then(Value::as_str) == Some("reject") {
1307            Decision::Reject
1308        } else {
1309            Decision::Approve
1310        };
1311        let mut sub = BorrowedSubstrate::new(&self.facade);
1312        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
1313        let observer = areev_loop_adapter::observer_for_principal(actor);
1314        match self.engine().review(
1315            &mut sub, hash, decision, actor, observer, &scopes, because, now_ms(),
1316        ) {
1317            Ok(()) => ok_json(json!({"ok": true})),
1318            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1319        }
1320    }
1321
1322    fn loop_apply(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
1323        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1324        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
1325        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
1326        let bound = self.facade.authz();
1327        let actor = if self.credentials.is_some() {
1328            bound.principal().to_string()
1329        } else {
1330            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
1331        };
1332        let actor = actor.as_str();
1333        let allow_destructive = req.get("allow_destructive").and_then(Value::as_bool).unwrap_or(false);
1334        let mut sub = BorrowedSubstrate::new(&self.facade);
1335        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
1336        let observer = areev_loop_adapter::observer_for_principal(actor);
1337        match self.engine().apply(
1338            &mut sub, hash, actor, observer, &scopes, because, allow_destructive, now_ms(),
1339        ) {
1340            Ok(applied) => ok_json(json!({"ok": true, "rollbackable": applied.rollbackable})),
1341            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1342        }
1343    }
1344
1345    fn loop_rollback(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
1346        let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1347        let hash = req.get("hash").and_then(Value::as_str).unwrap_or("");
1348        let because = req.get("because").and_then(Value::as_str).unwrap_or("");
1349        let bound = self.facade.authz();
1350        let actor = if self.credentials.is_some() {
1351            bound.principal().to_string()
1352        } else {
1353            req.get("actor").and_then(Value::as_str).unwrap_or("user:console").to_string()
1354        };
1355        let actor = actor.as_str();
1356        let mut sub = BorrowedSubstrate::new(&self.facade);
1357        let scopes = areev_loop_adapter::scopes_for(&self.facade.authz());
1358        let observer = areev_loop_adapter::observer_for_principal(actor);
1359        match self.engine().rollback(
1360            &mut sub, hash, actor, observer, &scopes, because, now_ms(),
1361        ) {
1362            Ok(()) => ok_json(json!({"ok": true})),
1363            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1364        }
1365    }
1366
1367    /// Edit one analyzer's file-config from the Setup view. The body is
1368    /// `{analyzer_id, enabled?, severity_floor?, clear_floor?, params?,
1369    /// namespaces?}`; absent fields are left unchanged. The console holds all
1370    /// scopes (local root of trust), so `Admin` is satisfied; an unknown
1371    /// analyzer or bad param is a structured `ok:false` (not a 500).
1372    fn loop_config(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
1373        let id = serde_json::from_slice::<Value>(body)
1374            .ok()
1375            .and_then(|v| v.get("analyzer_id").and_then(Value::as_str).map(str::to_string))
1376            .unwrap_or_default();
1377        // The update reads the same body; the extra `analyzer_id` key is ignored.
1378        let update: areev_loop::AnalyzerConfigUpdate = serde_json::from_slice(body).unwrap_or_default();
1379        let mut sub = BorrowedSubstrate::new(&self.facade);
1380        match self.engine().set_analyzer_config(&mut sub, &id, update, &areev_loop_adapter::scopes_for(&self.facade.authz())) {
1381            Ok(cfg) => ok_json(json!({"ok": true, "config": cfg})),
1382            Err(e) => ok_json(json!({"ok": false, "error": e.to_string(), "code": e.code()})),
1383        }
1384    }
1385}
1386
1387impl UiServer {
1388    /// Declare or clear a per-namespace anonymization policy from the
1389    /// console (Connect → Settings). Rides the same write gate as every
1390    /// console POST (auth + Origin + body cap upstream); the policy itself
1391    /// validates fail-closed in the store.
1392    fn anon_config(&self, body: &[u8]) -> (&'static str, &'static str, Vec<u8>) {
1393        let v: Value = match serde_json::from_slice(body) {
1394            Ok(v) => v,
1395            Err(e) => return ok_json(json!({"ok": false, "error": e.to_string()})),
1396        };
1397        let Some(ns) = v.get("ns").and_then(Value::as_str).filter(|n| !n.trim().is_empty())
1398        else {
1399            return ok_json(json!({"ok": false, "error": "ns is required"}));
1400        };
1401        let result = if v.get("clear").and_then(Value::as_bool) == Some(true) {
1402            self.facade.with_store(|m| m.clear_anon_policy(ns))
1403        } else {
1404            match v.get("policy") {
1405                Some(policy) => {
1406                    let policy_json = policy.to_string();
1407                    self.facade.with_store(|m| m.set_anon_policy(ns, &policy_json))
1408                }
1409                None => {
1410                    return ok_json(json!({"ok": false, "error": "policy (object) or clear: true is required"}));
1411                }
1412            }
1413        };
1414        match result {
1415            Ok(()) => {
1416                let declared = self.facade.with_store(|m| m.anon_declared());
1417                ok_json(json!({"ok": true, "policies": declared
1418                    .iter()
1419                    .map(|(ns, mode)| json!({"ns": ns, "mode": mode}))
1420                    .collect::<Vec<_>>()}))
1421            }
1422            Err(e) => ok_json(json!({"ok": false, "error": e.to_string()})),
1423        }
1424    }
1425}
1426
1427/// True when a `host[:port]` (or `[ipv6]:port`) authority names a loopback
1428/// host. Shared by the Origin drive-by check and the Host-header
1429/// (DNS-rebinding) check.
1430fn host_is_local(host_port: &str) -> bool {
1431    let host = if let Some(h) = host_port.strip_prefix('[') {
1432        h.split(']').next().unwrap_or("")
1433    } else {
1434        host_port.split(':').next().unwrap_or("")
1435    };
1436    matches!(host, "127.0.0.1" | "localhost" | "::1")
1437}
1438
1439/// True when an Origin header names a loopback host (any port, http/https).
1440fn origin_is_local(origin: &str) -> bool {
1441    let rest = origin
1442        .strip_prefix("http://")
1443        .or_else(|| origin.strip_prefix("https://"));
1444    let Some(rest) = rest else { return false };
1445    let host_port = rest.split('/').next().unwrap_or("");
1446    host_is_local(host_port)
1447}
1448
1449fn now_label() -> String {
1450    format!("{}", std::time::SystemTime::now()
1451        .duration_since(std::time::UNIX_EPOCH)
1452        .map(|d| d.as_millis())
1453        .unwrap_or(0))
1454}
1455
1456fn ok_json(v: Value) -> (&'static str, &'static str, Vec<u8>) {
1457    ("200 OK", "application/json", v.to_string().into_bytes())
1458}
1459
1460fn run_api_err(msg: &str) -> (&'static str, &'static str, Vec<u8>) {
1461    (
1462        "400 Bad Request",
1463        "application/json",
1464        serde_json::json!({"ok": false, "error": msg}).to_string().into_bytes(),
1465    )
1466}
1467
1468/// True when a `POST /api/cal` body is a read-only statement. Classification
1469/// is delegated to `areev-cal`'s exhaustive [`areev_cal::classify`] module —
1470/// the single source of truth — so grammar growth cannot desynchronize this
1471/// gate (a keyword sniff lived here before and would have silently
1472/// misclassified any new statement). Fail closed: unparseable text is not
1473/// read-only.
1474fn cal_body_is_read_only(body: &[u8]) -> bool {
1475    let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1476    let q = req.get("query").and_then(Value::as_str).unwrap_or("");
1477    areev_cal::classify::query_is_read_only(q)
1478}
1479
1480fn status_from_str(s: &str) -> Option<RecStatus> {
1481    match s {
1482        "pending" => Some(RecStatus::Pending),
1483        "approved" => Some(RecStatus::Approved),
1484        "rejected" => Some(RecStatus::Rejected),
1485        "applied" => Some(RecStatus::Applied),
1486        "rolled_back" => Some(RecStatus::RolledBack),
1487        "expired" => Some(RecStatus::Expired),
1488        _ => None, // includes "all"
1489    }
1490}
1491
1492fn rec_json(r: &areev_loop::Recommendation) -> Value {
1493    json!({
1494        "hash": r.hash,
1495        "status": r.status.as_str(),
1496        "severity": r.severity.as_str(),
1497        "analyzer": r.analyzer,
1498        "summary": r.summary.render(),
1499        "target_ref": r.target_ref,
1500        "destructive": r.destructive,
1501        "rollbackable": r.rollbackable,
1502        "evidence": r.evidence,
1503    })
1504}
1505
1506fn urldecode(s: &str) -> String {
1507    let mut out = Vec::new();
1508    let b = s.as_bytes();
1509    let mut i = 0;
1510    while i < b.len() {
1511        match b[i] {
1512            b'%' if i + 2 < b.len() + 1 && i + 2 < b.len() + 1 => {
1513                if i + 2 < b.len() + 1 && i + 2 < b.len() {
1514                    let hex = std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or("");
1515                    if let Ok(v) = u8::from_str_radix(hex, 16) {
1516                        out.push(v);
1517                        i += 3;
1518                        continue;
1519                    }
1520                }
1521                out.push(b[i]);
1522                i += 1;
1523            }
1524            b'+' => {
1525                out.push(b' ');
1526                i += 1;
1527            }
1528            c => {
1529                out.push(c);
1530                i += 1;
1531            }
1532        }
1533    }
1534    String::from_utf8_lossy(&out).to_string()
1535}
1536
1537fn html_escape(s: &str) -> String {
1538    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
1539}
1540
1541/// Constant-time byte comparison — avoids leaking the bearer token through
1542/// response timing. A length mismatch fails fast (token length is not secret).
1543fn ct_eq(a: &[u8], b: &[u8]) -> bool {
1544    if a.len() != b.len() {
1545        return false;
1546    }
1547    let mut diff = 0u8;
1548    for (x, y) in a.iter().zip(b.iter()) {
1549        diff |= x ^ y;
1550    }
1551    diff == 0
1552}
1553
1554/// Decode standard base64 (RFC 4648), enough for HTTP Basic credentials.
1555/// Hand-rolled to keep the server dependency-free. Returns `None` on any
1556/// invalid character or truncated input.
1557fn base64_decode(s: &str) -> Option<Vec<u8>> {
1558    fn val(c: u8) -> Option<u32> {
1559        match c {
1560            b'A'..=b'Z' => Some((c - b'A') as u32),
1561            b'a'..=b'z' => Some((c - b'a' + 26) as u32),
1562            b'0'..=b'9' => Some((c - b'0' + 52) as u32),
1563            b'+' => Some(62),
1564            b'/' => Some(63),
1565            _ => None,
1566        }
1567    }
1568    let s = s.trim().trim_end_matches('=');
1569    let mut out = Vec::with_capacity(s.len() * 3 / 4);
1570    let (mut acc, mut bits) = (0u32, 0u32);
1571    for &c in s.as_bytes() {
1572        acc = (acc << 6) | val(c)?;
1573        bits += 6;
1574        if bits >= 8 {
1575            bits -= 8;
1576            out.push((acc >> bits) as u8);
1577        }
1578    }
1579    Some(out)
1580}
1581
1582/// Extract the password from an HTTP Basic credential (`base64("user:pass")`).
1583/// The console ignores the username and treats the password as the token.
1584/// Returns `None` if the value is not valid base64/UTF-8 or has no `:`.
1585fn basic_auth_password(b64: &str) -> Option<String> {
1586    let text = String::from_utf8(base64_decode(b64)?).ok()?;
1587    text.split_once(':').map(|(_user, pass)| pass.to_string())
1588}
1589
1590/// Sanitize a client-supplied segment name into a single safe filename.
1591/// Strips anything outside `[A-Za-z0-9-._]`, then requires the result to be
1592/// exactly one normal path component — rejecting empty names, `.`/`..`, and
1593/// path separators so a push/pull cannot escape the segment directory.
1594fn safe_segment_name(name: &str) -> Option<String> {
1595    let safe: String = name
1596        .chars()
1597        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_'))
1598        .collect();
1599    if safe.is_empty() || safe.len() > 128 {
1600        return None;
1601    }
1602    let mut comps = std::path::Path::new(&safe).components();
1603    match (comps.next(), comps.next()) {
1604        (Some(std::path::Component::Normal(c)), None) if c.to_str() == Some(safe.as_str()) => {
1605            Some(safe)
1606        }
1607        _ => None,
1608    }
1609}
1610
1611#[cfg(test)]
1612mod loop_route_tests {
1613    use super::UiServer;
1614    use areev_cal::AreevFacade;
1615    use areev_core::types::{Fact, Grain};
1616    use areev_store::Areev;
1617
1618    fn server(auth: Option<&str>) -> UiServer {
1619        let dir = tempfile::tempdir().unwrap();
1620        let path = dir.path().join("t.db");
1621        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
1622        // Two identical facts → a duplicate-consolidation recommendation.
1623        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller")).unwrap();
1624        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller")).unwrap();
1625        std::mem::forget(dir); // keep the file alive for the server's lifetime
1626        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
1627        let s = UiServer::new(facade, "test".into());
1628        match auth {
1629            Some(t) => s.with_auth(t.to_string()),
1630            None => s,
1631        }
1632    }
1633
1634    fn text(r: &(&str, &str, Vec<u8>)) -> String {
1635        String::from_utf8_lossy(&r.2).to_string()
1636    }
1637
1638    #[test]
1639    fn token_less_console_is_read_only() {
1640        let s = server(None);
1641        // A loop mutation (run) is a write → 401.
1642        assert!(s.route("POST", "/api/loop/run", b"{}", None, None).0.starts_with("401"));
1643        // A write CAL → 401.
1644        let w = s.route("POST", "/api/cal", br#"{"query":"ADD fact SET subject=\"x\""}"#, None, None);
1645        assert!(w.0.starts_with("401"), "write CAL must be 401: {}", text(&w));
1646        // A read CAL → 200.
1647        let r = s.route("POST", "/api/cal", br#"{"query":"RECALL facts WHERE subject = \"acme\""}"#, None, None);
1648        assert!(r.0.starts_with("200"), "read CAL allowed: {}", text(&r));
1649        // Areev Loop reads stay open token-less.
1650        assert!(s.route("GET", "/api/loop/recommendations", b"", None, None).0.starts_with("200"));
1651    }
1652
1653    #[test]
1654    fn telemetry_endpoint_is_an_open_read() {
1655        let s = server(None);
1656        let r = s.route("GET", "/api/loop/telemetry", b"", None, None);
1657        assert!(r.0.starts_with("200"), "telemetry read open: {}", text(&r));
1658        let body = text(&r);
1659        assert!(body.contains("\"ok\":true"), "{body}");
1660        // The test store opens bare (telemetry off) → enabled:false.
1661        assert!(body.contains("\"enabled\":false"), "{body}");
1662    }
1663
1664    #[test]
1665    fn authenticated_run_review_apply_roundtrip() {
1666        let s = server(Some("tok"));
1667        let run = s.route("POST", "/api/loop/run", b"{}", Some("tok"), None);
1668        assert!(run.0.starts_with("200"), "run: {}", text(&run));
1669        assert!(text(&run).contains("\"ran\""));
1670
1671        let list = s.route("GET", "/api/loop/recommendations?status=pending", b"", Some("tok"), None);
1672        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
1673        let recs = v["recommendations"].as_array().unwrap();
1674        assert!(!recs.is_empty(), "at least one recommendation");
1675        let hash = recs[0]["hash"].as_str().unwrap().to_string();
1676
1677        let rev = s.route(
1678            "POST",
1679            "/api/loop/review",
1680            format!(r#"{{"hash":"{hash}","decision":"approve","because":"ok"}}"#).as_bytes(),
1681            Some("tok"),
1682            None,
1683        );
1684        assert!(text(&rev).contains("\"ok\":true"), "review: {}", text(&rev));
1685
1686        let ap = s.route(
1687            "POST",
1688            "/api/loop/apply",
1689            format!(r#"{{"hash":"{hash}","because":"go"}}"#).as_bytes(),
1690            Some("tok"),
1691            None,
1692        );
1693        assert!(text(&ap).contains("\"ok\":true"), "apply: {}", text(&ap));
1694    }
1695
1696    #[test]
1697    fn config_edit_toggles_analyzer_via_console() {
1698        let s = server(Some("tok"));
1699        // Token-less write → 401 (guarded like every POST).
1700        assert!(s.route("POST", "/api/loop/config", b"{}", None, None).0.starts_with("401"));
1701
1702        // Read the analyzers; pick one that is on by default.
1703        let list = s.route("GET", "/api/loop/analyzers", b"", Some("tok"), None);
1704        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
1705        let id = v["analyzers"]
1706            .as_array()
1707            .unwrap()
1708            .iter()
1709            .find(|x| x["enabled"] == true)
1710            .expect("some analyzer is on")["id"]
1711            .as_str()
1712            .unwrap()
1713            .to_string();
1714
1715        // Disable it via the console endpoint.
1716        let post = s.route(
1717            "POST",
1718            "/api/loop/config",
1719            format!(r#"{{"analyzer_id":"{id}","enabled":false}}"#).as_bytes(),
1720            Some("tok"),
1721            None,
1722        );
1723        assert!(text(&post).contains("\"ok\":true"), "config: {}", text(&post));
1724
1725        // It reads back disabled.
1726        let list2 = s.route("GET", "/api/loop/analyzers", b"", Some("tok"), None);
1727        let v2: serde_json::Value = serde_json::from_slice(&list2.2).unwrap();
1728        let now = v2["analyzers"]
1729            .as_array()
1730            .unwrap()
1731            .iter()
1732            .find(|x| x["id"] == id.as_str())
1733            .unwrap();
1734        assert_eq!(now["enabled"], false, "toggled off and persisted");
1735    }
1736
1737    #[test]
1738    fn self_approval_surfaces_lop_code() {
1739        let s = server(Some("tok"));
1740        s.route("POST", "/api/loop/run", b"{}", Some("tok"), None);
1741        let list = s.route("GET", "/api/loop/recommendations?status=pending", b"", Some("tok"), None);
1742        let v: serde_json::Value = serde_json::from_slice(&list.2).unwrap();
1743        let rec = &v["recommendations"].as_array().unwrap()[0];
1744        let hash = rec["hash"].as_str().unwrap();
1745        let analyzer = rec["analyzer"].as_str().unwrap();
1746        let creator = format!("engine:{analyzer}");
1747        // The engine actor approving its own proposal is blocked.
1748        let rev = s.route(
1749            "POST",
1750            "/api/loop/review",
1751            format!(r#"{{"hash":"{hash}","decision":"approve","because":"self","actor":"{creator}"}}"#).as_bytes(),
1752            Some("tok"),
1753            None,
1754        );
1755        assert!(text(&rev).contains("LOP-E021"), "self-approval blocked: {}", text(&rev));
1756    }
1757}
1758
1759#[cfg(test)]
1760mod security_tests {
1761    use super::{base64_decode, basic_auth_password, ct_eq, safe_segment_name};
1762
1763    #[test]
1764    fn ct_eq_matches_only_equal() {
1765        assert!(ct_eq(b"secret-token", b"secret-token"));
1766        assert!(!ct_eq(b"secret-token", b"secret-toker"));
1767        assert!(!ct_eq(b"secret", b"secret-token")); // length mismatch
1768        assert!(ct_eq(b"", b""));
1769    }
1770
1771    #[test]
1772    fn base64_decode_roundtrips_known_vectors() {
1773        // RFC 4648 test vectors (with and without padding).
1774        assert_eq!(base64_decode("").unwrap(), b"");
1775        assert_eq!(base64_decode("Zg==").unwrap(), b"f");
1776        assert_eq!(base64_decode("Zm8=").unwrap(), b"fo");
1777        assert_eq!(base64_decode("Zm9v").unwrap(), b"foo");
1778        assert_eq!(base64_decode("Zm9vYmFy").unwrap(), b"foobar");
1779        // padding is optional for us
1780        assert_eq!(base64_decode("Zg").unwrap(), b"f");
1781        // invalid characters are rejected
1782        assert!(base64_decode("****").is_none());
1783    }
1784
1785    #[test]
1786    fn basic_auth_extracts_password_ignoring_username() {
1787        // base64("areev:s3cret") and base64(":s3cret") both yield the token.
1788        assert_eq!(basic_auth_password("ZGVqYTpzM2NyZXQ=").as_deref(), Some("s3cret"));
1789        assert_eq!(basic_auth_password("OnMzY3JldA==").as_deref(), Some("s3cret"));
1790        // a password may itself contain ':' — only the first ':' splits.
1791        // base64("u:a:b") -> "a:b"
1792        assert_eq!(basic_auth_password("dTphOmI=").as_deref(), Some("a:b"));
1793        // no ':' at all → not a valid Basic credential
1794        assert_eq!(basic_auth_password("bm9jb2xvbg=="), None); // "nocolon"
1795        assert_eq!(basic_auth_password("****"), None); // not base64
1796    }
1797
1798    #[test]
1799    fn safe_segment_name_blocks_traversal() {
1800        assert_eq!(safe_segment_name("push-123.mgb").as_deref(), Some("push-123.mgb"));
1801        assert_eq!(safe_segment_name(".."), None);
1802        assert_eq!(safe_segment_name("."), None);
1803        assert_eq!(safe_segment_name(""), None);
1804        // Separators are stripped, so any accepted name is a single component
1805        // that cannot escape the segment directory.
1806        for probe in ["../../etc/passwd", "/etc/passwd", "a/../b", "foo/bar"] {
1807            if let Some(s) = safe_segment_name(probe) {
1808                assert!(!s.contains('/') && s != ".." && s != ".", "unsafe: {s}");
1809            }
1810        }
1811    }
1812}
1813
1814#[cfg(test)]
1815mod credential_route_tests {
1816    use super::UiServer;
1817    use areev_cal::AreevFacade;
1818    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
1819    use areev_core::types::{Fact, Grain};
1820    use areev_store::Areev;
1821
1822    /// A server in credential-map mode: two env-referenced tokens, rights
1823    /// seeded as grant grains in the file itself.
1824    fn server() -> UiServer {
1825        std::env::set_var("AREEV_TEST_READER_TOK", "reader-secret");
1826        std::env::set_var("AREEV_TEST_WRITER_TOK", "writer-secret");
1827        let dir = tempfile::tempdir().unwrap();
1828        let path = dir.path().join("t.db");
1829        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
1830        store
1831            .add(&Fact::new("user:reader", REL_PERMITS, "read ON *").namespace(AUTHZ_NS).created_at(1_000))
1832            .unwrap();
1833        store
1834            .add(
1835                &Fact::new("agent:writer", REL_PERMITS, "read,write ON caller")
1836                    .namespace(AUTHZ_NS)
1837                    .created_at(2_000),
1838            )
1839            .unwrap();
1840        store.add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(3_000)).unwrap();
1841        std::mem::forget(dir);
1842        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
1843        let map = CredentialMap::from_json(
1844            r#"{"version":1,"tokens":[
1845                {"env":"AREEV_TEST_READER_TOK","principal":"user:reader"},
1846                {"env":"AREEV_TEST_WRITER_TOK","principal":"agent:writer"}
1847            ]}"#,
1848        )
1849        .unwrap();
1850        UiServer::new(facade, "test".into()).with_credentials(map)
1851    }
1852
1853    fn text(r: &(&str, &str, Vec<u8>)) -> String {
1854        String::from_utf8_lossy(&r.2).to_string()
1855    }
1856
1857    const READ: &[u8] = br#"{"query":"RECALL facts WHERE subject = \"acme\""}"#;
1858    const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
1859
1860    #[test]
1861    fn tokens_bind_principals_and_verbs_decide() {
1862        let s = server();
1863
1864        // The reader reads…
1865        let r = s.route("POST", "/api/cal", READ, Some("reader-secret"), None);
1866        assert!(r.0.starts_with("200"), "{}", text(&r));
1867        assert!(text(&r).contains("grains"));
1868        // …and cannot write.
1869        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
1870        assert!(text(&w).contains("AUT-E001"), "reader write must be refused: {}", text(&w));
1871
1872        // The writer writes.
1873        let w = s.route("POST", "/api/cal", WRITE, Some("writer-secret"), None);
1874        assert!(text(&w).contains("added"), "writer write must land: {}", text(&w));
1875
1876        // Sequential isolation: the very next reader request is still
1877        // read-only — nothing leaked from the writer's binding.
1878        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
1879        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
1880    }
1881
1882    #[test]
1883    fn anonymous_is_read_only_and_loop_run_is_verb_gated() {
1884        let s = server();
1885        // No token → anonymous: reads work…
1886        let r = s.route("POST", "/api/cal", READ, None, None);
1887        assert!(r.0.starts_with("200"), "{}", text(&r));
1888        assert!(text(&r).contains("grains"));
1889        // …writes are verb-refused…
1890        let w = s.route("POST", "/api/cal", WRITE, None, None);
1891        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
1892        // …and an unknown token is anonymous too, never an escalation.
1893        let w = s.route("POST", "/api/cal", WRITE, Some("stolen-guess"), None);
1894        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
1895
1896        // The analysis trigger needs loop.run — anonymous gets 403.
1897        let run = s.route("POST", "/api/loop/run", b"{}", None, None);
1898        assert!(run.0.starts_with("403"), "{}", text(&run));
1899    }
1900
1901    #[test]
1902    fn whoami_reports_the_bound_principal() {
1903        let s = server();
1904        let r = s.route("GET", "/api/whoami", b"", Some("reader-secret"), None);
1905        assert!(text(&r).contains("user:reader"), "{}", text(&r));
1906        assert!(text(&r).contains("credentials"));
1907        let r = s.route("GET", "/api/whoami", b"", None, None);
1908        assert!(text(&r).contains("anonymous"), "{}", text(&r));
1909    }
1910
1911    /// A credential map must not silently disable `--token-env`. Attaching
1912    /// one changes WHO a request is; the operator who also asked for a
1913    /// shared secret still gets authentication on every request.
1914    #[test]
1915    fn a_credential_map_does_not_disable_the_shared_secret() {
1916        let s = server().with_auth("console-token".into());
1917
1918        // No credential at all: refused, not dropped to `anonymous`.
1919        let r = s.route("POST", "/api/cal", READ, None, None);
1920        assert!(r.0.starts_with("401"), "{}", text(&r));
1921        let page = s.route("GET", "/", b"", None, None);
1922        assert!(page.0.starts_with("401"), "the console page is guarded too");
1923        // An unrecognized token is refused rather than downgraded.
1924        let r = s.route("POST", "/api/cal", READ, Some("stolen-guess"), None);
1925        assert!(r.0.starts_with("401"), "{}", text(&r));
1926
1927        // A map token still binds its principal and its verbs still decide.
1928        let r = s.route("POST", "/api/cal", READ, Some("reader-secret"), None);
1929        assert!(r.0.starts_with("200"), "{}", text(&r));
1930        let w = s.route("POST", "/api/cal", WRITE, Some("reader-secret"), None);
1931        assert!(text(&w).contains("AUT-E001"), "{}", text(&w));
1932
1933        // The shared secret is the implied admin (docs/cal-all-you-need
1934        // -proposal.md §5.2b) — it keeps the owner session it always had.
1935        let w = s.route("POST", "/api/cal", WRITE, Some("console-token"), None);
1936        assert!(text(&w).contains("added"), "{}", text(&w));
1937    }
1938
1939    /// `RUN LOOP` through CAL is gated exactly as `POST /api/loop/run` is —
1940    /// otherwise the CAL surface is a way around the HTTP gate.
1941    #[test]
1942    fn run_loop_via_cal_is_verb_gated_like_the_route() {
1943        let s = server();
1944        let run = s.route("POST", "/api/loop/run", b"{}", None, None);
1945        assert!(run.0.starts_with("403"), "{}", text(&run));
1946        let cal = s.route("POST", "/api/cal", br#"{"query":"RUN LOOP"}"#, None, None);
1947        assert!(
1948            text(&cal).contains("AUT-E001"),
1949            "anonymous must not run the loop through CAL either: {}",
1950            text(&cal)
1951        );
1952    }
1953}
1954
1955#[cfg(test)]
1956mod builder_tests {
1957    use super::UiServer;
1958    use areev_cal::AreevFacade;
1959    use areev_store::Areev;
1960
1961    fn server() -> UiServer {
1962        let dir = tempfile::tempdir().unwrap();
1963        let path = dir.path().join("t.db");
1964        let store = Areev::open(path.to_str().unwrap()).unwrap();
1965        std::mem::forget(dir);
1966        UiServer::new(AreevFacade::with_session(store, Some("caller".into()), None), "t".into())
1967    }
1968
1969    /// `areev ui --no-destructive-ops --policy FILE` calls these in this
1970    /// order. A later builder must not re-enable destruction the operator
1971    /// turned off — the console was announced as read-only.
1972    #[test]
1973    fn attaching_a_loop_policy_preserves_the_destructive_cap() {
1974        let s = server()
1975            .allow_destructive_ops(false)
1976            .with_loop_policy(areev_loop::Policy::default());
1977        let r = s.route(
1978            "POST",
1979            "/api/cal",
1980            br#"{"query":"FORGET sha256:684c6c9bda818630a870119d0726e4d242ed537af061658ef6f3acb158a2c67d"}"#,
1981            None,
1982            None,
1983        );
1984        let body = String::from_utf8_lossy(&r.2).to_string();
1985        assert!(
1986            body.contains("--no-destructive-ops") || r.0.starts_with("401"),
1987            "destruction must stay disabled: {body}"
1988        );
1989    }
1990}
1991
1992#[cfg(test)]
1993mod run_api_tests {
1994    use super::UiServer;
1995    use areev_cal::AreevFacade;
1996    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
1997    use areev_core::types::{Fact, Grain, Tool, ToolKind, Workflow};
1998    use areev_store::Areev;
1999    use std::sync::Arc;
2000
2001    /// A server whose file holds a PARKED run (Client-gated approve node) —
2002    /// the HITL queue's fixture. Returns (server, ask id).
2003    fn parked_server() -> (UiServer, String) {
2004        std::env::set_var("AREEV_RUN_OFFICER_TOK", "officer-secret");
2005        std::env::set_var("AREEV_RUN_STARTER_TOK", "starter-secret");
2006        let dir = tempfile::tempdir().unwrap();
2007        let path = dir.path().join("t.db");
2008        let mut store = Areev::open(path.to_str().unwrap()).unwrap();
2009        for (who, what) in [
2010            ("user:officer", "read,run.respond ON ops"),
2011            ("user:starter", "read ON ops"),
2012        ] {
2013            store
2014                .add(&Fact::new(who, REL_PERMITS, what).namespace(AUTHZ_NS).created_at(900))
2015                .unwrap();
2016        }
2017        std::mem::forget(dir);
2018        let facade = Arc::new(AreevFacade::with_session(store, Some("ops".into()), None));
2019
2020        // Seed + run the plan to the park with a scripted runner.
2021        let (wf, _g, _a) = facade
2022            .with_store(|m| {
2023                let greet = Tool::new("greet")
2024                    .kind(ToolKind::Definition)
2025                    .tool_description("t")
2026                    .created_at(500)
2027                    .namespace("ops");
2028                let gh = m.add(&greet)?;
2029                let approve = Tool::new("approve")
2030                    .kind(ToolKind::Definition)
2031                    .tool_description("human approves")
2032                    .executor_kind(areev_core::types::ExecutorKind::Client)
2033                    .created_at(501)
2034                    .namespace("ops");
2035                let ah = m.add(&approve)?;
2036                let wf = Workflow::new(vec!["greet".into(), "approve".into()])
2037                    .edge("greet", "approve")
2038                    .bind("greet", &gh.to_hex())
2039                    .bind("approve", &ah.to_hex())
2040                    .created_at(502)
2041                    .namespace("ops");
2042                let wh = m.add(&wf)?;
2043                Ok::<_, areev_core::error::AreevError>((wh, gh, ah))
2044            })
2045            .unwrap();
2046        struct Ok1;
2047        impl areev_run::HostToolExecutor for Ok1 {
2048            fn execute(
2049                &self,
2050                t: &str,
2051                _h: &str,
2052                _i: &serde_json::Value,
2053                _k: &str,
2054            ) -> areev_run::ExecResult {
2055                areev_run::ExecResult::Ok(serde_json::json!({t.to_string(): true}))
2056            }
2057        }
2058        let runner = areev_run::Runner {
2059            facade: Arc::clone(&facade),
2060            clock: Arc::new(areev_run::ScriptedClock::new(
2061                (0..100).map(|i| 1_758_000_000_000 + i * 10).collect(),
2062            )),
2063            executor: Arc::new(Ok1),
2064            llm: None,
2065            observer: None,
2066            ns: "ops".into(),
2067            principal: "user:starter".into(),
2068        };
2069        let session = runner
2070            .start(&wf, "hitl-1", serde_json::json!({}), &areev_run::RunOptions {
2071                workers: 1,
2072                ..Default::default()
2073            })
2074            .unwrap();
2075        let areev_run::RunSession::Parked { envelope, .. } = session else {
2076            panic!("expected park")
2077        };
2078        let ask = envelope["asks"][0]["tool_call_id"].as_str().unwrap().to_string();
2079
2080        // Rebuild a facade-owning server over the SAME file is impossible
2081        // (single writer) — hand the server the same Arc'd facade via the
2082        // Arc-aware constructor path: UiServer::new takes AreevFacade, so
2083        // we build the server FIRST in real deployments; here we reuse the
2084        // internal Arc through a second UiServer field write. Instead:
2085        // drop the runner (facade Arc count drops) and unwrap.
2086        drop(runner);
2087        let facade = Arc::try_unwrap(facade).unwrap_or_else(|_| panic!("facade still shared"));
2088        let map = CredentialMap::from_json(
2089            r#"{"version":1,"tokens":[
2090                {"env":"AREEV_RUN_OFFICER_TOK","principal":"user:officer"},
2091                {"env":"AREEV_RUN_STARTER_TOK","principal":"user:starter"}
2092            ]}"#,
2093        )
2094        .unwrap();
2095        let server = UiServer::new(facade, "test".into())
2096            .with_auth("shared-console-secret".into())
2097            .with_credentials(map);
2098        (server, ask)
2099    }
2100
2101    fn body(run_id: &str, ask: &str) -> Vec<u8> {
2102        serde_json::json!({"run_id": run_id, "tool_call_id": ask, "result": {"approved": true}})
2103            .to_string()
2104            .into_bytes()
2105    }
2106
2107    #[test]
2108    fn shared_token_approvals_are_refused_and_principals_approve() {
2109        let (s, ask) = parked_server();
2110
2111        // The HITL queue is visible.
2112        let r = s.route("GET", "/api/run/list", b"", Some("shared-console-secret"), None);
2113        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
2114        let r = s.route(
2115            "GET",
2116            "/api/run/inspect?run_id=hitl-1",
2117            b"",
2118            Some("shared-console-secret"),
2119            None,
2120        );
2121        assert!(String::from_utf8_lossy(&r.2).contains(&ask), "ask visible in inspect");
2122
2123        // 1. The SHARED console secret cannot approve — identity is the point.
2124        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("shared-console-secret"), None);
2125        assert!(r.0.starts_with("403"), "shared-token approval must refuse: {}", r.0);
2126
2127        // 2. The STARTER's own credential cannot approve their own run
2128        //    (separation of duties, enforced by the runtime).
2129        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("starter-secret"), None);
2130        let text = String::from_utf8_lossy(&r.2).to_string();
2131        assert!(text.contains("responder") || text.contains("RUN-E012"), "{text}");
2132
2133        // 3. The officer's principal-bound credential approves.
2134        let r = s.route("POST", "/api/run/respond", &body("hitl-1", &ask), Some("officer-secret"), None);
2135        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
2136        assert!(String::from_utf8_lossy(&r.2).contains("user:officer"));
2137
2138        // 4. The kill switch keeps its low bar: shared token may cancel.
2139        let r = s.route(
2140            "POST",
2141            "/api/run/cancel",
2142            br#"{"run_id":"hitl-1","because":"test brake"}"#,
2143            Some("shared-console-secret"),
2144            None,
2145        );
2146        assert!(r.0.starts_with("200"), "{}", String::from_utf8_lossy(&r.2));
2147    }
2148}
2149
2150#[cfg(test)]
2151mod memory_scoped_token_tests {
2152    use super::UiServer;
2153    use areev_cal::AreevFacade;
2154    use areev_core::authz::{CredentialMap, AUTHZ_NS, REL_PERMITS};
2155    use areev_core::types::{Fact, Grain};
2156    use areev_store::Areev;
2157
2158    /// The enterprise-plane hub rule: one auth file, per-memory token
2159    /// scopes — a token listed for memory A is an UNKNOWN token on
2160    /// memory B's server.
2161    #[test]
2162    fn memory_scoped_tokens_do_not_cross_memories() {
2163        std::env::set_var("AREEV_SCOPED_TOK", "scoped-secret");
2164        let map_json = r#"{"version":1,"tokens":[
2165            {"env":"AREEV_SCOPED_TOK","principal":"agent:sync","memories":["memory-a"]}
2166        ]}"#;
2167        let server_for = |label: &str| {
2168            let dir = tempfile::tempdir().unwrap();
2169            let mut store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
2170            store
2171                .add(
2172                    &Fact::new("agent:sync", REL_PERMITS, "read,write ON caller")
2173                        .namespace(AUTHZ_NS)
2174                        .created_at(1_000),
2175                )
2176                .unwrap();
2177            store
2178                .add(&Fact::new("acme", "tier", "Enterprise").namespace("caller").created_at(2_000))
2179                .unwrap();
2180            std::mem::forget(dir);
2181            let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2182            UiServer::new(facade, label.into())
2183                .with_credentials(CredentialMap::from_json(map_json).unwrap())
2184        };
2185        const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
2186
2187        // On memory-a the token authenticates and its grants let the write
2188        // through (no authorization refusal in the CAL payload).
2189        let a = server_for("memory-a");
2190        let r = a.route("POST", "/api/cal", WRITE, Some("scoped-secret"), None);
2191        let text = String::from_utf8_lossy(&r.2).to_string();
2192        assert!(r.0.starts_with("200") && !text.contains("AUT-E001"), "{text}");
2193
2194        // On memory-b the SAME token is an unknown credential: the request
2195        // runs as anonymous and the write is refused (AUT-E001 rides the
2196        // CAL payload — the console surfaces statement results in-band).
2197        let b = server_for("memory-b");
2198        let r = b.route("POST", "/api/cal", WRITE, Some("scoped-secret"), None);
2199        let text = String::from_utf8_lossy(&r.2).to_string();
2200        assert!(
2201            text.contains("AUT-E001") && text.contains("anonymous"),
2202            "scoped token must not cross memories: {text}"
2203        );
2204
2205        // An auth file with an EMPTY memories scope refuses to load.
2206        assert!(CredentialMap::from_json(
2207            r#"{"version":1,"tokens":[{"env":"AREEV_SCOPED_TOK","principal":"x","memories":[]}]}"#
2208        )
2209        .is_err());
2210    }
2211}
2212
2213#[cfg(all(test, feature = "tls"))]
2214mod tls_tests {
2215    use super::UiServer;
2216    use areev_cal::AreevFacade;
2217    use areev_store::Areev;
2218    use std::io::{Read, Write};
2219
2220    fn self_signed(dir: &std::path::Path) -> Option<(String, String)> {
2221        let cert = dir.join("cert.pem");
2222        let key = dir.join("key.pem");
2223        let status = std::process::Command::new("openssl")
2224            .args([
2225                "req", "-x509", "-newkey", "rsa:2048", "-nodes",
2226                "-keyout", key.to_str().unwrap(), "-out", cert.to_str().unwrap(),
2227                "-days", "1", "-subj", "/CN=localhost",
2228                "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1",
2229                "-addext", "basicConstraints=critical,CA:FALSE",
2230            ])
2231            .stdout(std::process::Stdio::null())
2232            .stderr(std::process::Stdio::null())
2233            .status();
2234        match status {
2235            Ok(s) if s.success() => Some((
2236                cert.to_str().unwrap().to_string(),
2237                key.to_str().unwrap().to_string(),
2238            )),
2239            _ => None, // no openssl on this host: the CI leg covers it
2240        }
2241    }
2242
2243    /// The §3.2 gate: a TLS round-trip succeeds, and a PLAINTEXT client on
2244    /// the same listener is refused (no silent downgrade).
2245    #[test]
2246    fn tls_round_trip_and_no_plaintext_downgrade() {
2247        let dir = tempfile::tempdir().unwrap();
2248        let Some((cert, key)) = self_signed(dir.path()) else {
2249            eprintln!("skipping: no openssl binary");
2250            return;
2251        };
2252        let store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
2253        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2254        let server = UiServer::new(facade, "tls-test".into())
2255            .with_tls(&cert, &key)
2256            .unwrap();
2257        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2258        let addr = listener.local_addr().unwrap();
2259        let handle = std::thread::spawn(move || {
2260            // Two connections: the TLS client, then the plaintext prober.
2261            for _ in 0..2 {
2262                if let Ok((s, _)) = listener.accept() {
2263                    let _ = server.handle(s);
2264                }
2265            }
2266        });
2267
2268        // 1. TLS round-trip: trust exactly our self-signed cert.
2269        let mut roots = rustls::RootCertStore::empty();
2270        {
2271            use rustls::pki_types::pem::PemObject;
2272            for c in rustls::pki_types::CertificateDer::pem_file_iter(&cert).unwrap() {
2273                roots.add(c.unwrap()).unwrap();
2274            }
2275        }
2276        let config = std::sync::Arc::new(
2277            rustls::ClientConfig::builder()
2278                .with_root_certificates(roots)
2279                .with_no_client_auth(),
2280        );
2281        let name = rustls::pki_types::ServerName::try_from("localhost").unwrap();
2282        let session = rustls::ClientConnection::new(config, name).unwrap();
2283        let tcp = std::net::TcpStream::connect(addr).unwrap();
2284        let mut tls = rustls::StreamOwned::new(session, tcp);
2285        tls.write_all(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")
2286            .unwrap();
2287        let mut response = String::new();
2288        let _ = tls.read_to_string(&mut response);
2289        assert!(response.starts_with("HTTP/1.1 200"), "{}", &response[..response.len().min(120)]);
2290        assert!(response.contains("Areev"), "console served over TLS");
2291
2292        // 2. No downgrade: plaintext HTTP on the TLS listener gets a
2293        // handshake failure, never a page.
2294        let mut plain = std::net::TcpStream::connect(addr).unwrap();
2295        plain
2296            .write_all(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")
2297            .unwrap();
2298        let mut buf = Vec::new();
2299        let _ = plain.read_to_end(&mut buf);
2300        let text = String::from_utf8_lossy(&buf);
2301        assert!(
2302            !text.contains("HTTP/1.1 200"),
2303            "plaintext must not be served on a TLS listener: {text}"
2304        );
2305        handle.join().unwrap();
2306    }
2307}
2308
2309#[cfg(test)]
2310mod sso_tests {
2311    use super::UiServer;
2312    use areev_cal::AreevFacade;
2313    use areev_core::authz::{AUTHZ_NS, REL_PERMITS};
2314    use areev_core::types::{Fact, Grain};
2315    use areev_store::Areev;
2316    use std::io::{Read, Write};
2317
2318    const WRITE: &[u8] = br#"{"query":"ADD fact SET subject = \"x\" SET relation = \"r\" SET object = \"o\" SET namespace = \"caller\" REASON \"t\""}"#;
2319
2320    fn sso_server() -> UiServer {
2321        let dir = tempfile::tempdir().unwrap();
2322        let mut store = Areev::open(dir.path().join("t.db").to_str().unwrap()).unwrap();
2323        store
2324            .add(
2325                &Fact::new("user:pat@example.com", REL_PERMITS, "read,write ON caller")
2326                    .namespace(AUTHZ_NS)
2327                    .created_at(1_000),
2328            )
2329            .unwrap();
2330        std::mem::forget(dir);
2331        let facade = AreevFacade::with_session(store, Some("caller".into()), None);
2332        UiServer::new(facade, "sso-test".into()).with_sso("x-forwarded-user", "proxy-secret")
2333    }
2334
2335    fn post(server: &UiServer, extra_headers: &str) -> String {
2336        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2337        let addr = listener.local_addr().unwrap();
2338        std::thread::scope(|scope| {
2339            scope.spawn(|| {
2340                if let Ok((s, _)) = listener.accept() {
2341                    let _ = server.handle(s);
2342                }
2343            });
2344            let mut c = std::net::TcpStream::connect(addr).unwrap();
2345            let req = format!(
2346                "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",
2347                WRITE.len()
2348            );
2349            c.write_all(req.as_bytes()).unwrap();
2350            c.write_all(WRITE).unwrap();
2351            let mut out = String::new();
2352            let _ = c.read_to_string(&mut out);
2353            out
2354        })
2355    }
2356
2357    /// The §3.3 gate: a proxy-proven identity lands as a named actor whose
2358    /// FILE grants decide; a forged identity header without the proxy
2359    /// secret is ignored (the write is refused as anonymous).
2360    #[test]
2361    fn proxied_identity_works_and_forged_headers_are_ignored() {
2362        let server = sso_server();
2363
2364        // 1. Proxy-proven: identity + secret → the granted principal writes.
2365        let ok = post(
2366            &server,
2367            "X-Forwarded-User: user:pat@example.com\r\nX-Areev-Proxy-Secret: proxy-secret\r\n",
2368        );
2369        assert!(ok.contains("HTTP/1.1 200"), "{}", &ok[..ok.len().min(200)]);
2370        assert!(!ok.contains("AUT-E001"), "granted principal must write: {ok}");
2371
2372        // 2. Forged: the identity header WITHOUT the secret is ignored — the
2373        // request is anonymous and the write refuses.
2374        let forged = post(&server, "X-Forwarded-User: user:pat@example.com\r\n");
2375        assert!(
2376            forged.contains("anonymous") || forged.contains("401"),
2377            "forged identity must not authenticate: {forged}"
2378        );
2379
2380        // 3. Wrong secret: same refusal (constant-time compare, same path).
2381        let wrong = post(
2382            &server,
2383            "X-Forwarded-User: user:pat@example.com\r\nX-Areev-Proxy-Secret: guess\r\n",
2384        );
2385        assert!(
2386            wrong.contains("anonymous") || wrong.contains("401"),
2387            "wrong proxy secret must not authenticate: {wrong}"
2388        );
2389    }
2390}