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 identity;
12mod materialize;
13mod routes;
14mod state;
15mod thq_dispatch;
16mod thq_register;
17pub mod tls;
18pub mod xagent;
19
20/// The BIN's version, injected by the `trustee` binary at startup
21/// ([`set_bin_version`]) — the web UI's burger-menu footer displays it.
22/// Falls back to this crate's version when unset (trustee-api embedded
23/// elsewhere without a bin).
24static BIN_VERSION: std::sync::OnceLock<String> = std::sync::OnceLock::new();
25
26/// Called by the `trustee` binary so the web UI can show the real product
27/// version (the binary's — what `trustee --version` prints), not
28/// trustee-api's crate version. First call wins; a restart is a new process.
29pub fn set_bin_version(v: &str) {
30    let _ = BIN_VERSION.set(v.to_string());
31}
32
33/// The version label for the web UI: the bin's version if injected, else
34/// this crate's.
35pub 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// ── Test-process HOME isolation (the 456-folder leak) ────────────────────
43//
44// OWNER REPORT 2026-11-22: ~/.trustee/users held 456 folders on an
45// 18-profile runtime. Root cause: the test fixtures (TempUser & friends,
46// keyed by `std::process::id()`) resolved `dirs::home_dir()` — every
47// `cargo test` run minted a fresh set of ghost `users/{hash}` folders in
48// the REAL home (456 folders ≈ every gate run since the users/ namespace
49// shipped; the mtime histogram matches ship days exactly, and a disk
50// tombstone carried a test fixture's literal chain id).
51//
52// FIX: a ctor runs before main → before any test thread spawns → the
53// set_var below is race-free (single-threaded at that point). The whole
54// test binary then resolves HOME to a fresh per-run scratch dir; the
55// pid-keyed fixtures keep their cross-run isolation semantics, just under
56// /tmp instead of the real home. Zero prod impact: cfg(test) + dev-dep.
57// The `trustee-test-home-*` scratch class is swept like every other
58// per-pid test-residue class.
59#[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
70// Embedded Cedar policy defaults (compiled into binary)
71const 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
84/// Run the API server.
85///
86/// Creates a `Session` with the given config, starts a background task to
87/// drain workflow messages and broadcast them to WebSocket clients, then
88/// serves the REST + WebSocket + static files on `addr`.
89///
90/// If `[oidc]` or `[dev]` sections are found in the config TOML, auth is
91/// enabled — all `/api/v1/*` endpoints (except health) require a valid token.
92///
93/// By default serves over HTTPS using a self-signed certificate from
94/// `~/.trustee/certs/`. If `use_tls` is false, serves plain HTTP.
95pub 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    // Parse auth config from TOML (returns None if no [oidc] or [dev] sections)
103    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        // Parse Cedar authorization config (P2: fail-closed on init failure)
112        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        // 16F: teach auth about the service-account issuer candidates so
123        // agent tokens (minted on service vhosts) validate in check_auth.
124        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        // Open mode — loud, by design (local/dev posture preserved).
140        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    // THQ enrollment (v0.3 runtime lane): parse before config_toml is
145    // moved into the session. No [thq] = lane off; malformed = LOUD +
146    // lane off (never a silent skip; no compat translation of old keys).
147    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    // Build the session — keep copies of secrets/build_info for per-user sessions
157    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    // Extract agent name from config TOML for stateless operation
167    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    // Create the broadcast channel for WebSocket fan-out
180    let (ws_tx, _ws_rx) = tokio::sync::broadcast::channel::<String>(256);
181
182    // Wrap session in shared state (with shared config/secrets/build_info for per-user sessions)
183    // Parse knobs: [web].max_sessions_per_user, [users].allow_llm_overlay
184    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    // Start background message drain task (owns workflow_rx directly — no deadlock)
213    state.clone().spawn_drain_task(workflow_rx);
214
215    // 16F: per-agent dispatch table from per-user [thq] overlays — the
216    // dispatch lane is UNCHANGED by the 0.15.0 enrollment rewrite
217    // (different concept: agents-as-users vs the runtime-the-process).
218    thq_dispatch::populate(state.clone());
219
220    // Build router
221    //
222    // Auth middleware approach: since axum 0.8's from_fn_with_state has
223    // trait bound issues with nested routers, we apply auth checking at
224    // the handler level via a helper. Each protected route's handler
225    // calls auth::check_auth() first. This is simpler and avoids type
226    // complexity.
227    let app = axum::Router::new()
228        // Public routes
229        .route("/api/v1/health", get(routes::health))
230        .nest("/auth", auth::auth_routes())
231        // Protected API routes
232        .route("/api/v1/models", get(routes::list_models))
233        // LEGACY ACTIVE-SESSION ROUTES RETIRED (2026-10-27, owner order):
234        // /api/v1/session, /session/command, /session/cancel, /session/handoff,
235        // /session/stream, /session/name, /session/new, /project/name — the
236        // mutable active-pointer surface. Every consumer is session-scoped
237        // (THQ console, trustee-web, Android app post-4801f26); the pointer
238        // machinery (ensure_active_session / active_session_id) is removed
239        // with them — it was the root of the resumed-session bug class
240        // (22f8745e).
241        // Session discovery & resume
242        // Session discovery & resume (checkpoint-based, existing)
243        .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        // MSU: session-scoped live routes
260        .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        // Static files from trustee-web
283        .route("/", get(routes::serve_index))
284        .route("/{file}", get(routes::serve_static))
285        // 16F: per-agent THQ dispatch surface (impersonation by Bearer swap)
286        .merge(crate::xagent::router());
287    // THQ v0.3 enrollment callback lane: THQ POSTs the runtime secret
288    // here (register → /thq/enroll → pull/state loop). No [thq] config
289    // → no route (404 for would-be enroll callers).
290    let app = match &thq_enrollment {
291        Some(enr) => app.merge(thq_register::enroll_route(enr.clone())),
292        None => app,
293    };
294    // state clone for the enrollment loop (with_state below consumes it)
295    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    // Bind BEFORE starting the enrollment loop: register's callback must
302    // land on a live /thq/enroll route (otherwise the first register
303    // wastes its callback and the loop self-heals a cycle later).
304    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        // Install ring as the process-level crypto provider (required when
311        // rustls is built with default-features=false to avoid ambiguity
312        // with aws-lc-rs pulled in transitively by other crates).
313        let _ = rustls::crypto::ring::default_provider().install_default();
314
315        // Ensure self-signed certs exist
316        let cert_dir = tls::default_cert_dir();
317        let (cert_path, key_path) = tls::ensure_certs(&cert_dir)?;
318
319        // Load TLS config
320        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        // Manual accept loop — spawn hyper-util auto connection per TLS stream
326        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                // Use hyper-util auto builder with the tower service from axum.
348                // serve_connection_with_upgrades is required for WebSocket support.
349                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
367/// Parse [cedar] section from config TOML and create a CedarAuthorizer if enabled.
368///
369/// Configuration:
370/// - `[cedar] enabled = true/false` (default: false)
371/// - `[cedar] policy_path = "/path/to/policies.cedar"` (filesystem override)
372/// - `[cedar] schema_path = "/path/to/schema.cedarschema"` (filesystem override)
373/// - `[cedar] policy_store_url = "https://..."` (remote policy store)
374///
375/// When enabled without filesystem paths, uses embedded defaults.
376/// P2 boot result for Cedar (nghr 645809c3).
377struct CedarBoot {
378    authorizer: Option<Arc<pep::cedar::CedarAuthorizer>>,
379    /// Explicit per-environment escape hatch: `[cedar] allow_disabled = true`
380    /// opts THIS deployment into identity-only mode (Cedar absent). The
381    /// DEFAULT is fail-closed: web mode with auth configured refuses to
382    /// boot without a working Cedar authorizer.
383    allow_disabled: bool,
384}
385
386/// Pure decision for the P2 fail-closed posture — unit-tested.
387pub(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        // Open mode (no [oidc]/[dev]) — preserved for local/dev usage; the
394        // absence of auth is logged loudly at boot.
395        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
409/// THE POLICY/BINARY SKEW GUARD (the eynak boot-1 refusal class, 2026-10-31):
410/// a deployed filesystem policy override can reference actions the binary's
411/// schema doesn't declare — the binary updated its action set, the deployed
412/// policy files didn't, and Cedar's validate_on_load refused the boot
413/// fail-closed with a validation error that names the FAILURE, not the SKEW
414/// (the operator's fix was 26s of manual archaeology; the next binary bump
415/// would re-trigger it). This audit names the skew BEFORE the boot dies:
416/// every `Action::"X"` referenced by the policy but not declared by the
417/// schema — loud, one line each, at boot.
418pub(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
424/// Every `Action::"Name"` referenced anywhere in a Cedar policy text
425/// (permit/forbid action clauses and condition clauses alike). `//` comments
426/// are stripped first — a comment may NAME a removed action (the shipped
427/// policy's migration note does) and that is not a reference.
428fn 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
452/// Every action DECLARED by a Cedar schema text (`action Name appliesTo …;`
453/// / `action Name;` — the empty-namespace form this repo ships).
454fn 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
471/// Run the skew audit on a policy/schema pair and log LOUD per unknown
472/// action (the guard's disclosure — never silent). Returns the unknown list
473/// for tests.
474pub(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        // One line per unknown action, naming the source — the operator sees
478        // the skew in seconds, not archaeology. Fail-closed still applies
479        // downstream (validate_on_load refuses the boot); this is the
480        // disclosure that makes the refusal ACTIONABLE.
481        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    // Default policy/schema paths point to ~/{agent_name}/policies/ (created by trustee init).
525    // Agent name is read from [agent] name in config, defaulting to "trustee".
526    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    // THE POLICY/BINARY SKEW GUARD (the eynak boot-1 refusal class): audit
566    // BEFORE the authorizer constructs — the embedded pair always (atomic
567    // ship drift), and the resolved filesystem pair when the files exist
568    // (the deployed-override skew). validate_on_load still refuses the boot
569    // fail-closed downstream; this names the skew so the refusal is
570    // actionable in seconds.
571    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        // FAIL-CLOSED (nghr 645809c3): the v0.1.0–0.1.1 fame bug class —
614        // enabled-but-broken Cedar used to silently disable authorization.
615        // Now the boot dies loudly instead.
616        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}