1pub mod auth;
11pub mod identity;
12mod materialize;
13mod routes;
14mod state;
15mod thq_dispatch;
16mod thq_register;
17pub mod tls;
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
142 .get("agent")
143 .and_then(|a| a.get("name"))
144 .and_then(|n| n.as_str())
145 {
146 session.agent_name = name.to_string();
147 }
148 }
149 }
150
151 let (ws_tx, _ws_rx) = tokio::sync::broadcast::channel::<String>(256);
153
154 let (max_sessions, allow_llm_overlay) = {
157 let config_str: &str = &config_toml_for_state;
158 match toml::from_str::<toml::Value>(config_str) {
159 Ok(v) => {
160 let max_sessions = v
161 .get("web")
162 .and_then(|w| w.as_table())
163 .and_then(|w| w.get("max_sessions_per_user").and_then(|v| v.as_integer()))
164 .map(|v| v as usize)
165 .unwrap_or(4);
166 let allow_llm_overlay = v
167 .get("users")
168 .and_then(|u| u.as_table())
169 .and_then(|u| u.get("allow_llm_overlay").and_then(|v| v.as_bool()))
170 .unwrap_or(false);
171 (max_sessions, allow_llm_overlay)
172 }
173 Err(_) => (4, false),
174 }
175 };
176
177 let state = ServerState::new(session, ws_tx, auth_state)
178 .with_config_toml(config_toml_for_state)
179 .with_secrets(secrets_for_state)
180 .with_build_info(build_info_for_state)
181 .with_max_sessions_per_user(max_sessions)
182 .with_allow_llm_overlay(allow_llm_overlay);
183
184 state.clone().spawn_drain_task(workflow_rx);
186
187 thq_dispatch::populate(state.clone());
191
192 let app = axum::Router::new()
200 .route("/api/v1/health", get(routes::health))
202 .nest("/auth", auth::auth_routes())
203 .route("/api/v1/models", get(routes::list_models))
205 .route(
216 "/api/v1/sessions",
217 get(routes::list_sessions).post(routes::create_session),
218 )
219 .route("/api/v1/sessions/live", get(routes::list_live_sessions))
220 .route(
221 "/api/v1/sessions/{id}",
222 get(routes::get_session_detail).delete(routes::destroy_session),
223 )
224 .route("/api/v1/sessions/{id}/live", get(routes::get_live_session))
225 .route("/api/v1/sessions/{id}/resume", post(routes::resume_session))
226 .route(
227 "/api/v1/sessions/{id}/history",
228 get(routes::get_session_history),
229 )
230 .route(
232 "/api/v1/sessions/{id}/command",
233 post(routes::post_command_session).layer(axum::extract::DefaultBodyLimit::max(
234 routes::ATTACH_BODY_LIMIT,
235 )),
236 )
237 .route(
238 "/api/v1/sessions/{id}/cancel",
239 post(routes::post_cancel_session),
240 )
241 .route(
242 "/api/v1/sessions/{id}/handoff",
243 post(routes::post_handoff_session),
244 )
245 .route(
246 "/api/v1/sessions/{id}/name",
247 post(routes::set_session_name_session),
248 )
249 .route(
250 "/api/v1/sessions/{id}/stream",
251 get(routes::ws_session_handler),
252 )
253 .route("/", get(routes::serve_index))
255 .route("/{file}", get(routes::serve_static))
256 .merge(crate::xagent::router());
258 let app = match &thq_enrollment {
262 Some(enr) => app.merge(thq_register::enroll_route(enr.clone())),
263 None => app,
264 };
265 let enrollment_state = state.clone();
267 let app = app
268 .layer(CorsLayer::permissive())
269 .layer(axum::extract::DefaultBodyLimit::max(10 * 1024 * 1024))
270 .with_state(state);
271
272 let listener = tokio::net::TcpListener::bind(addr).await?;
276 if let Some(enr) = thq_enrollment {
277 enr.spawn(enrollment_state);
278 }
279
280 if use_tls {
281 let _ = rustls::crypto::ring::default_provider().install_default();
285
286 let cert_dir = tls::default_cert_dir();
288 let (cert_path, key_path) = tls::ensure_certs(&cert_dir)?;
289
290 let tls_config = tls::load_tls_config(&cert_path, &key_path)?;
292 let acceptor = tokio_rustls::TlsAcceptor::from(std::sync::Arc::new(tls_config));
293
294 tracing::info!("Trustee API listening on https://{}", addr);
295
296 loop {
298 let (tcp_stream, peer_addr) = match listener.accept().await {
299 Ok(stream) => stream,
300 Err(e) => {
301 tracing::warn!("TCP accept failed: {}", e);
302 continue;
303 }
304 };
305
306 let acceptor = acceptor.clone();
307 let app = app.clone();
308
309 tokio::spawn(async move {
310 let tls_stream = match acceptor.accept(tcp_stream).await {
311 Ok(s) => s,
312 Err(e) => {
313 tracing::debug!("TLS accept failed from {}: {}", peer_addr, e);
314 return;
315 }
316 };
317
318 let io = hyper_util::rt::TokioIo::new(tls_stream);
321 let svc = hyper_util::service::TowerToHyperService::new(app);
322
323 let _ = hyper_util::server::conn::auto::Builder::new(
324 hyper_util::rt::TokioExecutor::new(),
325 )
326 .serve_connection_with_upgrades(io, svc)
327 .await;
328 });
329 }
330 } else {
331 tracing::info!("Trustee API listening on http://{}", addr);
332 axum::serve(listener, app).await?;
333 }
334
335 Ok(())
336}
337
338struct CedarBoot {
349 authorizer: Option<Arc<pep::cedar::CedarAuthorizer>>,
350 allow_disabled: bool,
355}
356
357pub(crate) fn cedar_boot_decision(
359 auth_configured: bool,
360 cedar_present: bool,
361 allow_disabled: bool,
362) -> Result<(), String> {
363 if !auth_configured {
364 return Ok(());
367 }
368 if cedar_present || allow_disabled {
369 Ok(())
370 } else {
371 Err(
372 "Cedar authorization is REQUIRED in web mode (fail-closed, nghr 645809c3). \
373 Either configure it: [cedar] enabled = true (policies ship embedded), \
374 or explicitly opt out per environment: [cedar] allow_disabled = true."
375 .to_string(),
376 )
377 }
378}
379
380async fn parse_cedar_config(config_toml: &str) -> Result<CedarBoot, String> {
381 let parsed: Option<toml::Table> = toml::from_str(config_toml).ok();
382 let cedar_table = parsed.as_ref().and_then(|t| t.get("cedar"));
383 let allow_disabled = cedar_table
384 .and_then(|c| c.get("allow_disabled"))
385 .and_then(|v| v.as_bool())
386 .unwrap_or(false);
387
388 let Some(cedar_section) = cedar_table.and_then(|c| c.as_table().cloned()) else {
389 return Ok(CedarBoot {
390 authorizer: None,
391 allow_disabled,
392 });
393 };
394 let enabled = cedar_section
395 .get("enabled")
396 .and_then(|v| v.as_bool())
397 .unwrap_or(false);
398
399 if !enabled {
400 tracing::debug!("Cedar authorization disabled (default)");
401 return Ok(CedarBoot {
402 authorizer: None,
403 allow_disabled,
404 });
405 }
406
407 tracing::info!("Cedar authorization enabled — initializing authorizer");
408
409 let agent_name = parsed
412 .as_ref()
413 .and_then(|t| t.get("agent"))
414 .and_then(|a| a.as_table())
415 .and_then(|a| a.get("name"))
416 .and_then(|n| n.as_str())
417 .unwrap_or("trustee");
418
419 let home_policies_dir = dirs::home_dir()
420 .map(|h| h.join(format!(".{}", agent_name)).join("policies"))
421 .unwrap_or_else(|| std::path::PathBuf::from("/nonexistent"));
422
423 let default_policy_path = home_policies_dir.join("trustee_default.cedar");
424 let default_schema_path = home_policies_dir.join("trustee_schema.cedarschema");
425
426 let policy_path = cedar_section
427 .get("policy_path")
428 .and_then(|v| v.as_str())
429 .filter(|s| !s.is_empty())
430 .map(std::path::PathBuf::from)
431 .unwrap_or(default_policy_path);
432
433 let schema_path = cedar_section
434 .get("schema_path")
435 .and_then(|v| v.as_str())
436 .filter(|s| !s.is_empty())
437 .map(std::path::PathBuf::from)
438 .or_else(|| Some(default_schema_path));
439
440 let policy_store_url = cedar_section
441 .get("policy_store_url")
442 .and_then(|v| v.as_str())
443 .map(String::from);
444
445 let policy_store_token = cedar_section
446 .get("policy_store_token")
447 .and_then(|v| v.as_str())
448 .map(String::from);
449
450 let cedar_config = pep::cedar::CedarConfig {
451 policy_path,
452 schema_path,
453 entities_path: None,
454 default_decision: pep::cedar::DefaultDecision::Deny,
455 validate_on_load: true,
456 policy_store_url,
457 policy_store_token,
458 embedded_policy: Some(EMBEDDED_CEDAR_POLICY),
459 embedded_schema: Some(EMBEDDED_CEDAR_SCHEMA),
460 };
461
462 match pep::cedar::CedarAuthorizer::new_with_policy_store(cedar_config).await {
463 Ok(auth) => {
464 tracing::info!("Cedar authorizer initialized successfully");
465 Ok(CedarBoot {
466 authorizer: Some(Arc::new(auth)),
467 allow_disabled,
468 })
469 }
470 Err(e) => {
474 let msg = format!(
475 "Cedar authorization is enabled but FAILED to initialize: {e}. \
476 Refusing to boot (fail-closed). Fix the policy/schema configuration \
477 or explicitly set [cedar] allow_disabled = true to run identity-only."
478 );
479 tracing::error!("{msg}");
480 Err(msg)
481 }
482 }
483}