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