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
16use std::net::SocketAddr;
17use std::sync::Arc;
18
19use anyhow::Result;
20use axum::routing::{get, post};
21use tower_http::cors::CorsLayer;
22
23pub use auth::{AuthConfig, AuthState};
24pub use state::ServerState;
25
26/// Run the API server.
27///
28/// Creates a `Session` with the given config, starts a background task to
29/// drain workflow messages and broadcast them to WebSocket clients, then
30/// serves the REST + WebSocket + static files on `addr`.
31///
32/// If `[oidc]` or `[dev]` sections are found in the config TOML, auth is
33/// enabled — all `/api/v1/*` endpoints (except health) require a valid token.
34///
35/// By default serves over HTTPS using a self-signed certificate from
36/// `~/.trustee/certs/`. If `use_tls` is false, serves plain HTTP.
37pub async fn run(
38    config_toml: String,
39    secrets: std::collections::HashMap<String, String>,
40    build_info: trustee_core::types::BuildInfo,
41    addr: SocketAddr,
42    use_tls: bool,
43) -> Result<()> {
44    // Parse auth config from TOML (returns None if no [oidc] or [dev] sections)
45    let auth_state = AuthConfig::from_toml(&config_toml).map(|cfg| {
46        let is_dev = cfg.dev_config.local_dev_mode;
47        tracing::info!(
48            "Auth enabled: {} mode, issuer={}",
49            if is_dev { "development" } else { "production" },
50            cfg.issuer_url
51        );
52        Arc::new(AuthState::new(cfg))
53    });
54
55    // Parse THQ registration config before config_toml is moved into session
56    let thq_config = thq_register::ThqConfig::from_toml(&config_toml);
57
58    // Build the session — keep copies of secrets/build_info for per-user sessions
59    let config_toml_for_state = config_toml.clone();
60    let secrets_for_state = secrets.clone();
61    let build_info_for_state = build_info.clone();
62    let (mut session, workflow_rx) = trustee_core::session::Session::new();
63    session.config_toml = Some(config_toml);
64    session.secrets = Some(secrets);
65    session.build_info = Some(build_info);
66    session.parse_auto_handoff_config();
67
68    // Extract agent name from config TOML for stateless operation
69    if let Some(ref config_toml_str) = session.config_toml {
70        if let Ok(table) = config_toml_str.parse::<toml::Value>() {
71            if let Some(name) = table.get("agent").and_then(|a| a.get("name")).and_then(|n| n.as_str()) {
72                session.agent_name = name.to_string();
73            }
74        }
75    }
76
77    // Create the broadcast channel for WebSocket fan-out
78    let (ws_tx, _ws_rx) = tokio::sync::broadcast::channel::<String>(256);
79
80    // Wrap session in shared state (with shared config/secrets/build_info for per-user sessions)
81    let state = ServerState::new(session, ws_tx, auth_state)
82        .with_config_toml(config_toml_for_state)
83        .with_secrets(secrets_for_state)
84        .with_build_info(build_info_for_state);
85
86    // Start background message drain task (owns workflow_rx directly — no deadlock)
87    state.clone().spawn_drain_task(workflow_rx);
88
89    // THQ auto-registration with Torpi (if [thq] section is present in config)
90    if let Some(cfg) = thq_config {
91        thq_register::spawn(cfg);
92    } else {
93        tracing::debug!("THQ registration not configured (no [thq] section)");
94    }
95
96    // Build router
97    //
98    // Auth middleware approach: since axum 0.8's from_fn_with_state has
99    // trait bound issues with nested routers, we apply auth checking at
100    // the handler level via a helper. Each protected route's handler
101    // calls auth::check_auth() first. This is simpler and avoids type
102    // complexity.
103    let app = axum::Router::new()
104        // Public routes
105        .route("/api/v1/health", get(routes::health))
106        .nest("/auth", auth::auth_routes())
107        // Protected API routes
108        .route("/api/v1/session", get(routes::get_session))
109        .route("/api/v1/session/command", post(routes::post_command))
110        .route("/api/v1/session/cancel", post(routes::post_cancel))
111        .route("/api/v1/session/handoff", post(routes::post_handoff))
112        .route("/api/v1/session/stream", get(routes::ws_handler))
113        // Session naming
114        .route("/api/v1/session/name", post(routes::set_session_name))
115        .route("/api/v1/session/new", post(routes::new_session))
116        .route("/api/v1/project/name", post(routes::set_project_name))
117        // Session discovery & resume
118        .route("/api/v1/sessions", get(routes::list_sessions))
119        .route("/api/v1/sessions/{id}", get(routes::get_session_detail))
120        .route("/api/v1/sessions/{id}/resume", post(routes::resume_session))
121        .route("/api/v1/sessions/{id}/history", get(routes::get_session_history))
122        // Static files from trustee-web
123        .route("/", get(routes::serve_index))
124        .route("/{file}", get(routes::serve_static))
125        .layer(CorsLayer::permissive())
126        .layer(axum::extract::DefaultBodyLimit::max(10 * 1024 * 1024))
127        .with_state(state);
128
129    // Start server
130    let listener = tokio::net::TcpListener::bind(addr).await?;
131
132    if use_tls {
133        // Install ring as the process-level crypto provider (required when
134        // rustls is built with default-features=false to avoid ambiguity
135        // with aws-lc-rs pulled in transitively by other crates).
136        let _ = rustls::crypto::ring::default_provider().install_default();
137
138        // Ensure self-signed certs exist
139        let cert_dir = tls::default_cert_dir();
140        let (cert_path, key_path) = tls::ensure_certs(&cert_dir)?;
141
142        // Load TLS config
143        let tls_config = tls::load_tls_config(&cert_path, &key_path)?;
144        let acceptor = tokio_rustls::TlsAcceptor::from(std::sync::Arc::new(tls_config));
145
146        tracing::info!("Trustee API listening on https://{}", addr);
147
148        // Manual accept loop — spawn hyper-util auto connection per TLS stream
149        loop {
150            let (tcp_stream, peer_addr) = match listener.accept().await {
151                Ok(stream) => stream,
152                Err(e) => {
153                    tracing::warn!("TCP accept failed: {}", e);
154                    continue;
155                }
156            };
157
158            let acceptor = acceptor.clone();
159            let app = app.clone();
160
161            tokio::spawn(async move {
162                let tls_stream = match acceptor.accept(tcp_stream).await {
163                    Ok(s) => s,
164                    Err(e) => {
165                        tracing::debug!("TLS accept failed from {}: {}", peer_addr, e);
166                        return;
167                    }
168                };
169
170                // Use hyper-util auto builder with the tower service from axum.
171                // serve_connection_with_upgrades is required for WebSocket support.
172                let io = hyper_util::rt::TokioIo::new(tls_stream);
173                let svc = hyper_util::service::TowerToHyperService::new(app);
174
175                let _ = hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new())
176                    .serve_connection_with_upgrades(io, svc)
177                    .await;
178            });
179        }
180    } else {
181        tracing::info!("Trustee API listening on http://{}", addr);
182        axum::serve(listener, app).await?;
183    }
184
185    Ok(())
186}