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