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
42#[cfg(test)]
60mod test_home_isolation {
61 #[ctor::ctor]
62 fn isolate_test_home() {
63 let scratch = std::env::temp_dir()
64 .join(format!("trustee-test-home-{}", std::process::id()));
65 let _ = std::fs::create_dir_all(&scratch);
66 std::env::set_var("HOME", &scratch);
67 }
68}
69
70const EMBEDDED_CEDAR_POLICY: &str = include_str!("../policies/trustee_default.cedar");
72const EMBEDDED_CEDAR_SCHEMA: &str = include_str!("../policies/trustee_schema.cedarschema");
73
74use std::net::SocketAddr;
75use std::sync::Arc;
76
77use anyhow::Result;
78use axum::routing::{get, post};
79use tower_http::cors::CorsLayer;
80
81pub use auth::{AuthConfig, AuthState};
82pub use state::ServerState;
83
84pub async fn run(
96 config_toml: String,
97 secrets: std::collections::HashMap<String, String>,
98 build_info: trustee_core::types::BuildInfo,
99 addr: SocketAddr,
100 use_tls: bool,
101) -> Result<()> {
102 let auth_state = if let Some(cfg) = AuthConfig::from_toml(&config_toml) {
104 let is_dev = cfg.dev_config.local_dev_mode;
105 tracing::info!(
106 "Auth enabled: {} mode, issuer={}",
107 if is_dev { "development" } else { "production" },
108 cfg.issuer_url
109 );
110
111 let cedar_boot = parse_cedar_config(&config_toml)
113 .await
114 .map_err(|e| anyhow::anyhow!("{e}"))?;
115 cedar_boot_decision(
116 true,
117 cedar_boot.authorizer.is_some(),
118 cedar_boot.allow_disabled,
119 )
120 .map_err(|e| anyhow::anyhow!("{e}"))?;
121
122 let mut issuer_fallbacks = crate::state::service_issuers_from_config(&config_toml);
125 for si in crate::thq_dispatch::discover_service_issuers() {
126 if !issuer_fallbacks.contains(&si) {
127 issuer_fallbacks.push(si);
128 }
129 }
130 issuer_fallbacks.retain(|si| *si != cfg.issuer_url);
131 if !issuer_fallbacks.is_empty() {
132 tracing::info!("Auth issuer fallbacks armed: {:?}", issuer_fallbacks);
133 }
134 Some(Arc::new(
135 AuthState::with_cedar(cfg, cedar_boot.authorizer)
136 .with_issuer_fallbacks(issuer_fallbacks),
137 ))
138 } else {
139 tracing::warn!("AUTH NOT CONFIGURED: trustee-web is running WITHOUT authentication or Cedar authorization (no [oidc]/[dev] section). Never expose this to a network.");
141 None
142 };
143
144 let thq_enrollment = match thq_register::ThqConfig::from_toml(&config_toml) {
148 Ok(None) => None,
149 Err(e) => {
150 tracing::error!("THQ enrollment DISABLED — [thq] is malformed: {e}");
151 None
152 }
153 Ok(Some(cfg)) => Some(thq_register::Enrollment::new(cfg)),
154 };
155
156 let config_toml_for_state = config_toml.clone();
158 let secrets_for_state = secrets.clone();
159 let build_info_for_state = build_info.clone();
160 let (mut session, workflow_rx) = trustee_core::session::Session::new();
161 session.config_toml = Some(config_toml);
162 session.secrets = Some(secrets);
163 session.build_info = Some(build_info);
164 session.parse_auto_handoff_config();
165
166 if let Some(ref config_toml_str) = session.config_toml {
168 if let Ok(table) = config_toml_str.parse::<toml::Value>() {
169 if let Some(name) = table
170 .get("agent")
171 .and_then(|a| a.get("name"))
172 .and_then(|n| n.as_str())
173 {
174 session.agent_name = name.to_string();
175 }
176 }
177 }
178
179 let (ws_tx, _ws_rx) = tokio::sync::broadcast::channel::<String>(256);
181
182 let (max_sessions, allow_llm_overlay) = {
185 let config_str: &str = &config_toml_for_state;
186 match toml::from_str::<toml::Value>(config_str) {
187 Ok(v) => {
188 let max_sessions = v
189 .get("web")
190 .and_then(|w| w.as_table())
191 .and_then(|w| w.get("max_sessions_per_user").and_then(|v| v.as_integer()))
192 .map(|v| v as usize)
193 .unwrap_or(4);
194 let allow_llm_overlay = v
195 .get("users")
196 .and_then(|u| u.as_table())
197 .and_then(|u| u.get("allow_llm_overlay").and_then(|v| v.as_bool()))
198 .unwrap_or(false);
199 (max_sessions, allow_llm_overlay)
200 }
201 Err(_) => (4, false),
202 }
203 };
204
205 let state = ServerState::new(session, ws_tx, auth_state)
206 .with_config_toml(config_toml_for_state)
207 .with_secrets(secrets_for_state)
208 .with_build_info(build_info_for_state)
209 .with_max_sessions_per_user(max_sessions)
210 .with_allow_llm_overlay(allow_llm_overlay);
211
212 state.clone().spawn_drain_task(workflow_rx);
214
215 thq_dispatch::populate(state.clone());
219
220 let app = axum::Router::new()
228 .route("/api/v1/health", get(routes::health))
230 .nest("/auth", auth::auth_routes())
231 .route("/api/v1/models", get(routes::list_models))
233 .route(
244 "/api/v1/sessions",
245 get(routes::list_sessions).post(routes::create_session),
246 )
247 .route("/api/v1/sessions/live", get(routes::list_live_sessions))
248 .route(
249 "/api/v1/sessions/{id}",
250 get(routes::get_session_detail).delete(routes::destroy_session),
251 )
252 .route("/api/v1/sessions/{id}/live", get(routes::get_live_session))
253 .route("/api/v1/sessions/{id}/resume", post(routes::resume_session))
254 .route("/api/v1/sessions/{id}/fork", post(routes::fork_session))
255 .route(
256 "/api/v1/sessions/{id}/history",
257 get(routes::get_session_history),
258 )
259 .route(
261 "/api/v1/sessions/{id}/command",
262 post(routes::post_command_session).layer(axum::extract::DefaultBodyLimit::max(
263 routes::ATTACH_BODY_LIMIT,
264 )),
265 )
266 .route(
267 "/api/v1/sessions/{id}/cancel",
268 post(routes::post_cancel_session),
269 )
270 .route(
271 "/api/v1/sessions/{id}/handoff",
272 post(routes::post_handoff_session),
273 )
274 .route(
275 "/api/v1/sessions/{id}/name",
276 post(routes::set_session_name_session),
277 )
278 .route(
279 "/api/v1/sessions/{id}/stream",
280 get(routes::ws_session_handler),
281 )
282 .route("/", get(routes::serve_index))
284 .route("/{file}", get(routes::serve_static))
285 .merge(crate::xagent::router());
287 let app = match &thq_enrollment {
291 Some(enr) => app.merge(thq_register::enroll_route(enr.clone())),
292 None => app,
293 };
294 let enrollment_state = state.clone();
296 let app = app
297 .layer(CorsLayer::permissive())
298 .layer(axum::extract::DefaultBodyLimit::max(10 * 1024 * 1024))
299 .with_state(state);
300
301 let listener = tokio::net::TcpListener::bind(addr).await?;
305 if let Some(enr) = thq_enrollment {
306 enr.spawn(enrollment_state);
307 }
308
309 if use_tls {
310 let _ = rustls::crypto::ring::default_provider().install_default();
314
315 let cert_dir = tls::default_cert_dir();
317 let (cert_path, key_path) = tls::ensure_certs(&cert_dir)?;
318
319 let tls_config = tls::load_tls_config(&cert_path, &key_path)?;
321 let acceptor = tokio_rustls::TlsAcceptor::from(std::sync::Arc::new(tls_config));
322
323 tracing::info!("Trustee API listening on https://{}", addr);
324
325 loop {
327 let (tcp_stream, peer_addr) = match listener.accept().await {
328 Ok(stream) => stream,
329 Err(e) => {
330 tracing::warn!("TCP accept failed: {}", e);
331 continue;
332 }
333 };
334
335 let acceptor = acceptor.clone();
336 let app = app.clone();
337
338 tokio::spawn(async move {
339 let tls_stream = match acceptor.accept(tcp_stream).await {
340 Ok(s) => s,
341 Err(e) => {
342 tracing::debug!("TLS accept failed from {}: {}", peer_addr, e);
343 return;
344 }
345 };
346
347 let io = hyper_util::rt::TokioIo::new(tls_stream);
350 let svc = hyper_util::service::TowerToHyperService::new(app);
351
352 let _ = hyper_util::server::conn::auto::Builder::new(
353 hyper_util::rt::TokioExecutor::new(),
354 )
355 .serve_connection_with_upgrades(io, svc)
356 .await;
357 });
358 }
359 } else {
360 tracing::info!("Trustee API listening on http://{}", addr);
361 axum::serve(listener, app).await?;
362 }
363
364 Ok(())
365}
366
367struct CedarBoot {
378 authorizer: Option<Arc<pep::cedar::CedarAuthorizer>>,
379 allow_disabled: bool,
384}
385
386pub(crate) fn cedar_boot_decision(
388 auth_configured: bool,
389 cedar_present: bool,
390 allow_disabled: bool,
391) -> Result<(), String> {
392 if !auth_configured {
393 return Ok(());
396 }
397 if cedar_present || allow_disabled {
398 Ok(())
399 } else {
400 Err(
401 "Cedar authorization is REQUIRED in web mode (fail-closed, nghr 645809c3). \
402 Either configure it: [cedar] enabled = true (policies ship embedded), \
403 or explicitly opt out per environment: [cedar] allow_disabled = true."
404 .to_string(),
405 )
406 }
407}
408
409pub(crate) fn audit_policy_action_skew(policy_text: &str, schema_text: &str) -> Vec<String> {
419 let referenced = policy_action_refs(policy_text);
420 let declared = schema_action_decls(schema_text);
421 referenced.difference(&declared).cloned().collect()
422}
423
424fn policy_action_refs(policy_text: &str) -> std::collections::BTreeSet<String> {
429 let code: String = policy_text
430 .lines()
431 .map(|l| match l.find("//") {
432 Some(pos) => &l[..pos],
433 None => l,
434 })
435 .collect::<Vec<_>>()
436 .join("\n");
437 let mut out = std::collections::BTreeSet::new();
438 let mut rest = code.as_str();
439 while let Some(pos) = rest.find("Action::\"") {
440 rest = &rest[pos + "Action::\"".len()..];
441 match rest.find('"') {
442 Some(end) => {
443 out.insert(rest[..end].to_string());
444 rest = &rest[end..];
445 }
446 None => break,
447 }
448 }
449 out
450}
451
452fn schema_action_decls(schema_text: &str) -> std::collections::BTreeSet<String> {
455 let mut out = std::collections::BTreeSet::new();
456 for line in schema_text.lines() {
457 let line = line.trim_start();
458 if let Some(rest) = line.strip_prefix("action ") {
459 let name: String = rest
460 .chars()
461 .take_while(|c| !c.is_whitespace() && *c != ';')
462 .collect();
463 if !name.is_empty() {
464 out.insert(name);
465 }
466 }
467 }
468 out
469}
470
471pub(crate) fn log_policy_action_skew(source: &str, policy_text: &str, schema_text: &str) -> Vec<String> {
475 let unknown = audit_policy_action_skew(policy_text, schema_text);
476 if !unknown.is_empty() {
477 for action in &unknown {
482 tracing::error!(
483 "Cedar POLICY/BINARY SKEW ({source}): policy references action Action::\"{action}\" which this binary's schema does NOT declare — the deployed policy files predate (or postdate) this binary's action set. Fix: align the policy files with the binary's schema (the embedded pair is authoritative), or update the binary."
484 );
485 }
486 tracing::error!(
487 "Cedar POLICY/BINARY SKEW ({source}): {} unknown action(s) total: {:?}",
488 unknown.len(),
489 unknown
490 );
491 }
492 unknown
493}
494
495async fn parse_cedar_config(config_toml: &str) -> Result<CedarBoot, String> {
496 let parsed: Option<toml::Table> = toml::from_str(config_toml).ok();
497 let cedar_table = parsed.as_ref().and_then(|t| t.get("cedar"));
498 let allow_disabled = cedar_table
499 .and_then(|c| c.get("allow_disabled"))
500 .and_then(|v| v.as_bool())
501 .unwrap_or(false);
502
503 let Some(cedar_section) = cedar_table.and_then(|c| c.as_table().cloned()) else {
504 return Ok(CedarBoot {
505 authorizer: None,
506 allow_disabled,
507 });
508 };
509 let enabled = cedar_section
510 .get("enabled")
511 .and_then(|v| v.as_bool())
512 .unwrap_or(false);
513
514 if !enabled {
515 tracing::debug!("Cedar authorization disabled (default)");
516 return Ok(CedarBoot {
517 authorizer: None,
518 allow_disabled,
519 });
520 }
521
522 tracing::info!("Cedar authorization enabled — initializing authorizer");
523
524 let agent_name = parsed
527 .as_ref()
528 .and_then(|t| t.get("agent"))
529 .and_then(|a| a.as_table())
530 .and_then(|a| a.get("name"))
531 .and_then(|n| n.as_str())
532 .unwrap_or("trustee");
533
534 let home_policies_dir = dirs::home_dir()
535 .map(|h| h.join(format!(".{}", agent_name)).join("policies"))
536 .unwrap_or_else(|| std::path::PathBuf::from("/nonexistent"));
537
538 let default_policy_path = home_policies_dir.join("trustee_default.cedar");
539 let default_schema_path = home_policies_dir.join("trustee_schema.cedarschema");
540
541 let policy_path = cedar_section
542 .get("policy_path")
543 .and_then(|v| v.as_str())
544 .filter(|s| !s.is_empty())
545 .map(std::path::PathBuf::from)
546 .unwrap_or(default_policy_path);
547
548 let schema_path = cedar_section
549 .get("schema_path")
550 .and_then(|v| v.as_str())
551 .filter(|s| !s.is_empty())
552 .map(std::path::PathBuf::from)
553 .or_else(|| Some(default_schema_path));
554
555 let policy_store_url = cedar_section
556 .get("policy_store_url")
557 .and_then(|v| v.as_str())
558 .map(String::from);
559
560 let policy_store_token = cedar_section
561 .get("policy_store_token")
562 .and_then(|v| v.as_str())
563 .map(String::from);
564
565 log_policy_action_skew("embedded", EMBEDDED_CEDAR_POLICY, EMBEDDED_CEDAR_SCHEMA);
572 if policy_path.exists() && schema_path.as_ref().is_some_and(|p| p.exists()) {
573 match (
574 std::fs::read_to_string(&policy_path),
575 schema_path.as_ref().and_then(|p| std::fs::read_to_string(p).ok()),
576 ) {
577 (Ok(policy_text), Some(schema_text)) => {
578 log_policy_action_skew(
579 &format!("filesystem {}", policy_path.display()),
580 &policy_text,
581 &schema_text,
582 );
583 }
584 _ => {
585 tracing::warn!(
586 "Cedar skew guard: policy file {} exists but the schema file is unreadable — the audit ran on the embedded pair only",
587 policy_path.display()
588 );
589 }
590 }
591 }
592
593 let cedar_config = pep::cedar::CedarConfig {
594 policy_path,
595 schema_path,
596 entities_path: None,
597 default_decision: pep::cedar::DefaultDecision::Deny,
598 validate_on_load: true,
599 policy_store_url,
600 policy_store_token,
601 embedded_policy: Some(EMBEDDED_CEDAR_POLICY),
602 embedded_schema: Some(EMBEDDED_CEDAR_SCHEMA),
603 };
604
605 match pep::cedar::CedarAuthorizer::new_with_policy_store(cedar_config).await {
606 Ok(auth) => {
607 tracing::info!("Cedar authorizer initialized successfully");
608 Ok(CedarBoot {
609 authorizer: Some(Arc::new(auth)),
610 allow_disabled,
611 })
612 }
613 Err(e) => {
617 let msg = format!(
618 "Cedar authorization is enabled but FAILED to initialize: {e}. \
619 Refusing to boot (fail-closed). Fix the policy/schema configuration \
620 or explicitly set [cedar] allow_disabled = true to run identity-only."
621 );
622 tracing::error!("{msg}");
623 Err(msg)
624 }
625 }
626}