1pub mod auth;
11pub mod identity;
12pub mod tls;
13mod routes;
14mod state;
15mod materialize;
16mod thq_dispatch;
17mod thq_register;
18pub mod xagent;
19
20static BIN_VERSION: std::sync::OnceLock<String> = std::sync::OnceLock::new();
25
26pub fn set_bin_version(v: &str) {
30 let _ = BIN_VERSION.set(v.to_string());
31}
32
33pub fn bin_version() -> &'static str {
36 BIN_VERSION
37 .get()
38 .map(|s| s.as_str())
39 .unwrap_or(env!("CARGO_PKG_VERSION"))
40}
41
42const EMBEDDED_CEDAR_POLICY: &str = include_str!("../policies/trustee_default.cedar");
44const EMBEDDED_CEDAR_SCHEMA: &str = include_str!("../policies/trustee_schema.cedarschema");
45
46use std::net::SocketAddr;
47use std::sync::Arc;
48
49use anyhow::Result;
50use axum::routing::{get, post};
51use tower_http::cors::CorsLayer;
52
53pub use auth::{AuthConfig, AuthState};
54pub use state::ServerState;
55
56pub async fn run(
68 config_toml: String,
69 secrets: std::collections::HashMap<String, String>,
70 build_info: trustee_core::types::BuildInfo,
71 addr: SocketAddr,
72 use_tls: bool,
73) -> Result<()> {
74 let auth_state = if let Some(cfg) = AuthConfig::from_toml(&config_toml) {
76 let is_dev = cfg.dev_config.local_dev_mode;
77 tracing::info!(
78 "Auth enabled: {} mode, issuer={}",
79 if is_dev { "development" } else { "production" },
80 cfg.issuer_url
81 );
82
83 let cedar_boot = parse_cedar_config(&config_toml)
85 .await
86 .map_err(|e| anyhow::anyhow!("{e}"))?;
87 cedar_boot_decision(
88 true,
89 cedar_boot.authorizer.is_some(),
90 cedar_boot.allow_disabled,
91 )
92 .map_err(|e| anyhow::anyhow!("{e}"))?;
93
94 let mut issuer_fallbacks = crate::state::service_issuers_from_config(&config_toml);
97 for si in crate::thq_dispatch::discover_service_issuers() {
98 if !issuer_fallbacks.contains(&si) {
99 issuer_fallbacks.push(si);
100 }
101 }
102 issuer_fallbacks.retain(|si| *si != cfg.issuer_url);
103 if !issuer_fallbacks.is_empty() {
104 tracing::info!("Auth issuer fallbacks armed: {:?}", issuer_fallbacks);
105 }
106 Some(Arc::new(
107 AuthState::with_cedar(cfg, cedar_boot.authorizer)
108 .with_issuer_fallbacks(issuer_fallbacks),
109 ))
110 } else {
111 tracing::warn!("AUTH NOT CONFIGURED: trustee-web is running WITHOUT authentication or Cedar authorization (no [oidc]/[dev] section). Never expose this to a network.");
113 None
114 };
115
116 let thq_enrollment = match thq_register::ThqConfig::from_toml(&config_toml) {
120 Ok(None) => None,
121 Err(e) => {
122 tracing::error!("THQ enrollment DISABLED — [thq] is malformed: {e}");
123 None
124 }
125 Ok(Some(cfg)) => Some(thq_register::Enrollment::new(cfg)),
126 };
127
128 let config_toml_for_state = config_toml.clone();
130 let secrets_for_state = secrets.clone();
131 let build_info_for_state = build_info.clone();
132 let (mut session, workflow_rx) = trustee_core::session::Session::new();
133 session.config_toml = Some(config_toml);
134 session.secrets = Some(secrets);
135 session.build_info = Some(build_info);
136 session.parse_auto_handoff_config();
137
138 if let Some(ref config_toml_str) = session.config_toml {
140 if let Ok(table) = config_toml_str.parse::<toml::Value>() {
141 if let Some(name) = table.get("agent").and_then(|a| a.get("name")).and_then(|n| n.as_str()) {
142 session.agent_name = name.to_string();
143 }
144 }
145 }
146
147 let (ws_tx, _ws_rx) = tokio::sync::broadcast::channel::<String>(256);
149
150 let (max_sessions, allow_llm_overlay) = {
153 let config_str: &str = &config_toml_for_state;
154 match toml::from_str::<toml::Value>(config_str) {
155 Ok(v) => {
156 let max_sessions = v
157 .get("web")
158 .and_then(|w| w.as_table())
159 .and_then(|w| w.get("max_sessions_per_user").and_then(|v| v.as_integer()))
160 .map(|v| v as usize)
161 .unwrap_or(4);
162 let allow_llm_overlay = v
163 .get("users")
164 .and_then(|u| u.as_table())
165 .and_then(|u| u.get("allow_llm_overlay").and_then(|v| v.as_bool()))
166 .unwrap_or(false);
167 (max_sessions, allow_llm_overlay)
168 }
169 Err(_) => (4, false),
170 }
171 };
172
173 let state = ServerState::new(session, ws_tx, auth_state)
174 .with_config_toml(config_toml_for_state)
175 .with_secrets(secrets_for_state)
176 .with_build_info(build_info_for_state)
177 .with_max_sessions_per_user(max_sessions)
178 .with_allow_llm_overlay(allow_llm_overlay);
179
180 state.clone().spawn_drain_task(workflow_rx);
182
183 thq_dispatch::populate(state.clone());
187
188 let app = axum::Router::new()
196 .route("/api/v1/health", get(routes::health))
198 .nest("/auth", auth::auth_routes())
199 .route("/api/v1/models", get(routes::list_models))
201 .route("/api/v1/session", get(routes::get_session))
202 .route(
203 "/api/v1/session/command",
204 post(routes::post_command).layer(axum::extract::DefaultBodyLimit::max(
205 routes::ATTACH_BODY_LIMIT,
206 )),
207 )
208 .route("/api/v1/session/cancel", post(routes::post_cancel))
209 .route("/api/v1/session/handoff", post(routes::post_handoff))
210 .route("/api/v1/session/stream", get(routes::ws_handler))
211 .route("/api/v1/session/name", post(routes::set_session_name))
213 .route("/api/v1/session/new", post(routes::new_session))
214 .route("/api/v1/project/name", post(routes::set_project_name))
215 .route("/api/v1/sessions", get(routes::list_sessions).post(routes::create_session))
218 .route("/api/v1/sessions/live", get(routes::list_live_sessions))
219 .route("/api/v1/sessions/{id}", get(routes::get_session_detail).delete(routes::destroy_session))
220 .route("/api/v1/sessions/{id}/live", get(routes::get_live_session))
221 .route("/api/v1/sessions/{id}/resume", post(routes::resume_session))
222 .route("/api/v1/sessions/{id}/history", get(routes::get_session_history))
223 .route(
225 "/api/v1/sessions/{id}/command",
226 post(routes::post_command_session).layer(axum::extract::DefaultBodyLimit::max(
227 routes::ATTACH_BODY_LIMIT,
228 )),
229 )
230 .route("/api/v1/sessions/{id}/cancel", post(routes::post_cancel_session))
231 .route("/api/v1/sessions/{id}/handoff", post(routes::post_handoff_session))
232 .route("/api/v1/sessions/{id}/name", post(routes::set_session_name_session))
233 .route("/api/v1/sessions/{id}/stream", get(routes::ws_session_handler))
234 .route("/", get(routes::serve_index))
236 .route("/{file}", get(routes::serve_static))
237 .merge(crate::xagent::router());
239 let app = match &thq_enrollment {
243 Some(enr) => app.merge(thq_register::enroll_route(enr.clone())),
244 None => app,
245 };
246 let enrollment_state = state.clone();
248 let app = app
249 .layer(CorsLayer::permissive())
250 .layer(axum::extract::DefaultBodyLimit::max(10 * 1024 * 1024))
251 .with_state(state);
252
253 let listener = tokio::net::TcpListener::bind(addr).await?;
257 if let Some(enr) = thq_enrollment {
258 enr.spawn(enrollment_state);
259 }
260
261 if use_tls {
262 let _ = rustls::crypto::ring::default_provider().install_default();
266
267 let cert_dir = tls::default_cert_dir();
269 let (cert_path, key_path) = tls::ensure_certs(&cert_dir)?;
270
271 let tls_config = tls::load_tls_config(&cert_path, &key_path)?;
273 let acceptor = tokio_rustls::TlsAcceptor::from(std::sync::Arc::new(tls_config));
274
275 tracing::info!("Trustee API listening on https://{}", addr);
276
277 loop {
279 let (tcp_stream, peer_addr) = match listener.accept().await {
280 Ok(stream) => stream,
281 Err(e) => {
282 tracing::warn!("TCP accept failed: {}", e);
283 continue;
284 }
285 };
286
287 let acceptor = acceptor.clone();
288 let app = app.clone();
289
290 tokio::spawn(async move {
291 let tls_stream = match acceptor.accept(tcp_stream).await {
292 Ok(s) => s,
293 Err(e) => {
294 tracing::debug!("TLS accept failed from {}: {}", peer_addr, e);
295 return;
296 }
297 };
298
299 let io = hyper_util::rt::TokioIo::new(tls_stream);
302 let svc = hyper_util::service::TowerToHyperService::new(app);
303
304 let _ = hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new())
305 .serve_connection_with_upgrades(io, svc)
306 .await;
307 });
308 }
309 } else {
310 tracing::info!("Trustee API listening on http://{}", addr);
311 axum::serve(listener, app).await?;
312 }
313
314 Ok(())
315}
316
317struct CedarBoot {
328 authorizer: Option<Arc<pep::cedar::CedarAuthorizer>>,
329 allow_disabled: bool,
334}
335
336pub(crate) fn cedar_boot_decision(
338 auth_configured: bool,
339 cedar_present: bool,
340 allow_disabled: bool,
341) -> Result<(), String> {
342 if !auth_configured {
343 return Ok(());
346 }
347 if cedar_present || allow_disabled {
348 Ok(())
349 } else {
350 Err(
351 "Cedar authorization is REQUIRED in web mode (fail-closed, nghr 645809c3). \
352 Either configure it: [cedar] enabled = true (policies ship embedded), \
353 or explicitly opt out per environment: [cedar] allow_disabled = true."
354 .to_string(),
355 )
356 }
357}
358
359async fn parse_cedar_config(config_toml: &str) -> Result<CedarBoot, String> {
360 let parsed: Option<toml::Table> = toml::from_str(config_toml).ok();
361 let cedar_table = parsed.as_ref().and_then(|t| t.get("cedar"));
362 let allow_disabled = cedar_table
363 .and_then(|c| c.get("allow_disabled"))
364 .and_then(|v| v.as_bool())
365 .unwrap_or(false);
366
367 let Some(cedar_section) = cedar_table.and_then(|c| c.as_table().cloned()) else {
368 return Ok(CedarBoot {
369 authorizer: None,
370 allow_disabled,
371 });
372 };
373 let enabled = cedar_section
374 .get("enabled")
375 .and_then(|v| v.as_bool())
376 .unwrap_or(false);
377
378 if !enabled {
379 tracing::debug!("Cedar authorization disabled (default)");
380 return Ok(CedarBoot {
381 authorizer: None,
382 allow_disabled,
383 });
384 }
385
386 tracing::info!("Cedar authorization enabled — initializing authorizer");
387
388 let agent_name = parsed
391 .as_ref()
392 .and_then(|t| t.get("agent"))
393 .and_then(|a| a.as_table())
394 .and_then(|a| a.get("name"))
395 .and_then(|n| n.as_str())
396 .unwrap_or("trustee");
397
398 let home_policies_dir = dirs::home_dir()
399 .map(|h| h.join(format!(".{}", agent_name)).join("policies"))
400 .unwrap_or_else(|| std::path::PathBuf::from("/nonexistent"));
401
402 let default_policy_path = home_policies_dir.join("trustee_default.cedar");
403 let default_schema_path = home_policies_dir.join("trustee_schema.cedarschema");
404
405 let policy_path = cedar_section
406 .get("policy_path")
407 .and_then(|v| v.as_str())
408 .filter(|s| !s.is_empty())
409 .map(std::path::PathBuf::from)
410 .unwrap_or(default_policy_path);
411
412 let schema_path = cedar_section
413 .get("schema_path")
414 .and_then(|v| v.as_str())
415 .filter(|s| !s.is_empty())
416 .map(std::path::PathBuf::from)
417 .or_else(|| Some(default_schema_path));
418
419 let policy_store_url = cedar_section
420 .get("policy_store_url")
421 .and_then(|v| v.as_str())
422 .map(String::from);
423
424 let policy_store_token = cedar_section
425 .get("policy_store_token")
426 .and_then(|v| v.as_str())
427 .map(String::from);
428
429 let cedar_config = pep::cedar::CedarConfig {
430 policy_path,
431 schema_path,
432 entities_path: None,
433 default_decision: pep::cedar::DefaultDecision::Deny,
434 validate_on_load: true,
435 policy_store_url,
436 policy_store_token,
437 embedded_policy: Some(EMBEDDED_CEDAR_POLICY),
438 embedded_schema: Some(EMBEDDED_CEDAR_SCHEMA),
439 };
440
441 match pep::cedar::CedarAuthorizer::new_with_policy_store(cedar_config).await {
442 Ok(auth) => {
443 tracing::info!("Cedar authorizer initialized successfully");
444 Ok(CedarBoot {
445 authorizer: Some(Arc::new(auth)),
446 allow_disabled,
447 })
448 }
449 Err(e) => {
453 let msg = format!(
454 "Cedar authorization is enabled but FAILED to initialize: {e}. \
455 Refusing to boot (fail-closed). Fix the policy/schema configuration \
456 or explicitly set [cedar] allow_disabled = true to run identity-only."
457 );
458 tracing::error!("{msg}");
459 Err(msg)
460 }
461 }
462}