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;
15
16// Embedded Cedar policy defaults (compiled into binary)
17const EMBEDDED_CEDAR_POLICY: &str = include_str!("../policies/trustee_default.cedar");
18const EMBEDDED_CEDAR_SCHEMA: &str = include_str!("../policies/trustee_schema.cedarschema");
19
20use std::net::SocketAddr;
21use std::sync::Arc;
22
23use anyhow::Result;
24use axum::routing::{get, post};
25use tower_http::cors::CorsLayer;
26
27pub use auth::{AuthConfig, AuthState};
28pub use state::ServerState;
29
30/// Run the API server.
31///
32/// Creates a `Session` with the given config, starts a background task to
33/// drain workflow messages and broadcast them to WebSocket clients, then
34/// serves the REST + WebSocket + static files on `addr`.
35///
36/// If `[oidc]` or `[dev]` sections are found in the config TOML, auth is
37/// enabled — all `/api/v1/*` endpoints (except health) require a valid token.
38///
39/// By default serves over HTTPS using a self-signed certificate from
40/// `~/.trustee/certs/`. If `use_tls` is false, serves plain HTTP.
41pub async fn run(
42    config_toml: String,
43    secrets: std::collections::HashMap<String, String>,
44    build_info: trustee_core::types::BuildInfo,
45    addr: SocketAddr,
46    use_tls: bool,
47) -> Result<()> {
48    // Parse auth config from TOML (returns None if no [oidc] or [dev] sections)
49    let auth_state = if let Some(cfg) = AuthConfig::from_toml(&config_toml) {
50        let is_dev = cfg.dev_config.local_dev_mode;
51        tracing::info!(
52            "Auth enabled: {} mode, issuer={}",
53            if is_dev { "development" } else { "production" },
54            cfg.issuer_url
55        );
56
57        // Parse optional Cedar authorization config
58        let cedar_authorizer = parse_cedar_config(&config_toml).await;
59
60        Some(Arc::new(AuthState::with_cedar(cfg, cedar_authorizer)))
61    } else {
62        None
63    };
64
65    // Parse THQ registration config before config_toml is moved into session
66    let thq_config = thq_register::ThqConfig::from_toml(&config_toml);
67
68    // Build the session — keep copies of secrets/build_info for per-user sessions
69    let config_toml_for_state = config_toml.clone();
70    let secrets_for_state = secrets.clone();
71    let build_info_for_state = build_info.clone();
72    let (mut session, workflow_rx) = trustee_core::session::Session::new();
73    session.config_toml = Some(config_toml);
74    session.secrets = Some(secrets);
75    session.build_info = Some(build_info);
76    session.parse_auto_handoff_config();
77
78    // Extract agent name from config TOML for stateless operation
79    if let Some(ref config_toml_str) = session.config_toml {
80        if let Ok(table) = config_toml_str.parse::<toml::Value>() {
81            if let Some(name) = table.get("agent").and_then(|a| a.get("name")).and_then(|n| n.as_str()) {
82                session.agent_name = name.to_string();
83            }
84        }
85    }
86
87    // Create the broadcast channel for WebSocket fan-out
88    let (ws_tx, _ws_rx) = tokio::sync::broadcast::channel::<String>(256);
89
90    // Wrap session in shared state (with shared config/secrets/build_info for per-user sessions)
91    // Parse max_sessions_per_user from [web] section
92    let max_sessions: usize = {
93        let config_str: &str = &config_toml_for_state;
94        match toml::from_str::<toml::Value>(config_str) {
95            Ok(v) => v
96                .get("web")
97                .and_then(|w| w.as_table())
98                .and_then(|w| w.get("max_sessions_per_user").and_then(|v| v.as_integer()))
99                .map(|v| v as usize)
100                .unwrap_or(4),
101            Err(_) => 4,
102        }
103    };
104
105    let state = ServerState::new(session, ws_tx, auth_state)
106        .with_config_toml(config_toml_for_state)
107        .with_secrets(secrets_for_state)
108        .with_build_info(build_info_for_state)
109        .with_max_sessions_per_user(max_sessions);
110
111    // Start background message drain task (owns workflow_rx directly — no deadlock)
112    state.clone().spawn_drain_task(workflow_rx);
113
114    // THQ auto-registration with Torpi (if [thq] section is present in config)
115    if let Some(cfg) = thq_config {
116        thq_register::spawn(cfg);
117    } else {
118        tracing::debug!("THQ registration not configured (no [thq] section)");
119    }
120
121    // Build router
122    //
123    // Auth middleware approach: since axum 0.8's from_fn_with_state has
124    // trait bound issues with nested routers, we apply auth checking at
125    // the handler level via a helper. Each protected route's handler
126    // calls auth::check_auth() first. This is simpler and avoids type
127    // complexity.
128    let app = axum::Router::new()
129        // Public routes
130        .route("/api/v1/health", get(routes::health))
131        .nest("/auth", auth::auth_routes())
132        // Protected API routes
133        .route("/api/v1/session", get(routes::get_session))
134        .route("/api/v1/session/command", post(routes::post_command))
135        .route("/api/v1/session/cancel", post(routes::post_cancel))
136        .route("/api/v1/session/handoff", post(routes::post_handoff))
137        .route("/api/v1/session/stream", get(routes::ws_handler))
138        // Session naming
139        .route("/api/v1/session/name", post(routes::set_session_name))
140        .route("/api/v1/session/new", post(routes::new_session))
141        .route("/api/v1/project/name", post(routes::set_project_name))
142        // Session discovery & resume
143        // Session discovery & resume (checkpoint-based, existing)
144        .route("/api/v1/sessions", get(routes::list_sessions).post(routes::create_session))
145        .route("/api/v1/sessions/live", get(routes::list_live_sessions))
146        .route("/api/v1/sessions/{id}", get(routes::get_session_detail).delete(routes::destroy_session))
147        .route("/api/v1/sessions/{id}/live", get(routes::get_live_session))
148        .route("/api/v1/sessions/{id}/resume", post(routes::resume_session))
149        .route("/api/v1/sessions/{id}/history", get(routes::get_session_history))
150        // MSU: session-scoped live routes
151        .route("/api/v1/sessions/{id}/command", post(routes::post_command_session))
152        .route("/api/v1/sessions/{id}/cancel", post(routes::post_cancel_session))
153        .route("/api/v1/sessions/{id}/handoff", post(routes::post_handoff_session))
154        .route("/api/v1/sessions/{id}/name", post(routes::set_session_name_session))
155        .route("/api/v1/sessions/{id}/stream", get(routes::ws_session_handler))
156        // Static files from trustee-web
157        .route("/", get(routes::serve_index))
158        .route("/{file}", get(routes::serve_static))
159        .layer(CorsLayer::permissive())
160        .layer(axum::extract::DefaultBodyLimit::max(10 * 1024 * 1024))
161        .with_state(state);
162
163    // Start server
164    let listener = tokio::net::TcpListener::bind(addr).await?;
165
166    if use_tls {
167        // Install ring as the process-level crypto provider (required when
168        // rustls is built with default-features=false to avoid ambiguity
169        // with aws-lc-rs pulled in transitively by other crates).
170        let _ = rustls::crypto::ring::default_provider().install_default();
171
172        // Ensure self-signed certs exist
173        let cert_dir = tls::default_cert_dir();
174        let (cert_path, key_path) = tls::ensure_certs(&cert_dir)?;
175
176        // Load TLS config
177        let tls_config = tls::load_tls_config(&cert_path, &key_path)?;
178        let acceptor = tokio_rustls::TlsAcceptor::from(std::sync::Arc::new(tls_config));
179
180        tracing::info!("Trustee API listening on https://{}", addr);
181
182        // Manual accept loop — spawn hyper-util auto connection per TLS stream
183        loop {
184            let (tcp_stream, peer_addr) = match listener.accept().await {
185                Ok(stream) => stream,
186                Err(e) => {
187                    tracing::warn!("TCP accept failed: {}", e);
188                    continue;
189                }
190            };
191
192            let acceptor = acceptor.clone();
193            let app = app.clone();
194
195            tokio::spawn(async move {
196                let tls_stream = match acceptor.accept(tcp_stream).await {
197                    Ok(s) => s,
198                    Err(e) => {
199                        tracing::debug!("TLS accept failed from {}: {}", peer_addr, e);
200                        return;
201                    }
202                };
203
204                // Use hyper-util auto builder with the tower service from axum.
205                // serve_connection_with_upgrades is required for WebSocket support.
206                let io = hyper_util::rt::TokioIo::new(tls_stream);
207                let svc = hyper_util::service::TowerToHyperService::new(app);
208
209                let _ = hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new())
210                    .serve_connection_with_upgrades(io, svc)
211                    .await;
212            });
213        }
214    } else {
215        tracing::info!("Trustee API listening on http://{}", addr);
216        axum::serve(listener, app).await?;
217    }
218
219    Ok(())
220}
221
222/// Parse [cedar] section from config TOML and create a CedarAuthorizer if enabled.
223///
224/// Configuration:
225/// - `[cedar] enabled = true/false` (default: false)
226/// - `[cedar] policy_path = "/path/to/policies.cedar"` (filesystem override)
227/// - `[cedar] schema_path = "/path/to/schema.cedarschema"` (filesystem override)
228/// - `[cedar] policy_store_url = "https://..."` (remote policy store)
229///
230/// When enabled without filesystem paths, uses embedded defaults.
231async fn parse_cedar_config(config_toml: &str) -> Option<Arc<pep::cedar::CedarAuthorizer>> {
232    let table: toml::Table = match toml::from_str(config_toml) {
233        Ok(t) => t,
234        Err(_) => return None,
235    };
236
237    let cedar_section = table.get("cedar")?.as_table()?;
238    let enabled = cedar_section
239        .get("enabled")
240        .and_then(|v| v.as_bool())
241        .unwrap_or(false);
242
243    if !enabled {
244        tracing::debug!("Cedar authorization disabled (default)");
245        return None;
246    }
247
248    tracing::info!("Cedar authorization enabled — initializing authorizer");
249
250    // Default policy/schema paths point to ~/{agent_name}/policies/ (created by trustee init).
251    // Agent name is read from [agent] name in config, defaulting to "trustee".
252    let agent_name = table
253        .get("agent")
254        .and_then(|a| a.as_table())
255        .and_then(|a| a.get("name"))
256        .and_then(|n| n.as_str())
257        .unwrap_or("trustee");
258
259    let home_policies_dir = dirs::home_dir()
260        .map(|h| h.join(format!(".{}", agent_name)).join("policies"))
261        .unwrap_or_else(|| std::path::PathBuf::from("/nonexistent"));
262
263    let default_policy_path = home_policies_dir.join("trustee_default.cedar");
264    let default_schema_path = home_policies_dir.join("trustee_schema.cedarschema");
265
266    let policy_path = cedar_section
267        .get("policy_path")
268        .and_then(|v| v.as_str())
269        .filter(|s| !s.is_empty())
270        .map(std::path::PathBuf::from)
271        .unwrap_or(default_policy_path);
272
273    let schema_path = cedar_section
274        .get("schema_path")
275        .and_then(|v| v.as_str())
276        .filter(|s| !s.is_empty())
277        .map(std::path::PathBuf::from)
278        .or_else(|| Some(default_schema_path));
279
280    let policy_store_url = cedar_section
281        .get("policy_store_url")
282        .and_then(|v| v.as_str())
283        .map(String::from);
284
285    let policy_store_token = cedar_section
286        .get("policy_store_token")
287        .and_then(|v| v.as_str())
288        .map(String::from);
289
290    let cedar_config = pep::cedar::CedarConfig {
291        policy_path,
292        schema_path,
293        entities_path: None,
294        default_decision: pep::cedar::DefaultDecision::Deny,
295        validate_on_load: true,
296        policy_store_url,
297        policy_store_token,
298        embedded_policy: Some(EMBEDDED_CEDAR_POLICY),
299        embedded_schema: Some(EMBEDDED_CEDAR_SCHEMA),
300    };
301
302    match pep::cedar::CedarAuthorizer::new_with_policy_store(cedar_config).await {
303        Ok(auth) => {
304            tracing::info!("Cedar authorizer initialized successfully");
305            Some(Arc::new(auth))
306        }
307        Err(e) => {
308            tracing::error!("Failed to initialize Cedar authorizer: {}", e);
309            tracing::warn!("Cedar was enabled but initialization failed — auth will proceed WITHOUT Cedar");
310            None
311        }
312    }
313}