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(
191            "/api/v1/session/command",
192            post(routes::post_command).layer(axum::extract::DefaultBodyLimit::max(
193                routes::ATTACH_BODY_LIMIT,
194            )),
195        )
196        .route("/api/v1/session/cancel", post(routes::post_cancel))
197        .route("/api/v1/session/handoff", post(routes::post_handoff))
198        .route("/api/v1/session/stream", get(routes::ws_handler))
199        // Session naming
200        .route("/api/v1/session/name", post(routes::set_session_name))
201        .route("/api/v1/session/new", post(routes::new_session))
202        .route("/api/v1/project/name", post(routes::set_project_name))
203        // Session discovery & resume
204        // Session discovery & resume (checkpoint-based, existing)
205        .route("/api/v1/sessions", get(routes::list_sessions).post(routes::create_session))
206        .route("/api/v1/sessions/live", get(routes::list_live_sessions))
207        .route("/api/v1/sessions/{id}", get(routes::get_session_detail).delete(routes::destroy_session))
208        .route("/api/v1/sessions/{id}/live", get(routes::get_live_session))
209        .route("/api/v1/sessions/{id}/resume", post(routes::resume_session))
210        .route("/api/v1/sessions/{id}/history", get(routes::get_session_history))
211        // MSU: session-scoped live routes
212        .route(
213            "/api/v1/sessions/{id}/command",
214            post(routes::post_command_session).layer(axum::extract::DefaultBodyLimit::max(
215                routes::ATTACH_BODY_LIMIT,
216            )),
217        )
218        .route("/api/v1/sessions/{id}/cancel", post(routes::post_cancel_session))
219        .route("/api/v1/sessions/{id}/handoff", post(routes::post_handoff_session))
220        .route("/api/v1/sessions/{id}/name", post(routes::set_session_name_session))
221        .route("/api/v1/sessions/{id}/stream", get(routes::ws_session_handler))
222        // Static files from trustee-web
223        .route("/", get(routes::serve_index))
224        .route("/{file}", get(routes::serve_static))
225        // 16F: per-agent THQ dispatch surface (impersonation by Bearer swap)
226        .merge(crate::xagent::router())
227        .layer(CorsLayer::permissive())
228        .layer(axum::extract::DefaultBodyLimit::max(10 * 1024 * 1024))
229        .with_state(state);
230
231    // Start server
232    let listener = tokio::net::TcpListener::bind(addr).await?;
233
234    if use_tls {
235        // Install ring as the process-level crypto provider (required when
236        // rustls is built with default-features=false to avoid ambiguity
237        // with aws-lc-rs pulled in transitively by other crates).
238        let _ = rustls::crypto::ring::default_provider().install_default();
239
240        // Ensure self-signed certs exist
241        let cert_dir = tls::default_cert_dir();
242        let (cert_path, key_path) = tls::ensure_certs(&cert_dir)?;
243
244        // Load TLS config
245        let tls_config = tls::load_tls_config(&cert_path, &key_path)?;
246        let acceptor = tokio_rustls::TlsAcceptor::from(std::sync::Arc::new(tls_config));
247
248        tracing::info!("Trustee API listening on https://{}", addr);
249
250        // Manual accept loop — spawn hyper-util auto connection per TLS stream
251        loop {
252            let (tcp_stream, peer_addr) = match listener.accept().await {
253                Ok(stream) => stream,
254                Err(e) => {
255                    tracing::warn!("TCP accept failed: {}", e);
256                    continue;
257                }
258            };
259
260            let acceptor = acceptor.clone();
261            let app = app.clone();
262
263            tokio::spawn(async move {
264                let tls_stream = match acceptor.accept(tcp_stream).await {
265                    Ok(s) => s,
266                    Err(e) => {
267                        tracing::debug!("TLS accept failed from {}: {}", peer_addr, e);
268                        return;
269                    }
270                };
271
272                // Use hyper-util auto builder with the tower service from axum.
273                // serve_connection_with_upgrades is required for WebSocket support.
274                let io = hyper_util::rt::TokioIo::new(tls_stream);
275                let svc = hyper_util::service::TowerToHyperService::new(app);
276
277                let _ = hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new())
278                    .serve_connection_with_upgrades(io, svc)
279                    .await;
280            });
281        }
282    } else {
283        tracing::info!("Trustee API listening on http://{}", addr);
284        axum::serve(listener, app).await?;
285    }
286
287    Ok(())
288}
289
290/// Parse [cedar] section from config TOML and create a CedarAuthorizer if enabled.
291///
292/// Configuration:
293/// - `[cedar] enabled = true/false` (default: false)
294/// - `[cedar] policy_path = "/path/to/policies.cedar"` (filesystem override)
295/// - `[cedar] schema_path = "/path/to/schema.cedarschema"` (filesystem override)
296/// - `[cedar] policy_store_url = "https://..."` (remote policy store)
297///
298/// When enabled without filesystem paths, uses embedded defaults.
299/// P2 boot result for Cedar (nghr 645809c3).
300struct CedarBoot {
301    authorizer: Option<Arc<pep::cedar::CedarAuthorizer>>,
302    /// Explicit per-environment escape hatch: `[cedar] allow_disabled = true`
303    /// opts THIS deployment into identity-only mode (Cedar absent). The
304    /// DEFAULT is fail-closed: web mode with auth configured refuses to
305    /// boot without a working Cedar authorizer.
306    allow_disabled: bool,
307}
308
309/// Pure decision for the P2 fail-closed posture — unit-tested.
310pub(crate) fn cedar_boot_decision(
311    auth_configured: bool,
312    cedar_present: bool,
313    allow_disabled: bool,
314) -> Result<(), String> {
315    if !auth_configured {
316        // Open mode (no [oidc]/[dev]) — preserved for local/dev usage; the
317        // absence of auth is logged loudly at boot.
318        return Ok(());
319    }
320    if cedar_present || allow_disabled {
321        Ok(())
322    } else {
323        Err(
324            "Cedar authorization is REQUIRED in web mode (fail-closed, nghr 645809c3). \
325             Either configure it: [cedar] enabled = true (policies ship embedded), \
326             or explicitly opt out per environment: [cedar] allow_disabled = true."
327                .to_string(),
328        )
329    }
330}
331
332async fn parse_cedar_config(config_toml: &str) -> Result<CedarBoot, String> {
333    let parsed: Option<toml::Table> = toml::from_str(config_toml).ok();
334    let cedar_table = parsed.as_ref().and_then(|t| t.get("cedar"));
335    let allow_disabled = cedar_table
336        .and_then(|c| c.get("allow_disabled"))
337        .and_then(|v| v.as_bool())
338        .unwrap_or(false);
339
340    let Some(cedar_section) = cedar_table.and_then(|c| c.as_table().cloned()) else {
341        return Ok(CedarBoot {
342            authorizer: None,
343            allow_disabled,
344        });
345    };
346    let enabled = cedar_section
347        .get("enabled")
348        .and_then(|v| v.as_bool())
349        .unwrap_or(false);
350
351    if !enabled {
352        tracing::debug!("Cedar authorization disabled (default)");
353        return Ok(CedarBoot {
354            authorizer: None,
355            allow_disabled,
356        });
357    }
358
359    tracing::info!("Cedar authorization enabled — initializing authorizer");
360
361    // Default policy/schema paths point to ~/{agent_name}/policies/ (created by trustee init).
362    // Agent name is read from [agent] name in config, defaulting to "trustee".
363    let agent_name = parsed
364        .as_ref()
365        .and_then(|t| t.get("agent"))
366        .and_then(|a| a.as_table())
367        .and_then(|a| a.get("name"))
368        .and_then(|n| n.as_str())
369        .unwrap_or("trustee");
370
371    let home_policies_dir = dirs::home_dir()
372        .map(|h| h.join(format!(".{}", agent_name)).join("policies"))
373        .unwrap_or_else(|| std::path::PathBuf::from("/nonexistent"));
374
375    let default_policy_path = home_policies_dir.join("trustee_default.cedar");
376    let default_schema_path = home_policies_dir.join("trustee_schema.cedarschema");
377
378    let policy_path = cedar_section
379        .get("policy_path")
380        .and_then(|v| v.as_str())
381        .filter(|s| !s.is_empty())
382        .map(std::path::PathBuf::from)
383        .unwrap_or(default_policy_path);
384
385    let schema_path = cedar_section
386        .get("schema_path")
387        .and_then(|v| v.as_str())
388        .filter(|s| !s.is_empty())
389        .map(std::path::PathBuf::from)
390        .or_else(|| Some(default_schema_path));
391
392    let policy_store_url = cedar_section
393        .get("policy_store_url")
394        .and_then(|v| v.as_str())
395        .map(String::from);
396
397    let policy_store_token = cedar_section
398        .get("policy_store_token")
399        .and_then(|v| v.as_str())
400        .map(String::from);
401
402    let cedar_config = pep::cedar::CedarConfig {
403        policy_path,
404        schema_path,
405        entities_path: None,
406        default_decision: pep::cedar::DefaultDecision::Deny,
407        validate_on_load: true,
408        policy_store_url,
409        policy_store_token,
410        embedded_policy: Some(EMBEDDED_CEDAR_POLICY),
411        embedded_schema: Some(EMBEDDED_CEDAR_SCHEMA),
412    };
413
414    match pep::cedar::CedarAuthorizer::new_with_policy_store(cedar_config).await {
415        Ok(auth) => {
416            tracing::info!("Cedar authorizer initialized successfully");
417            Ok(CedarBoot {
418                authorizer: Some(Arc::new(auth)),
419                allow_disabled,
420            })
421        }
422        // FAIL-CLOSED (nghr 645809c3): the v0.1.0–0.1.1 fame bug class —
423        // enabled-but-broken Cedar used to silently disable authorization.
424        // Now the boot dies loudly instead.
425        Err(e) => {
426            let msg = format!(
427                "Cedar authorization is enabled but FAILED to initialize: {e}. \
428                 Refusing to boot (fail-closed). Fix the policy/schema configuration \
429                 or explicitly set [cedar] allow_disabled = true to run identity-only."
430            );
431            tracing::error!("{msg}");
432            Err(msg)
433        }
434    }
435}