Skip to main content

trustee_api/
lib.rs

1//! Trustee API — REST + WebSocket server for the Trustee agent.
2//!
3//! Wraps a [`trustee_core::session::Session`] and exposes it over HTTP.
4//! Static frontend files are served from [`trustee_web`].
5//!
6//! Authentication is optional. When `[oidc]` or `[dev]` sections are present
7//! in the config TOML, all `/api/v1/*` endpoints require a valid JWT or dev
8//! token. Otherwise, all endpoints are open.
9
10pub mod auth;
11pub mod tls;
12mod routes;
13mod state;
14mod thq_dispatch;
15mod thq_register;
16pub mod xagent;
17
18/// The BIN's version, injected by the `trustee` binary at startup
19/// ([`set_bin_version`]) — the web UI's burger-menu footer displays it.
20/// Falls back to this crate's version when unset (trustee-api embedded
21/// elsewhere without a bin).
22static BIN_VERSION: std::sync::OnceLock<String> = std::sync::OnceLock::new();
23
24/// Called by the `trustee` binary so the web UI can show the real product
25/// version (the binary's — what `trustee --version` prints), not
26/// trustee-api's crate version. First call wins; a restart is a new process.
27pub fn set_bin_version(v: &str) {
28    let _ = BIN_VERSION.set(v.to_string());
29}
30
31/// The version label for the web UI: the bin's version if injected, else
32/// this crate's.
33pub fn bin_version() -> &'static str {
34    BIN_VERSION
35        .get()
36        .map(|s| s.as_str())
37        .unwrap_or(env!("CARGO_PKG_VERSION"))
38}
39
40// Embedded Cedar policy defaults (compiled into binary)
41const EMBEDDED_CEDAR_POLICY: &str = include_str!("../policies/trustee_default.cedar");
42const EMBEDDED_CEDAR_SCHEMA: &str = include_str!("../policies/trustee_schema.cedarschema");
43
44use std::net::SocketAddr;
45use std::sync::Arc;
46
47use anyhow::Result;
48use axum::routing::{get, post};
49use tower_http::cors::CorsLayer;
50
51pub use auth::{AuthConfig, AuthState};
52pub use state::ServerState;
53
54/// Run the API server.
55///
56/// Creates a `Session` with the given config, starts a background task to
57/// drain workflow messages and broadcast them to WebSocket clients, then
58/// serves the REST + WebSocket + static files on `addr`.
59///
60/// If `[oidc]` or `[dev]` sections are found in the config TOML, auth is
61/// enabled — all `/api/v1/*` endpoints (except health) require a valid token.
62///
63/// By default serves over HTTPS using a self-signed certificate from
64/// `~/.trustee/certs/`. If `use_tls` is false, serves plain HTTP.
65pub async fn run(
66    config_toml: String,
67    secrets: std::collections::HashMap<String, String>,
68    build_info: trustee_core::types::BuildInfo,
69    addr: SocketAddr,
70    use_tls: bool,
71) -> Result<()> {
72    // Parse auth config from TOML (returns None if no [oidc] or [dev] sections)
73    let auth_state = if let Some(cfg) = AuthConfig::from_toml(&config_toml) {
74        let is_dev = cfg.dev_config.local_dev_mode;
75        tracing::info!(
76            "Auth enabled: {} mode, issuer={}",
77            if is_dev { "development" } else { "production" },
78            cfg.issuer_url
79        );
80
81        // Parse Cedar authorization config (P2: fail-closed on init failure)
82        let cedar_boot = parse_cedar_config(&config_toml)
83            .await
84            .map_err(|e| anyhow::anyhow!("{e}"))?;
85        cedar_boot_decision(
86            true,
87            cedar_boot.authorizer.is_some(),
88            cedar_boot.allow_disabled,
89        )
90        .map_err(|e| anyhow::anyhow!("{e}"))?;
91
92        // 16F: teach auth about the service-account issuer candidates so
93        // agent tokens (minted on service vhosts) validate in check_auth.
94        let mut issuer_fallbacks = crate::state::service_issuers_from_config(&config_toml);
95        for si in crate::thq_dispatch::discover_service_issuers() {
96            if !issuer_fallbacks.contains(&si) {
97                issuer_fallbacks.push(si);
98            }
99        }
100        issuer_fallbacks.retain(|si| *si != cfg.issuer_url);
101        if !issuer_fallbacks.is_empty() {
102            tracing::info!("Auth issuer fallbacks armed: {:?}", issuer_fallbacks);
103        }
104        Some(Arc::new(
105            AuthState::with_cedar(cfg, cedar_boot.authorizer)
106                .with_issuer_fallbacks(issuer_fallbacks),
107        ))
108    } else {
109        // Open mode — loud, by design (local/dev posture preserved).
110        tracing::warn!("AUTH NOT CONFIGURED: trustee-web is running WITHOUT authentication or Cedar authorization (no [oidc]/[dev] section). Never expose this to a network.");
111        None
112    };
113
114    // THQ enrollment (v0.3 runtime lane): parse before config_toml is
115    // moved into the session. No [thq] = lane off; malformed = LOUD +
116    // lane off (never a silent skip; no compat translation of old keys).
117    let thq_enrollment = match thq_register::ThqConfig::from_toml(&config_toml) {
118        Ok(None) => None,
119        Err(e) => {
120            tracing::error!("THQ enrollment DISABLED — [thq] is malformed: {e}");
121            None
122        }
123        Ok(Some(cfg)) => Some(thq_register::Enrollment::new(cfg)),
124    };
125
126    // Build the session — keep copies of secrets/build_info for per-user sessions
127    let config_toml_for_state = config_toml.clone();
128    let secrets_for_state = secrets.clone();
129    let build_info_for_state = build_info.clone();
130    let (mut session, workflow_rx) = trustee_core::session::Session::new();
131    session.config_toml = Some(config_toml);
132    session.secrets = Some(secrets);
133    session.build_info = Some(build_info);
134    session.parse_auto_handoff_config();
135
136    // Extract agent name from config TOML for stateless operation
137    if let Some(ref config_toml_str) = session.config_toml {
138        if let Ok(table) = config_toml_str.parse::<toml::Value>() {
139            if let Some(name) = table.get("agent").and_then(|a| a.get("name")).and_then(|n| n.as_str()) {
140                session.agent_name = name.to_string();
141            }
142        }
143    }
144
145    // Create the broadcast channel for WebSocket fan-out
146    let (ws_tx, _ws_rx) = tokio::sync::broadcast::channel::<String>(256);
147
148    // Wrap session in shared state (with shared config/secrets/build_info for per-user sessions)
149    // Parse knobs: [web].max_sessions_per_user, [users].allow_llm_overlay
150    let (max_sessions, allow_llm_overlay) = {
151        let config_str: &str = &config_toml_for_state;
152        match toml::from_str::<toml::Value>(config_str) {
153            Ok(v) => {
154                let max_sessions = v
155                    .get("web")
156                    .and_then(|w| w.as_table())
157                    .and_then(|w| w.get("max_sessions_per_user").and_then(|v| v.as_integer()))
158                    .map(|v| v as usize)
159                    .unwrap_or(4);
160                let allow_llm_overlay = v
161                    .get("users")
162                    .and_then(|u| u.as_table())
163                    .and_then(|u| u.get("allow_llm_overlay").and_then(|v| v.as_bool()))
164                    .unwrap_or(false);
165                (max_sessions, allow_llm_overlay)
166            }
167            Err(_) => (4, false),
168        }
169    };
170
171    let state = ServerState::new(session, ws_tx, auth_state)
172        .with_config_toml(config_toml_for_state)
173        .with_secrets(secrets_for_state)
174        .with_build_info(build_info_for_state)
175        .with_max_sessions_per_user(max_sessions)
176        .with_allow_llm_overlay(allow_llm_overlay);
177
178    // Start background message drain task (owns workflow_rx directly — no deadlock)
179    state.clone().spawn_drain_task(workflow_rx);
180
181    // 16F: per-agent dispatch table from per-user [thq] overlays — the
182    // dispatch lane is UNCHANGED by the 0.15.0 enrollment rewrite
183    // (different concept: agents-as-users vs the runtime-the-process).
184    thq_dispatch::populate(state.clone());
185
186    // Build router
187    //
188    // Auth middleware approach: since axum 0.8's from_fn_with_state has
189    // trait bound issues with nested routers, we apply auth checking at
190    // the handler level via a helper. Each protected route's handler
191    // calls auth::check_auth() first. This is simpler and avoids type
192    // complexity.
193    let app = axum::Router::new()
194        // Public routes
195        .route("/api/v1/health", get(routes::health))
196        .nest("/auth", auth::auth_routes())
197        // Protected API routes
198        .route("/api/v1/models", get(routes::list_models))
199        .route("/api/v1/session", get(routes::get_session))
200        .route(
201            "/api/v1/session/command",
202            post(routes::post_command).layer(axum::extract::DefaultBodyLimit::max(
203                routes::ATTACH_BODY_LIMIT,
204            )),
205        )
206        .route("/api/v1/session/cancel", post(routes::post_cancel))
207        .route("/api/v1/session/handoff", post(routes::post_handoff))
208        .route("/api/v1/session/stream", get(routes::ws_handler))
209        // Session naming
210        .route("/api/v1/session/name", post(routes::set_session_name))
211        .route("/api/v1/session/new", post(routes::new_session))
212        .route("/api/v1/project/name", post(routes::set_project_name))
213        // Session discovery & resume
214        // Session discovery & resume (checkpoint-based, existing)
215        .route("/api/v1/sessions", get(routes::list_sessions).post(routes::create_session))
216        .route("/api/v1/sessions/live", get(routes::list_live_sessions))
217        .route("/api/v1/sessions/{id}", get(routes::get_session_detail).delete(routes::destroy_session))
218        .route("/api/v1/sessions/{id}/live", get(routes::get_live_session))
219        .route("/api/v1/sessions/{id}/resume", post(routes::resume_session))
220        .route("/api/v1/sessions/{id}/history", get(routes::get_session_history))
221        // MSU: session-scoped live routes
222        .route(
223            "/api/v1/sessions/{id}/command",
224            post(routes::post_command_session).layer(axum::extract::DefaultBodyLimit::max(
225                routes::ATTACH_BODY_LIMIT,
226            )),
227        )
228        .route("/api/v1/sessions/{id}/cancel", post(routes::post_cancel_session))
229        .route("/api/v1/sessions/{id}/handoff", post(routes::post_handoff_session))
230        .route("/api/v1/sessions/{id}/name", post(routes::set_session_name_session))
231        .route("/api/v1/sessions/{id}/stream", get(routes::ws_session_handler))
232        // Static files from trustee-web
233        .route("/", get(routes::serve_index))
234        .route("/{file}", get(routes::serve_static))
235        // 16F: per-agent THQ dispatch surface (impersonation by Bearer swap)
236        .merge(crate::xagent::router());
237    // THQ v0.3 enrollment callback lane: THQ POSTs the runtime secret
238    // here (register → /thq/enroll → pull/state loop). No [thq] config
239    // → no route (404 for would-be enroll callers).
240    let app = match &thq_enrollment {
241        Some(enr) => app.merge(thq_register::enroll_route(enr.clone())),
242        None => app,
243    };
244    // state clone for the enrollment loop (with_state below consumes it)
245    let enrollment_state = state.clone();
246    let app = app
247        .layer(CorsLayer::permissive())
248        .layer(axum::extract::DefaultBodyLimit::max(10 * 1024 * 1024))
249        .with_state(state);
250
251    // Bind BEFORE starting the enrollment loop: register's callback must
252    // land on a live /thq/enroll route (otherwise the first register
253    // wastes its callback and the loop self-heals a cycle later).
254    let listener = tokio::net::TcpListener::bind(addr).await?;
255    if let Some(enr) = thq_enrollment {
256        enr.spawn(enrollment_state);
257    }
258
259    if use_tls {
260        // Install ring as the process-level crypto provider (required when
261        // rustls is built with default-features=false to avoid ambiguity
262        // with aws-lc-rs pulled in transitively by other crates).
263        let _ = rustls::crypto::ring::default_provider().install_default();
264
265        // Ensure self-signed certs exist
266        let cert_dir = tls::default_cert_dir();
267        let (cert_path, key_path) = tls::ensure_certs(&cert_dir)?;
268
269        // Load TLS config
270        let tls_config = tls::load_tls_config(&cert_path, &key_path)?;
271        let acceptor = tokio_rustls::TlsAcceptor::from(std::sync::Arc::new(tls_config));
272
273        tracing::info!("Trustee API listening on https://{}", addr);
274
275        // Manual accept loop — spawn hyper-util auto connection per TLS stream
276        loop {
277            let (tcp_stream, peer_addr) = match listener.accept().await {
278                Ok(stream) => stream,
279                Err(e) => {
280                    tracing::warn!("TCP accept failed: {}", e);
281                    continue;
282                }
283            };
284
285            let acceptor = acceptor.clone();
286            let app = app.clone();
287
288            tokio::spawn(async move {
289                let tls_stream = match acceptor.accept(tcp_stream).await {
290                    Ok(s) => s,
291                    Err(e) => {
292                        tracing::debug!("TLS accept failed from {}: {}", peer_addr, e);
293                        return;
294                    }
295                };
296
297                // Use hyper-util auto builder with the tower service from axum.
298                // serve_connection_with_upgrades is required for WebSocket support.
299                let io = hyper_util::rt::TokioIo::new(tls_stream);
300                let svc = hyper_util::service::TowerToHyperService::new(app);
301
302                let _ = hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new())
303                    .serve_connection_with_upgrades(io, svc)
304                    .await;
305            });
306        }
307    } else {
308        tracing::info!("Trustee API listening on http://{}", addr);
309        axum::serve(listener, app).await?;
310    }
311
312    Ok(())
313}
314
315/// Parse [cedar] section from config TOML and create a CedarAuthorizer if enabled.
316///
317/// Configuration:
318/// - `[cedar] enabled = true/false` (default: false)
319/// - `[cedar] policy_path = "/path/to/policies.cedar"` (filesystem override)
320/// - `[cedar] schema_path = "/path/to/schema.cedarschema"` (filesystem override)
321/// - `[cedar] policy_store_url = "https://..."` (remote policy store)
322///
323/// When enabled without filesystem paths, uses embedded defaults.
324/// P2 boot result for Cedar (nghr 645809c3).
325struct CedarBoot {
326    authorizer: Option<Arc<pep::cedar::CedarAuthorizer>>,
327    /// Explicit per-environment escape hatch: `[cedar] allow_disabled = true`
328    /// opts THIS deployment into identity-only mode (Cedar absent). The
329    /// DEFAULT is fail-closed: web mode with auth configured refuses to
330    /// boot without a working Cedar authorizer.
331    allow_disabled: bool,
332}
333
334/// Pure decision for the P2 fail-closed posture — unit-tested.
335pub(crate) fn cedar_boot_decision(
336    auth_configured: bool,
337    cedar_present: bool,
338    allow_disabled: bool,
339) -> Result<(), String> {
340    if !auth_configured {
341        // Open mode (no [oidc]/[dev]) — preserved for local/dev usage; the
342        // absence of auth is logged loudly at boot.
343        return Ok(());
344    }
345    if cedar_present || allow_disabled {
346        Ok(())
347    } else {
348        Err(
349            "Cedar authorization is REQUIRED in web mode (fail-closed, nghr 645809c3). \
350             Either configure it: [cedar] enabled = true (policies ship embedded), \
351             or explicitly opt out per environment: [cedar] allow_disabled = true."
352                .to_string(),
353        )
354    }
355}
356
357async fn parse_cedar_config(config_toml: &str) -> Result<CedarBoot, String> {
358    let parsed: Option<toml::Table> = toml::from_str(config_toml).ok();
359    let cedar_table = parsed.as_ref().and_then(|t| t.get("cedar"));
360    let allow_disabled = cedar_table
361        .and_then(|c| c.get("allow_disabled"))
362        .and_then(|v| v.as_bool())
363        .unwrap_or(false);
364
365    let Some(cedar_section) = cedar_table.and_then(|c| c.as_table().cloned()) else {
366        return Ok(CedarBoot {
367            authorizer: None,
368            allow_disabled,
369        });
370    };
371    let enabled = cedar_section
372        .get("enabled")
373        .and_then(|v| v.as_bool())
374        .unwrap_or(false);
375
376    if !enabled {
377        tracing::debug!("Cedar authorization disabled (default)");
378        return Ok(CedarBoot {
379            authorizer: None,
380            allow_disabled,
381        });
382    }
383
384    tracing::info!("Cedar authorization enabled — initializing authorizer");
385
386    // Default policy/schema paths point to ~/{agent_name}/policies/ (created by trustee init).
387    // Agent name is read from [agent] name in config, defaulting to "trustee".
388    let agent_name = parsed
389        .as_ref()
390        .and_then(|t| t.get("agent"))
391        .and_then(|a| a.as_table())
392        .and_then(|a| a.get("name"))
393        .and_then(|n| n.as_str())
394        .unwrap_or("trustee");
395
396    let home_policies_dir = dirs::home_dir()
397        .map(|h| h.join(format!(".{}", agent_name)).join("policies"))
398        .unwrap_or_else(|| std::path::PathBuf::from("/nonexistent"));
399
400    let default_policy_path = home_policies_dir.join("trustee_default.cedar");
401    let default_schema_path = home_policies_dir.join("trustee_schema.cedarschema");
402
403    let policy_path = cedar_section
404        .get("policy_path")
405        .and_then(|v| v.as_str())
406        .filter(|s| !s.is_empty())
407        .map(std::path::PathBuf::from)
408        .unwrap_or(default_policy_path);
409
410    let schema_path = cedar_section
411        .get("schema_path")
412        .and_then(|v| v.as_str())
413        .filter(|s| !s.is_empty())
414        .map(std::path::PathBuf::from)
415        .or_else(|| Some(default_schema_path));
416
417    let policy_store_url = cedar_section
418        .get("policy_store_url")
419        .and_then(|v| v.as_str())
420        .map(String::from);
421
422    let policy_store_token = cedar_section
423        .get("policy_store_token")
424        .and_then(|v| v.as_str())
425        .map(String::from);
426
427    let cedar_config = pep::cedar::CedarConfig {
428        policy_path,
429        schema_path,
430        entities_path: None,
431        default_decision: pep::cedar::DefaultDecision::Deny,
432        validate_on_load: true,
433        policy_store_url,
434        policy_store_token,
435        embedded_policy: Some(EMBEDDED_CEDAR_POLICY),
436        embedded_schema: Some(EMBEDDED_CEDAR_SCHEMA),
437    };
438
439    match pep::cedar::CedarAuthorizer::new_with_policy_store(cedar_config).await {
440        Ok(auth) => {
441            tracing::info!("Cedar authorizer initialized successfully");
442            Ok(CedarBoot {
443                authorizer: Some(Arc::new(auth)),
444                allow_disabled,
445            })
446        }
447        // FAIL-CLOSED (nghr 645809c3): the v0.1.0–0.1.1 fame bug class —
448        // enabled-but-broken Cedar used to silently disable authorization.
449        // Now the boot dies loudly instead.
450        Err(e) => {
451            let msg = format!(
452                "Cedar authorization is enabled but FAILED to initialize: {e}. \
453                 Refusing to boot (fail-closed). Fix the policy/schema configuration \
454                 or explicitly set [cedar] allow_disabled = true to run identity-only."
455            );
456            tracing::error!("{msg}");
457            Err(msg)
458        }
459    }
460}