Skip to main content

trustee_api/
auth.rs

1//! Authentication module for Trustee API.
2//!
3//! Uses PEP for OIDC/OAuth2:
4//! - `ResourceServerClient` for JWT validation (offline, cached JWKS)
5//! - `OidcClient` for authorization code + PKCE login flow
6//! - `PkceCookieManager` for stateless PKCE state (HMAC-signed cookies)
7//! - `DevConfig` for local development bypass
8//!
9//! Two deployment modes:
10//! - **Standalone**: browser hits /auth/login → IdP redirect → /auth/callback → cookie
11//! - **Centralized**: external auth app sends `Authorization: Bearer <token>` directly
12//!
13//! Token extraction order: `Authorization: Bearer` header → `trustee_token` cookie.
14
15use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17use std::sync::Mutex;
18use std::time::Duration as StdDuration;
19
20use crate::identity::IdentityRegistry;
21use axum::{
22    body::Body,
23    extract::{Query, State},
24    http::{header, StatusCode},
25    response::{IntoResponse, Json, Redirect, Response},
26};
27use axum_extra::extract::cookie::{Cookie, SameSite};
28use pep::oidc::pkce_cookie::PkceCookieManager;
29use pep::oidc_client::OidcClient;
30use pep::oidc_resource_server::ResourceServerClient;
31use pep::session_manager::WebSessionManager;
32use pep::{DevConfig, JwtClaims, JwtValidationOptions, OidcClientConfig};
33use serde::Deserialize;
34use sha2::{Digest, Sha256};
35use time::Duration as TimeDuration;
36
37use cedar_policy::{Context, Entities, EntityUid, Request};
38use std::str::FromStr;
39
40// ---------------------------------------------------------------------------
41// Configuration
42// ---------------------------------------------------------------------------
43
44/// Authentication configuration parsed from `[oidc]` and `[dev]` TOML sections.
45#[derive(Debug, Clone)]
46pub struct AuthConfig {
47    /// OIDC provider issuer URL
48    pub issuer_url: String,
49    /// OAuth2 client ID
50    pub client_id: String,
51    /// OAuth2 client secret (None → public client, PKCE only)
52    pub client_secret: Option<String>,
53    /// Redirect URI for OIDC callback
54    pub redirect_uri: String,
55    /// OAuth2 scopes
56    pub scope: String,
57    /// Token cookie name
58    pub cookie_name: String,
59    /// Development mode configuration
60    pub dev_config: DevConfig,
61    /// JWT validation options
62    pub validation_options: JwtValidationOptions,
63    /// Secret for signing PKCE state cookies
64    pub pkce_cookie_secret: String,
65}
66
67impl AuthConfig {
68    /// Parse auth config from the merged trustee TOML string.
69    ///
70    /// Reads `[oidc]` and `[dev]` sections. If neither is present, returns None
71    /// (auth disabled — all endpoints open).
72    pub fn from_toml(config_toml: &str) -> Option<Self> {
73        let table: toml::Table = toml::from_str(config_toml).ok()?;
74
75        // Check for dev mode
76        let dev_config = table
77            .get("dev")
78            .and_then(|d| d.as_table())
79            .map(|d| DevConfig {
80                local_dev_mode: d
81                    .get("local_dev_mode")
82                    .and_then(|v| v.as_bool())
83                    .unwrap_or(false),
84                local_dev_email: d
85                    .get("local_dev_email")
86                    .and_then(|v| v.as_str())
87                    .map(String::from),
88                local_dev_name: d
89                    .get("local_dev_name")
90                    .and_then(|v| v.as_str())
91                    .map(String::from),
92                local_dev_username: d
93                    .get("local_dev_username")
94                    .and_then(|v| v.as_str())
95                    .map(String::from),
96            });
97
98        // Dev mode without OIDC — return early with dev-only config
99        if let Some(ref dc) = dev_config {
100            if dc.local_dev_mode {
101                // Try to get OIDC config too (for login endpoint), but it's optional in dev mode
102                let oidc = Self::parse_oidc_section(&table);
103                return Some(Self {
104                    issuer_url: oidc
105                        .as_ref()
106                        .map(|o| o.0.clone())
107                        .unwrap_or_else(|| "https://auth.example.com".into()),
108                    client_id: oidc
109                        .as_ref()
110                        .map(|o| o.1.clone())
111                        .unwrap_or_else(|| "trustee".into()),
112                    client_secret: oidc.as_ref().and_then(|o| o.2.clone()),
113                    redirect_uri: oidc
114                        .as_ref()
115                        .map(|o| o.3.clone())
116                        .unwrap_or_else(|| "http://localhost:3000/auth/callback".into()),
117                    scope: oidc
118                        .as_ref()
119                        .map(|o| o.4.clone())
120                        .unwrap_or_else(|| "openid profile email".into()),
121                    cookie_name: "trustee_token".into(),
122                    dev_config: dc.clone(),
123                    validation_options: JwtValidationOptions::default(),
124                    pkce_cookie_secret: oidc
125                        .as_ref()
126                        .map(|o| o.6.clone())
127                        .unwrap_or_else(|| "trustee-default-pkce-secret-change-me".into()),
128                });
129            }
130        }
131
132        // Production mode — requires [oidc] section
133        let (
134            issuer_url,
135            client_id,
136            client_secret,
137            redirect_uri,
138            scope,
139            validation_options,
140            pkce_secret,
141        ) = Self::parse_oidc_section(&table)?;
142
143        Some(Self {
144            issuer_url,
145            client_id,
146            client_secret,
147            redirect_uri,
148            scope,
149            cookie_name: "trustee_token".into(),
150            dev_config: dev_config.unwrap_or_default(),
151            validation_options,
152            pkce_cookie_secret: pkce_secret,
153        })
154    }
155
156    /// Parse the `[oidc]` section from a TOML table.
157    /// Returns (issuer_url, client_id, client_secret, redirect_uri, scope, validation_options, pkce_secret).
158    fn parse_oidc_section(
159        table: &toml::Table,
160    ) -> Option<(
161        String,
162        String,
163        Option<String>,
164        String,
165        String,
166        JwtValidationOptions,
167        String,
168    )> {
169        let oidc = table.get("oidc")?.as_table()?;
170
171        let issuer_url = oidc.get("issuer_url")?.as_str()?.to_string();
172        let client_id = oidc.get("client_id")?.as_str()?.to_string();
173        let client_secret = oidc
174            .get("client_secret")
175            .and_then(|v| v.as_str())
176            .map(String::from);
177        let redirect_uri = oidc
178            .get("redirect_uri")
179            .or_else(|| oidc.get("redirect_url")) // backward compat
180            .and_then(|v| v.as_str())
181            .unwrap_or("http://localhost:3000/auth/callback")
182            .to_string();
183        let scope = oidc
184            .get("scope")
185            .and_then(|v| v.as_str())
186            .unwrap_or("openid profile email")
187            .to_string();
188
189        let mut validation_options = JwtValidationOptions::default();
190        if let Some(skip) = oidc.get("skip_issuer_validation").and_then(|v| v.as_bool()) {
191            validation_options.skip_issuer_validation = skip;
192        }
193        if let Some(skip) = oidc
194            .get("skip_audience_validation")
195            .and_then(|v| v.as_bool())
196        {
197            validation_options.skip_audience_validation = skip;
198        }
199        validation_options.expected_audience = oidc
200            .get("expected_audience")
201            .and_then(|v| v.as_str())
202            .map(String::from);
203
204        let pkce_secret = oidc
205            .get("pkce_cookie_secret")
206            .and_then(|v| v.as_str())
207            .unwrap_or("trustee-default-pkce-secret-change-me")
208            .to_string();
209
210        Some((
211            issuer_url,
212            client_id,
213            client_secret,
214            redirect_uri,
215            scope,
216            validation_options,
217            pkce_secret,
218        ))
219    }
220
221    /// Build OIDC client configuration for PEP's OidcClient.
222    pub fn oidc_client_config(&self) -> OidcClientConfig {
223        OidcClientConfig {
224            issuer_url: self.issuer_url.clone(),
225            client_id: self.client_id.clone(),
226            client_secret: self.client_secret.clone(),
227            redirect_uri: self.redirect_uri.clone(),
228            scope: self.scope.clone(),
229            code_challenge_method: "S256".to_string(),
230        }
231    }
232}
233
234// ---------------------------------------------------------------------------
235// Token validation cache (issue c41eb9d7)
236// ---------------------------------------------------------------------------
237
238/// Grace subtracted from a token's `exp` before its cached validation goes
239/// stale. MUST exceed PEP's 60s clock-skew leeway, so a cached result is
240/// never served for a token PEP itself would reject on skew.
241const CACHE_EXP_GRACE_SECS: i64 = 120;
242
243/// Upper bound on how long any cached validation stays fresh, regardless of
244/// token lifetime. Bounds staleness of role/group enrichment changes.
245const CACHE_TTL_SECS: i64 = 300;
246
247/// Maximum cached tokens — bounded memory on a long-running daemon.
248const CACHE_MAX_ENTRIES: usize = 1024;
249
250/// Cache key: first 16 bytes of SHA-256(token). 128-bit truncation — no
251/// practical collision, and the raw token is never stored or logged.
252fn validation_cache_key(token: &str) -> [u8; 16] {
253    let digest = Sha256::digest(token.as_bytes());
254    let mut key = [0u8; 16];
255    key.copy_from_slice(&digest[..16]);
256    key
257}
258
259fn unix_now() -> i64 {
260    std::time::SystemTime::now()
261        .duration_since(std::time::UNIX_EPOCH)
262        .map(|d| d.as_secs() as i64)
263        .unwrap_or(0)
264}
265
266/// AUTHN-only token validation cache.
267///
268/// Keyed by [`validation_cache_key`], entry lifetime
269/// `min(exp - CACHE_EXP_GRACE_SECS, now + CACHE_TTL_SECS)`. Never gates
270/// authorization: callers MUST still run Cedar per request on the cached
271/// principal (`check_auth` does). Critical sections are clone-and-insert
272/// sized — the lock is never held across an await, and a concurrent
273/// double-validation on a cold token is benign (one wasted validation,
274/// correctness intact).
275struct ValidationCache {
276    inner: Mutex<ValidationCacheInner>,
277}
278
279#[derive(Default)]
280struct ValidationCacheInner {
281    /// token-hash → (claims, valid_until as unix seconds)
282    entries: HashMap<[u8; 16], (JwtClaims, i64)>,
283    /// (sub, issuer) pairs already announced once at INFO.
284    first_sight: HashSet<(String, String)>,
285}
286
287impl ValidationCache {
288    fn new() -> Self {
289        Self {
290            inner: Mutex::new(ValidationCacheInner::default()),
291        }
292    }
293
294    /// Cached claims if present and still fresh.
295    fn get(&self, key: &[u8; 16], now: i64) -> Option<JwtClaims> {
296        let inner = self.inner.lock().expect("validation cache poisoned");
297        inner
298            .entries
299            .get(key)
300            .filter(|(_, until)| *until > now)
301            .map(|(claims, _)| claims.clone())
302    }
303
304    /// Store a fresh validation result with
305    /// `valid_until = min(exp - grace, now + ttl)`. A near-expiry token is
306    /// inserted harmlessly — `get` filters by time, so it is born stale.
307    fn put(&self, key: [u8; 16], claims: JwtClaims, now: i64) {
308        let valid_until = (claims.exp - CACHE_EXP_GRACE_SECS).min(now + CACHE_TTL_SECS);
309        let mut inner = self.inner.lock().expect("validation cache poisoned");
310        if inner.entries.len() >= CACHE_MAX_ENTRIES {
311            // Prefer dropping expired entries; if the map is all-hot, clear
312            // rather than random-evict live sessions. The cache is an
313            // optimization — correctness never depends on a hit.
314            inner.entries.retain(|_, (_, until)| *until > now);
315            if inner.entries.len() >= CACHE_MAX_ENTRIES {
316                inner.entries.clear();
317            }
318        }
319        inner.entries.insert(key, (claims, valid_until));
320    }
321
322    /// True on first sight of (sub, issuer) — the one chance to log at INFO.
323    fn mark_first_sight(&self, sub: &str, issuer: &str) -> bool {
324        let mut inner = self.inner.lock().expect("validation cache poisoned");
325        if inner.first_sight.len() >= CACHE_MAX_ENTRIES {
326            inner.first_sight.clear();
327        }
328        inner
329            .first_sight
330            .insert((sub.to_string(), issuer.to_string()))
331    }
332}
333
334/// Shared authentication state, stored in ServerState.
335#[derive(Clone)]
336pub struct AuthState {
337    /// OIDC client for login flow (authorization code + PKCE)
338    pub oidc_client: OidcClient,
339    /// Resource server client for JWT validation (lazy-initialized)
340    pub resource_server: ResourceServerClient,
341    /// OIDC client configuration
342    pub client_config: OidcClientConfig,
343    /// Auth configuration
344    pub config: AuthConfig,
345    /// Stateless PKCE cookie manager
346    pub pkce_manager: PkceCookieManager,
347    /// Web session manager (cookie session_id → server-side token with auto-refresh)
348    pub session_manager: Arc<WebSessionManager>,
349    /// 16F: service-account issuer candidates (Kanidm vhosts agent tokens
350    /// are minted on). Tokens carrying one of these fail primary validation
351    /// (the `[oidc]` issuer is a different vhost) — `check_auth` falls back
352    /// to validating against each candidate, never skipping issuer checks.
353    /// Same IdP, same keys, no trust expansion.
354    pub issuer_fallbacks: Vec<String>,
355    /// Cedar authorizer for ABAC authorization (None = Cedar disabled)
356    pub cedar_authorizer: Option<Arc<pep::cedar::CedarAuthorizer>>,
357    /// AUTHN-only token-validation cache (issue c41eb9d7). NEVER gates Cedar:
358    /// per-action authorization still runs per-request on the cached principal.
359    validation_cache: Arc<ValidationCache>,
360    /// ec3e0622 root-cause fix: stable identity pins (sub → user_key), derived
361    /// ONCE at first sighting and never recomputed from claims. Agents bypass
362    /// it (their key is already the immutable sub).
363    pub identity_registry: IdentityRegistry,
364}
365
366impl AuthState {
367    /// Create new auth state from configuration.
368    pub fn new(config: AuthConfig) -> Self {
369        Self::with_cedar(config, None)
370    }
371
372    /// Create new auth state with optional Cedar authorizer.
373    pub fn with_cedar(
374        config: AuthConfig,
375        cedar_authorizer: Option<Arc<pep::cedar::CedarAuthorizer>>,
376    ) -> Self {
377        let pkce_manager = PkceCookieManager::new(
378            config.pkce_cookie_secret.as_bytes(),
379            "trustee_pkce_state",
380            StdDuration::from_secs(600),
381        );
382
383        let session_manager = Arc::new(WebSessionManager::new(
384            OidcClient::new(),
385            config.issuer_url.clone(),
386            config.client_id.clone(),
387            config.client_secret.clone(),
388            config.scope.clone(),
389        ));
390
391        Self {
392            oidc_client: OidcClient::new(),
393            resource_server: ResourceServerClient::new(),
394            client_config: config.oidc_client_config(),
395            pkce_manager,
396            session_manager,
397            config,
398            cedar_authorizer,
399            issuer_fallbacks: Vec::new(),
400            validation_cache: Arc::new(ValidationCache::new()),
401            identity_registry: IdentityRegistry::from_default_home(),
402        }
403    }
404
405    /// ec3e0622 root-cause fix: resolve the namespace key THROUGH the pin
406    /// registry — the 16D derivation is consulted exactly ONCE per principal
407    /// (first sighting) and then never again. Claims may gate PERMISSIONS
408    /// (Cedar) but can no longer rotate the user's home directory. Agents
409    /// bypass the registry (their key is the immutable sub, per 16E).
410    pub fn resolve_user_key(&self, claims: &JwtClaims) -> String {
411        if PrincipalKind::from_role(claim_role(claims).as_deref()) == PrincipalKind::Agent {
412            return claims.sub.clone();
413        }
414        self.identity_registry
415            .pin(claims.sub.as_str(), &jwt_user_key(claims))
416    }
417
418    /// 16F: set the service-account issuer fallback candidates.
419    pub fn with_issuer_fallbacks(mut self, issuers: Vec<String>) -> Self {
420        self.issuer_fallbacks = issuers;
421        self
422    }
423
424    /// Check if development mode is enabled.
425    pub fn is_dev_mode(&self) -> bool {
426        self.config.dev_config.local_dev_mode
427    }
428
429    /// Validate a JWT token using PEP's ResourceServerClient.
430    pub async fn validate_token(&self, token: &str) -> anyhow::Result<JwtClaims> {
431        self.validate_token_on(&self.config.issuer_url, token).await
432    }
433
434    /// 16F: primary validation, then the service issuer if that fails —
435    /// cached per token (issue c41eb9d7).
436    ///
437    /// Kanidm stamps tokens with the vhost they were minted on: human logins
438    /// carry the `[oidc]` issuer, agent tokens exchanged via the service
439    /// credential carry the service issuer. Each validates only against its
440    /// own — this tries both, never skipping issuer validation.
441    ///
442    /// Results are cached (SHA-256(token)[:16] → claims, valid
443    /// `min(exp-120s, now+300s)`, cap 1024) so polling clients stop paying a
444    /// double validation + log line per request. AUTHN only: callers MUST
445    /// still run Cedar authorization per request (`check_auth` does).
446    pub async fn validate_token_flexible(&self, token: &str) -> anyhow::Result<JwtClaims> {
447        let key = validation_cache_key(token);
448        let now = unix_now();
449        if let Some(cached) = self.validation_cache.get(&key, now) {
450            return Ok(cached);
451        }
452        let claims = self.validate_token_flexible_uncached(token).await?;
453        self.validation_cache.put(key, claims.clone(), now);
454        Ok(claims)
455    }
456
457    async fn validate_token_flexible_uncached(&self, token: &str) -> anyhow::Result<JwtClaims> {
458        match self.validate_token(token).await {
459            Ok(claims) => Ok(claims),
460            Err(primary) => {
461                let mut last = primary;
462                for si in &self.issuer_fallbacks {
463                    if *si == self.config.issuer_url {
464                        continue; // primary already tried it
465                    }
466                    match self.validate_token_on(si, token).await {
467                        Ok(claims) => {
468                            // c41eb9d7: this used to log INFO per request — an
469                            // idle-poll terminal flood. One INFO on first
470                            // sight of (sub, issuer), DEBUG afterwards.
471                            let first = self.validation_cache.mark_first_sight(&claims.sub, si);
472                            let who = claims.preferred_username.as_deref().unwrap_or(&claims.sub);
473                            if first {
474                                tracing::info!(
475                                    "service principal {} authenticating via service-issuer fallback (iss={})",
476                                    who,
477                                    si
478                                );
479                            } else {
480                                tracing::debug!(
481                                    "token validated via service-issuer fallback (iss={}) — principal {}",
482                                    si,
483                                    who
484                                );
485                            }
486                            return Ok(claims);
487                        }
488                        Err(e) => last = e,
489                    }
490                }
491                // Auth failure must SCREAM regardless of caller handling
492                // (callers also warn on the returned error — belt and braces).
493                tracing::warn!(
494                    "token validation failed — primary: {last}; all service-issuer fallbacks exhausted"
495                );
496                Err(anyhow::anyhow!(
497                    "primary: {last}; all service-issuer fallbacks exhausted"
498                ))
499            }
500        }
501    }
502
503    /// Validate against a SPECIFIC issuer — validation AND enrichment must
504    /// both run on the vhost that issued the token.
505    pub async fn validate_token_on(
506        &self,
507        issuer_url: &str,
508        token: &str,
509    ) -> anyhow::Result<JwtClaims> {
510        let mut claims = self
511            .resource_server
512            .validate_jwt_with_options(
513                token,
514                issuer_url,
515                &self.config.client_id,
516                &self.config.validation_options,
517            )
518            .await
519            .map_err(|e| anyhow::anyhow!("Token validation failed: {}", e))?;
520
521        // Enrich with userinfo for role/groups (cached, no-op if already present)
522        // 2de5d1eb: this used to be `let _ =` — a silent role-less principal
523        // that Cedar then fail-closed DENIED with `matched policies: []` and
524        // zero diagnosis. Enrichment failure must SCREAM.
525        if let Err(e) = self
526            .resource_server
527            .enrich_claims_with_userinfo(&mut claims, token, issuer_url, None)
528            .await
529        {
530            tracing::error!(
531                "userinfo enrichment FAILED for sub {}: {} — principal carries NO role/groups; \
532                 with Cedar enabled every request will be DENIED until enrichment succeeds",
533                claims.sub,
534                e
535            );
536        }
537
538        // PEP only merges groups/role from userinfo. If name/email are missing
539        // (Kanidm JWTs only contain sub), fetch them from userinfo directly.
540        if claims.name.is_none() || claims.email.is_none() {
541            self.fill_userinfo_fields(&mut claims, token, issuer_url)
542                .await;
543        }
544
545        Ok(claims)
546    }
547
548    /// Fetch name/email/preferred_username from the OIDC userinfo endpoint
549    /// and fill in any that are missing from the JWT claims.
550    async fn fill_userinfo_fields(&self, claims: &mut JwtClaims, token: &str, issuer_url: &str) {
551        // Derive userinfo URL from issuer
552        // For Kanidm: issuer_url is the discovery endpoint,
553        // userinfo is at {issuer_url}/userinfo — the token's OWN vhost
554        // (16F: a token minted on the service vhost must enrich there too).
555        let userinfo_url = format!("{}/userinfo", issuer_url.trim_end_matches('/'));
556
557        let client = reqwest::Client::new();
558        let resp = client
559            .get(&userinfo_url)
560            .header("Authorization", format!("Bearer {}", token))
561            .header("Accept", "application/json")
562            .send()
563            .await;
564
565        let Ok(resp) = resp else {
566            tracing::debug!("Userinfo request failed for name/email enrichment");
567            return;
568        };
569
570        if !resp.status().is_success() {
571            tracing::debug!(
572                "Userinfo returned {} for name/email enrichment",
573                resp.status()
574            );
575            return;
576        }
577
578        let Ok(userinfo): Result<serde_json::Map<String, serde_json::Value>, _> = resp.json().await
579        else {
580            return;
581        };
582
583        tracing::debug!("Userinfo keys: {:?}", userinfo.keys().collect::<Vec<_>>());
584
585        if claims.name.is_none() {
586            if let Some(name) = userinfo.get("name").and_then(|v| v.as_str()) {
587                claims.name = Some(name.to_string());
588            }
589        }
590        if claims.email.is_none() {
591            if let Some(email) = userinfo.get("email").and_then(|v| v.as_str()) {
592                claims.email = Some(email.to_string());
593            }
594        }
595        if claims.preferred_username.is_none() {
596            if let Some(uname) = userinfo.get("preferred_username").and_then(|v| v.as_str()) {
597                claims.preferred_username = Some(uname.to_string());
598            }
599        }
600    }
601
602    /// Check Cedar authorization for the authenticated user.
603    ///
604    /// Returns Ok(()) if allowed (or if Cedar is not configured).
605    /// Returns Err(()) if denied — caller should return 403 Forbidden.
606    fn check_cedar_authorized(&self, claims: &JwtClaims, action: &str) -> Result<(), ()> {
607        let Some(ref authorizer) = self.cedar_authorizer else {
608            return Ok(()); // Cedar not configured — allow
609        };
610
611        // Build principal entity from JWT claims
612        let principal_entity = match pep::cedar::build_principal_entity(claims) {
613            Ok(e) => e,
614            Err(e) => {
615                tracing::error!("Cedar: failed to build principal entity: {}", e);
616                return Err(());
617            }
618        };
619
620        // Build entities set with principal + TrusteeApp resource
621        let mut entities_vec = vec![principal_entity];
622
623        // Add a TrusteeApp entity as the resource
624        let app_uid = match EntityUid::from_str(r#"TrusteeApp::"default""#) {
625            Ok(uid) => uid,
626            Err(e) => {
627                tracing::error!("Cedar: failed to build TrusteeApp uid: {}", e);
628                return Err(());
629            }
630        };
631        let app_entity = match cedar_policy::Entity::new(
632            app_uid,
633            std::collections::HashMap::new(),
634            std::collections::HashSet::new(),
635        ) {
636            Ok(e) => e,
637            Err(e) => {
638                tracing::error!("Cedar: failed to build TrusteeApp entity: {}", e);
639                return Err(());
640            }
641        };
642        entities_vec.push(app_entity);
643
644        let entities = match Entities::from_entities(entities_vec, None) {
645            Ok(e) => e,
646            Err(e) => {
647                tracing::error!("Cedar: failed to build entities set: {}", e);
648                return Err(());
649            }
650        };
651
652        // Build the Cedar authorization request
653        let principal_uid = match pep::cedar::build_principal_uid(claims) {
654            Ok(uid) => uid,
655            Err(e) => {
656                tracing::error!("Cedar: failed to build principal uid: {}", e);
657                return Err(());
658            }
659        };
660
661        let action_uid = match EntityUid::from_str(&format!("Action::\"{action}\"")) {
662            Ok(uid) => uid,
663            Err(e) => {
664                tracing::error!("Cedar: failed to build action uid: {}", e);
665                return Err(());
666            }
667        };
668
669        let resource_uid = match EntityUid::from_str(r#"TrusteeApp::"default""#) {
670            Ok(uid) => uid,
671            Err(e) => {
672                tracing::error!("Cedar: failed to build resource uid: {}", e);
673                return Err(());
674            }
675        };
676
677        let request = match Request::new(
678            principal_uid,
679            action_uid,
680            resource_uid,
681            Context::empty(),
682            None,
683        ) {
684            Ok(r) => r,
685            Err(e) => {
686                tracing::error!("Cedar: failed to build request: {}", e);
687                return Err(());
688            }
689        };
690
691        let response = authorizer.is_allowed_with_entities(&request, &entities);
692
693        if response.allowed() {
694            tracing::debug!(
695                "Cedar: authorized user {} (sub={})",
696                claims.email.as_deref().unwrap_or("unknown"),
697                claims.sub
698            );
699            Ok(())
700        } else {
701            tracing::warn!(
702                "Cedar: DENIED user {} (sub={}) — matched policies: {:?}, errors: {:?}",
703                claims.email.as_deref().unwrap_or("unknown"),
704                claims.sub,
705                response.matched_policies(),
706                response.errors()
707            );
708            Err(())
709        }
710    }
711}
712
713// ---------------------------------------------------------------------------
714// Auth checking — called by protected route handlers
715// ---------------------------------------------------------------------------
716
717/// Cedar action names (P2, nghr 645809c3).
718///
719/// Keep in sync with `policies/trustee_schema.cedarschema` — the schema and
720/// the embedded policy ship atomically with these constants; a filesystem
721/// policy override referencing removed actions will deny everything (loud,
722/// by design).
723pub mod actions {
724    pub const LIST_MODELS: &str = "ListModels";
725    pub const LIST_SESSIONS: &str = "ListSessions";
726    pub const VIEW_SESSION: &str = "ViewSession";
727    pub const VIEW_HISTORY: &str = "ViewHistory";
728    pub const CREATE_SESSION: &str = "CreateSession";
729    pub const COMMAND_SESSION: &str = "CommandSession";
730    pub const CANCEL_SESSION: &str = "CancelSession";
731    pub const HANDOFF_SESSION: &str = "HandoffSession";
732    pub const RESUME_SESSION: &str = "ResumeSession";
733    pub const UPDATE_SESSION: &str = "UpdateSession";
734    pub const DELETE_SESSION: &str = "DeleteSession";
735    pub const VIEW_MCP_CREDENTIALS: &str = "ViewMcpCredentials";
736    pub const UPDATE_MCP_CREDENTIALS: &str = "UpdateMcpCredentials";
737}
738
739/// Principal kind (16D). `Agent` iff the enriched `role` claim contains
740/// "agent" — the exact value mapped by Kanidm's `pdt-api-agents` group
741/// (role vocabulary: admin | user | service | agent, facts doc 42977cb7).
742#[derive(Debug, Clone, Copy, PartialEq, Eq)]
743pub enum PrincipalKind {
744    Human,
745    Agent,
746}
747
748impl PrincipalKind {
749    /// Classify from the primary role. Anything that is not exactly
750    /// "agent" is Human — fail-toward-human keeps the default posture
751    /// identical to pre-16D behavior.
752    pub fn from_role(role: Option<&str>) -> Self {
753        match role {
754            Some("agent") => Self::Agent,
755            _ => Self::Human,
756        }
757    }
758}
759
760/// Extract the primary role from enriched JWT claims.
761///
762/// PEP merges userinfo into `extra` (flattened claims). Kanidm delivers
763/// `role` as a STRING or an ARRAY (pep 366e8ed lesson) — accept both,
764/// first value wins.
765fn claim_role(claims: &JwtClaims) -> Option<String> {
766    match claims.extra.get("role") {
767        Some(serde_json::Value::String(s)) => Some(s.clone()),
768        Some(serde_json::Value::Array(arr)) => arr
769            .iter()
770            .filter_map(|v| v.as_str())
771            .next()
772            .map(|s| s.to_string()),
773        _ => None,
774    }
775}
776
777/// Authenticated user info extracted from the token.
778#[derive(Debug, Clone)]
779pub struct AuthUser {
780    pub sub: String,
781    pub email: Option<String>,
782    pub name: Option<String>,
783    pub username: Option<String>,
784    pub is_dev: bool,
785    /// Primary role from enriched claims (16D).
786    pub role: Option<String>,
787    /// Principal classification (16D): Agent iff role == "agent".
788    pub kind: PrincipalKind,
789}
790
791impl From<JwtClaims> for AuthUser {
792    fn from(claims: JwtClaims) -> Self {
793        let role = claim_role(&claims);
794        let kind = PrincipalKind::from_role(role.as_deref());
795        Self {
796            sub: claims.sub,
797            email: claims.email,
798            name: claims.name,
799            username: claims.preferred_username,
800            is_dev: false,
801            role,
802            kind,
803        }
804    }
805}
806
807/// Cookie max-age for session cookies (1 hour, matching the server-side idle timeout).
808const SESSION_COOKIE_MAX_AGE: StdDuration = StdDuration::from_secs(3600);
809
810/// PINNED (16D) + AGENT CARVE-OUT (16E): user_key for JWT principals.
811///
812/// Humans: `preferred_username` first, falling back to `sub`. NEVER email —
813/// email is rebindable in Kanidm and would silently re-home a principal's
814/// namespace.
815///
816/// Agents: `sub` — ALWAYS. Exchanged agent tokens carry no
817/// `preferred_username` today, but a future scope change (e.g. adding
818/// `profile` to the exchange) would add it and silently re-home every
819/// agent's namespace — the exact migration bug class 0.10→0.11 inflicted on
820/// humans. Agents are pinned to `sub` for the lifetime of the namespace.
821///
822/// MIGRATION NOTE (humans): the 16D rule changed the key for existing JWT
823/// humans (they were keyed by `sub` before 0.11.0). Kanidm humans have a
824/// `preferred_username`, so their namespace hash changes on first login —
825/// pre-web-production history under the old hash is orphaned, not deleted.
826fn jwt_user_key(claims: &JwtClaims) -> String {
827    if PrincipalKind::from_role(claim_role(claims).as_deref()) == PrincipalKind::Agent {
828        return claims.sub.clone();
829    }
830    match claims.preferred_username.as_deref() {
831        Some(u) if !u.trim().is_empty() => u.trim().to_string(),
832        _ => {
833            tracing::debug!(
834                "user_key: preferred_username missing/empty for sub {} — falling back to sub",
835                claims.sub
836            );
837            claims.sub.clone()
838        }
839    }
840}
841
842/// Extract a user key from a dev-mode token string.
843///
844/// Two formats (BOTH gated by `local_dev_mode` at every call site):
845/// - `dev:agent:<name>` → `agent-{name}` (16D: agent namespace in dev —
846///   unblocks per-user cache + THQ E2E without Kanidm accounts; distinct
847///   prefix so dev agents can never collide with dev humans)
848/// - `dev:email:name:username` → `dev:{email}` (dev humans, legacy)
849fn dev_user_key(token: &str) -> Option<String> {
850    if let Some(name) = token.strip_prefix("dev:agent:") {
851        let name = name.trim();
852        if name.is_empty() || name.contains(':') {
853            return None;
854        }
855        return Some(format!("agent-{name}"));
856    }
857    let parts: Vec<&str> = token.splitn(4, ':').collect();
858    if parts.len() >= 4 {
859        Some(format!("dev:{}", parts[1]))
860    } else {
861        None
862    }
863}
864
865/// Pure decision core of [`check_dispatch_admin`] — unit-testable without an IdP.
866pub(crate) fn dispatch_allowed(kind: PrincipalKind, role: Option<&str>) -> bool {
867    kind == PrincipalKind::Human && role == Some("admin")
868}
869
870/// 16F: admin gate for the per-agent dispatch surface (`/xagent/{name}`).
871///
872/// The OUTER dispatch must be performed by a HUMAN ADMIN: agents may never
873/// dispatch agents, and `service` is read-only by design. The impersonated
874/// INNER request is separately authenticated and Cedar-gated AS THE AGENT
875/// (per-action matrix), so this gate answers exactly one question: "may this
876/// principal dispatch agent-users at all".
877///
878/// Open mode (no auth configured) allows dispatch, consistent with the
879/// posture check_auth already applies. Dev-mode human tokens carry no role
880/// and are therefore rejected — dispatch testing requires a real admin JWT.
881pub async fn check_dispatch_admin(
882    auth: &Option<Arc<AuthState>>,
883    headers: &axum::http::HeaderMap,
884) -> Result<(), StatusCode> {
885    let Some(auth) = auth.as_ref() else {
886        return Ok(()); // open mode — same posture as check_auth
887    };
888    let Some(token) = headers
889        .get(header::AUTHORIZATION)
890        .and_then(|v| v.to_str().ok())
891        .and_then(|v| v.strip_prefix("Bearer "))
892        .map(|s| s.to_string())
893    else {
894        return Err(StatusCode::UNAUTHORIZED);
895    };
896    if token.starts_with("dev:") {
897        tracing::warn!("xagent dispatch rejected: dev tokens cannot dispatch agents");
898        return Err(StatusCode::FORBIDDEN);
899    }
900    let claims = auth.validate_token_flexible(&token).await.map_err(|e| {
901        tracing::warn!("xagent dispatch: caller token validation failed: {}", e);
902        StatusCode::UNAUTHORIZED
903    })?;
904    let user = AuthUser::from(claims);
905    if !dispatch_allowed(user.kind, user.role.as_deref()) {
906        tracing::warn!(
907            "xagent dispatch rejected: principal kind={:?} role={:?} — admin required",
908            user.kind,
909            user.role
910        );
911        return Err(StatusCode::FORBIDDEN);
912    }
913    Ok(())
914}
915
916impl AuthState {
917    /// 16F: exchange an agent-user's Kanidm service token for a short-lived
918    /// access token carrying `role=agent`, usable as the impersonated Bearer
919    /// on the inner dispatch. Same grant the MCP credentials use (verified
920    /// RFC 8693 shape); enrichment in `validate_token` resolves the role.
921    ///
922    /// `issuer_url` MUST be the service-account issuer: Kanidm binds token
923    /// exchange to the client origin — the `[oidc]` auth issuer host serves
924    /// logins but rejects exchange with `invalid_request`, while the
925    /// `[mcp.credentials.*]` service issuer (see
926    /// `ServerState::service_issuer`) accepts it (verified live 2026-08-30:
927    /// same token, 200 vs 400).
928    pub async fn exchange_agent_token(
929        &self,
930        issuer_url: &str,
931        service_token: &str,
932    ) -> Result<(String, u64), StatusCode> {
933        let tr = self
934            .oidc_client
935            .exchange_token(
936                issuer_url,
937                &self.config.client_id,
938                None, // public client — no secret (Kanidm rejects one)
939                service_token,
940                &self.config.client_id,
941                Some("openid groups"),
942            )
943            .await
944            .map_err(|e| {
945                tracing::error!(
946                    "xagent dispatch: agent token exchange FAILED at {issuer_url}: {} — impersonation unavailable",
947                    e
948                );
949                StatusCode::BAD_GATEWAY
950            })?;
951        Ok((tr.access_token, tr.expires_in.unwrap_or(900)))
952    }
953}
954
955/// Check authentication for a protected endpoint.
956///
957/// Returns `Ok((None, user_key))` if auth is not configured (open mode), or if
958/// a valid token is present without needing cookie renewal. Returns
959/// `Ok((Some(cookie), user_key))` if auth succeeded and the caller should
960/// include the given `Set-Cookie` header value in the response (rolling session).
961/// Returns `Err(StatusCode)` if auth is configured but no valid token is found.
962///
963/// The returned `user_key` is the identity string used for session isolation
964/// (JWT principals: `preferred_username || sub` — PINNED, see [`jwt_user_key`];
965/// `dev:{email}` for dev-mode humans, `agent-{name}` for `dev:agent:` tokens,
966/// `"default"` when auth is not configured). This avoids the need for handlers
967/// to call `resolve_user_key()` which would re-validate the JWT a second time.
968///
969/// Token sources (in order):
970/// 1. `Authorization: Bearer <token>` header (raw JWT — validated directly)
971/// 2. `trustee_token=<session_id>` cookie (looked up in WebSessionManager,
972///    auto-refreshed if near expiry)
973///
974/// Dev mode tokens use the format `dev:email:name:username`.
975pub async fn check_auth(
976    auth: &Option<Arc<AuthState>>,
977    headers: &axum::http::HeaderMap,
978    action: &str,
979) -> Result<(Option<String>, String), StatusCode> {
980    let Some(auth) = auth.as_ref() else {
981        return Ok((None, "default".to_string())); // Auth not configured — allow
982    };
983
984    // 1. Try Bearer header first (raw JWT — e.g. from API clients, Torpi proxy)
985    if let Some(token) = headers
986        .get(header::AUTHORIZATION)
987        .and_then(|v| v.to_str().ok())
988        .and_then(|v| v.strip_prefix("Bearer "))
989        .map(|s| s.to_string())
990    {
991        // Dev mode token — only accepted when dev mode is currently enabled
992        if token.starts_with("dev:") {
993            if !auth.config.dev_config.local_dev_mode {
994                tracing::warn!("Dev token presented but dev mode is disabled — rejecting");
995                return Err(StatusCode::UNAUTHORIZED);
996            }
997            return match dev_user_key(&token) {
998                Some(key) => Ok((None, key)),
999                None => Err(StatusCode::UNAUTHORIZED),
1000            };
1001        }
1002
1003        return match auth.validate_token_flexible(&token).await {
1004            Ok(claims) => {
1005                if auth.check_cedar_authorized(&claims, action).is_err() {
1006                    return Err(StatusCode::FORBIDDEN);
1007                }
1008                Ok((None, auth.resolve_user_key(&claims)))
1009            }
1010            Err(e) => {
1011                tracing::warn!("Bearer token validation failed: {}", e);
1012                Err(StatusCode::UNAUTHORIZED)
1013            }
1014        };
1015    }
1016
1017    // 2. Try cookie (session_id → WebSessionManager → access token with auto-refresh)
1018    let session_id = headers
1019        .get(header::COOKIE)
1020        .and_then(|v| v.to_str().ok())
1021        .and_then(|cookies| extract_token_from_cookies(cookies, &auth.config.cookie_name));
1022
1023    let Some(session_id) = session_id else {
1024        tracing::warn!("No auth token found in request");
1025        return Err(StatusCode::UNAUTHORIZED);
1026    };
1027
1028    // Dev mode token in cookie — only accepted when dev mode is currently enabled
1029    if session_id.starts_with("dev:") {
1030        if !auth.config.dev_config.local_dev_mode {
1031            tracing::warn!("Dev cookie presented but dev mode is disabled — rejecting");
1032            return Err(StatusCode::UNAUTHORIZED);
1033        }
1034        return match dev_user_key(&session_id) {
1035            Some(key) => Ok((None, key)),
1036            None => Err(StatusCode::UNAUTHORIZED),
1037        };
1038    }
1039
1040    // Session-based: look up via WebSessionManager (auto-refreshes)
1041    match auth.session_manager.get_token(&session_id).await {
1042        Ok(access_token) => match auth.validate_token(&access_token).await {
1043            Ok(claims) => {
1044                // Cedar authorization check
1045                if auth.check_cedar_authorized(&claims, action).is_err() {
1046                    return Err(StatusCode::FORBIDDEN);
1047                }
1048                // Roll the cookie — reset max-age so active users stay logged in
1049                let secure = auth.client_config.redirect_uri.starts_with("https");
1050                let cookie = create_auth_cookie(
1051                    &auth.config.cookie_name,
1052                    &session_id,
1053                    SESSION_COOKIE_MAX_AGE,
1054                    secure,
1055                );
1056                Ok((Some(cookie.to_string()), auth.resolve_user_key(&claims)))
1057            }
1058            Err(e) => {
1059                // Token was returned but JWT validation failed (e.g. ExpiredSignature
1060                // due to clock skew). Force-refresh and retry once.
1061                tracing::warn!(
1062                    "Session token validation failed: {} — attempting force-refresh",
1063                    e
1064                );
1065                match auth.session_manager.force_refresh(&session_id).await {
1066                    Ok(new_token) => match auth.validate_token(&new_token).await {
1067                        Ok(claims) => {
1068                            // Cedar authorization check
1069                            if auth.check_cedar_authorized(&claims, action).is_err() {
1070                                return Err(StatusCode::FORBIDDEN);
1071                            }
1072                            let secure = auth.client_config.redirect_uri.starts_with("https");
1073                            let cookie = create_auth_cookie(
1074                                &auth.config.cookie_name,
1075                                &session_id,
1076                                SESSION_COOKIE_MAX_AGE,
1077                                secure,
1078                            );
1079                            Ok((Some(cookie.to_string()), auth.resolve_user_key(&claims)))
1080                        }
1081                        Err(e2) => {
1082                            tracing::warn!(
1083                                "Session token still invalid after force-refresh: {}",
1084                                e2
1085                            );
1086                            Err(StatusCode::UNAUTHORIZED)
1087                        }
1088                    },
1089                    Err(e2) => {
1090                        tracing::warn!("Force-refresh failed: {}", e2);
1091                        Err(StatusCode::UNAUTHORIZED)
1092                    }
1093                }
1094            }
1095        },
1096        Err(e) => {
1097            tracing::warn!("Session lookup/refresh failed: {}", e);
1098            Err(StatusCode::UNAUTHORIZED)
1099        }
1100    }
1101}
1102
1103/// Extract a valid access token from the request (for use by handlers that
1104/// need the token itself, not just auth checking).
1105///
1106/// Resolves session_id cookies to actual access tokens via WebSessionManager.
1107/// Bearer headers are returned as-is.
1108async fn resolve_access_token(
1109    auth: &AuthState,
1110    headers: &axum::http::HeaderMap,
1111) -> Result<String, StatusCode> {
1112    // Bearer header — return as-is
1113    if let Some(token) = headers
1114        .get(header::AUTHORIZATION)
1115        .and_then(|v| v.to_str().ok())
1116        .and_then(|v| v.strip_prefix("Bearer "))
1117        .map(|s| s.to_string())
1118    {
1119        return Ok(token);
1120    }
1121
1122    // Cookie — resolve session_id → access_token
1123    let session_id = headers
1124        .get(header::COOKIE)
1125        .and_then(|v| v.to_str().ok())
1126        .and_then(|cookies| extract_token_from_cookies(cookies, &auth.config.cookie_name));
1127
1128    match session_id {
1129        Some(sid) if sid.starts_with("dev:") => {
1130            if !auth.config.dev_config.local_dev_mode {
1131                tracing::warn!(
1132                    "Dev cookie in resolve_access_token but dev mode is disabled — rejecting"
1133                );
1134                Err(StatusCode::UNAUTHORIZED)
1135            } else {
1136                Ok(sid)
1137            }
1138        }
1139        Some(sid) => auth.session_manager.get_token(&sid).await.map_err(|e| {
1140            tracing::warn!("Failed to resolve session token: {}", e);
1141            StatusCode::UNAUTHORIZED
1142        }),
1143        None => Err(StatusCode::UNAUTHORIZED),
1144    }
1145}
1146
1147/// Extract token value from a cookie header string.
1148fn extract_token_from_cookies(cookie_header: &str, cookie_name: &str) -> Option<String> {
1149    for cookie in cookie_header.split(';') {
1150        let cookie = cookie.trim();
1151        if let Some(value) = cookie.strip_prefix(&format!("{}=", cookie_name)) {
1152            return Some(value.to_string());
1153        }
1154    }
1155    None
1156}
1157
1158// ---------------------------------------------------------------------------
1159// Auth routes: /auth/login, /auth/callback, /auth/me, /auth/logout
1160// ---------------------------------------------------------------------------
1161
1162/// Build the auth routes as a nested Router.
1163pub fn auth_routes() -> axum::Router<crate::ServerState> {
1164    axum::Router::new()
1165        .route("/login", axum::routing::get(login_handler))
1166        .route("/callback", axum::routing::get(callback_handler))
1167        .route("/me", axum::routing::get(me_handler))
1168        .route("/logout", axum::routing::post(logout_handler))
1169        .route("/mcp/login", axum::routing::get(mcp_login_handler))
1170        .route("/mcp/callback", axum::routing::get(mcp_callback_handler))
1171        .route("/mcp/status", axum::routing::get(mcp_status_handler))
1172        .route("/mcp/logout", axum::routing::post(mcp_logout_handler))
1173}
1174
1175/// Query parameters for OIDC callback.
1176#[derive(Debug, Deserialize)]
1177pub struct CallbackQuery {
1178    pub code: Option<String>,
1179    pub state: Option<String>,
1180    pub error: Option<String>,
1181    pub error_description: Option<String>,
1182}
1183
1184/// GET /auth/login — initiate OIDC login with PKCE, or create dev session.
1185async fn login_handler(State(state): State<crate::ServerState>) -> Result<Response, AuthError> {
1186    let auth = state.auth.as_ref().ok_or(AuthError::AuthNotConfigured)?;
1187
1188    // Dev mode — create synthetic session
1189    if auth.is_dev_mode() {
1190        tracing::info!("Dev mode: creating dev session");
1191        let dev = &auth.config.dev_config;
1192        let dev_token = format!(
1193            "dev:{}:{}:{}",
1194            dev.local_dev_email.as_deref().unwrap_or("dev@localhost"),
1195            dev.local_dev_name.as_deref().unwrap_or("Dev User"),
1196            dev.local_dev_username.as_deref().unwrap_or("dev")
1197        );
1198        let cookie = create_auth_cookie(
1199            &auth.config.cookie_name,
1200            &dev_token,
1201            StdDuration::from_secs(86400),
1202            false,
1203        );
1204        return Ok(Response::builder()
1205            .status(StatusCode::FOUND)
1206            .header(header::LOCATION, "/")
1207            .header(header::SET_COOKIE, cookie.to_string())
1208            .body(Body::empty())
1209            .unwrap());
1210    }
1211
1212    // Production — redirect to IdP with PKCE
1213    let pkce_session = auth.pkce_manager.create();
1214    let challenge = OidcClient::generate_code_challenge(&pkce_session.verifier);
1215
1216    let auth_url = auth
1217        .oidc_client
1218        .build_authorization_url(&auth.client_config, &pkce_session.state, Some(&challenge))
1219        .await
1220        .map_err(|e| AuthError::OidcError(e.to_string()))?;
1221
1222    // Set PKCE state cookie (HttpOnly, SameSite=Lax)
1223    // Secure flag follows the redirect_uri scheme — HTTP localhost/LAN must not
1224    // set Secure or the browser drops the cookie and PKCE state is lost.
1225    let secure = auth.client_config.redirect_uri.starts_with("https");
1226    let pkce_cookie = Cookie::build((
1227        auth.pkce_manager.cookie_name().to_string(),
1228        pkce_session.cookie_value,
1229    ))
1230    .path("/")
1231    .http_only(true)
1232    .same_site(SameSite::Lax)
1233    .secure(secure)
1234    .max_age(TimeDuration::seconds(
1235        auth.pkce_manager.ttl().as_secs() as i64
1236    ))
1237    .build();
1238
1239    Ok(Response::builder()
1240        .status(StatusCode::TEMPORARY_REDIRECT)
1241        .header(header::LOCATION, &auth_url)
1242        .header(header::SET_COOKIE, pkce_cookie.to_string())
1243        .body(Body::empty())
1244        .unwrap())
1245}
1246
1247/// GET /auth/callback — exchange authorization code for tokens, set cookie.
1248async fn callback_handler(
1249    State(state): State<crate::ServerState>,
1250    Query(query): Query<CallbackQuery>,
1251    headers: axum::http::HeaderMap,
1252) -> Result<Response, AuthError> {
1253    let auth = state.auth.as_ref().ok_or(AuthError::AuthNotConfigured)?;
1254
1255    // Check for errors from IdP
1256    if let Some(error) = query.error {
1257        let desc = query.error_description.unwrap_or_default();
1258        tracing::error!("OIDC error: {} - {}", error, desc);
1259        return Ok(Redirect::temporary(&format!(
1260            "/?error={}&error_description={}",
1261            urlencoding::encode(&error),
1262            urlencoding::encode(&desc)
1263        ))
1264        .into_response());
1265    }
1266
1267    let code = query.code.ok_or(AuthError::MissingCode)?;
1268    let oauth_state = query.state.ok_or(AuthError::MissingState)?;
1269
1270    // Retrieve PKCE cookie
1271    let cookie_header = headers
1272        .get(header::COOKIE)
1273        .and_then(|v| v.to_str().ok())
1274        .unwrap_or("");
1275    let pkce_value = extract_token_from_cookies(cookie_header, auth.pkce_manager.cookie_name())
1276        .ok_or(AuthError::InvalidState)?;
1277
1278    // Verify PKCE cookie (HMAC + expiry + state match)
1279    let verifier = auth
1280        .pkce_manager
1281        .verify(&pkce_value, &oauth_state)
1282        .ok_or(AuthError::InvalidState)?;
1283
1284    // Exchange code for tokens
1285    tracing::info!("Exchanging authorization code for tokens");
1286    let token_response = auth
1287        .oidc_client
1288        .exchange_code_for_tokens(&auth.client_config, &code, Some(&verifier))
1289        .await
1290        .map_err(|e| AuthError::TokenExchangeFailed(e.to_string()))?;
1291
1292    let session_id = auth
1293        .session_manager
1294        .create_session(&token_response)
1295        .await
1296        .map_err(|e| AuthError::TokenExchangeFailed(format!("Session creation failed: {}", e)))?;
1297
1298    // Cookie lifetime matches server-side idle timeout (1 hour).
1299    // The cookie is rolled on every successful request via check_auth().
1300    let max_age = SESSION_COOKIE_MAX_AGE;
1301
1302    // Set auth cookie — Secure only when redirect_uri is HTTPS
1303    let secure = auth.client_config.redirect_uri.starts_with("https");
1304    let cookie = create_auth_cookie(&auth.config.cookie_name, &session_id, max_age, secure);
1305
1306    // Clear PKCE cookie (single-use)
1307    let clear_pkce = Cookie::build((auth.pkce_manager.cookie_name().to_string(), ""))
1308        .path("/")
1309        .http_only(true)
1310        .same_site(SameSite::Lax)
1311        .max_age(TimeDuration::seconds(-1))
1312        .build();
1313
1314    tracing::info!("Authentication successful, redirecting to /");
1315
1316    Ok(Response::builder()
1317        .status(StatusCode::FOUND)
1318        .header(header::LOCATION, "/")
1319        .header(header::SET_COOKIE, cookie.to_string())
1320        .header(header::SET_COOKIE, clear_pkce.to_string())
1321        .body(Body::empty())
1322        .unwrap())
1323}
1324
1325/// GET /auth/me — return current user info.
1326async fn me_handler(
1327    State(state): State<crate::ServerState>,
1328    headers: axum::http::HeaderMap,
1329) -> Response {
1330    let Some(ref auth) = state.auth else {
1331        // Auth not configured — always authenticated (no auth required)
1332        return axum::Json(serde_json::json!({
1333            "authenticated": true,
1334            "auth_enabled": false
1335        }))
1336        .into_response();
1337    };
1338
1339    let cookie_header = headers
1340        .get(header::COOKIE)
1341        .and_then(|v| v.to_str().ok())
1342        .unwrap_or("");
1343
1344    // Also try Authorization: Bearer header
1345    let bearer = headers
1346        .get(header::AUTHORIZATION)
1347        .and_then(|v| v.to_str().ok())
1348        .and_then(|v| v.strip_prefix("Bearer "))
1349        .map(String::from);
1350
1351    let token = bearer
1352        .clone()
1353        .or_else(|| extract_token_from_cookies(cookie_header, &auth.config.cookie_name));
1354
1355    let Some(cookie_value) = token else {
1356        return axum::Json(serde_json::json!({
1357            "authenticated": false,
1358            "auth_enabled": true
1359        }))
1360        .into_response();
1361    };
1362
1363    // Dev mode token (stored directly in cookie, no session manager)
1364    // Only report as authenticated when dev mode is currently enabled
1365    if cookie_value.starts_with("dev:") && auth.config.dev_config.local_dev_mode {
1366        let parts: Vec<&str> = cookie_value.splitn(4, ':').collect();
1367        if parts.len() >= 4 {
1368            return axum::Json(serde_json::json!({
1369                "authenticated": true,
1370                "auth_enabled": true,
1371                "email": parts[1],
1372                "name": parts[2],
1373                "username": parts[3],
1374                "dev_mode": true
1375            }))
1376            .into_response();
1377        }
1378    }
1379
1380    // Bearer header = raw JWT; Cookie value = session_id → resolve to access token
1381    let access_token = if bearer.is_some() {
1382        // Already have the raw token from Bearer header
1383        cookie_value
1384    } else {
1385        // Cookie value is a session_id — resolve via WebSessionManager
1386        match auth.session_manager.get_token(&cookie_value).await {
1387            Ok(token) => token,
1388            Err(e) => {
1389                tracing::debug!("Session token resolution failed for /auth/me: {}", e);
1390                return axum::Json(serde_json::json!({
1391                    "authenticated": false,
1392                    "auth_enabled": true
1393                }))
1394                .into_response();
1395            }
1396        }
1397    };
1398
1399    // Real JWT — validate and return claims
1400    match auth.validate_token(&access_token).await {
1401        Ok(claims) => axum::Json(serde_json::json!({
1402            "authenticated": true,
1403            "auth_enabled": true,
1404            "sub": claims.sub,
1405            "email": claims.email,
1406            "name": claims.name,
1407            "username": claims.preferred_username,
1408            "dev_mode": false
1409        }))
1410        .into_response(),
1411        Err(e) => {
1412            tracing::debug!("Token validation failed for /auth/me: {}", e);
1413            axum::Json(serde_json::json!({
1414                "authenticated": false,
1415                "auth_enabled": true
1416            }))
1417            .into_response()
1418        }
1419    }
1420}
1421
1422/// POST /auth/logout — destroy session and clear auth cookie.
1423async fn logout_handler(
1424    State(state): State<crate::ServerState>,
1425    headers: axum::http::HeaderMap,
1426) -> Response {
1427    let cookie_name = state
1428        .auth
1429        .as_ref()
1430        .map(|a| a.config.cookie_name.as_str())
1431        .unwrap_or("trustee_token");
1432
1433    // Destroy the session on the server side
1434    if let Some(ref auth) = state.auth {
1435        if let Some(cookie_header) = headers.get(header::COOKIE).and_then(|v| v.to_str().ok()) {
1436            if let Some(session_id) = extract_token_from_cookies(cookie_header, cookie_name) {
1437                if !session_id.starts_with("dev:") {
1438                    let _ = auth.session_manager.destroy_session(&session_id);
1439                }
1440            }
1441        }
1442    }
1443
1444    let cookie = Cookie::build((cookie_name.to_string(), ""))
1445        .path("/")
1446        .http_only(true)
1447        .same_site(SameSite::Lax)
1448        .max_age(TimeDuration::seconds(-1))
1449        .build();
1450
1451    Response::builder()
1452        .status(StatusCode::FOUND)
1453        .header(header::LOCATION, "/")
1454        .header(header::SET_COOKIE, cookie.to_string())
1455        .body(Body::empty())
1456        .unwrap()
1457}
1458
1459// ---------------------------------------------------------------------------
1460// MCP auth routes: /auth/mcp/login, /callback, /status, /logout (C2)
1461// ---------------------------------------------------------------------------
1462
1463/// Query parameters for MCP login initiation.
1464#[derive(Debug, Deserialize)]
1465pub struct McpLoginQuery {
1466    pub cred: String,
1467}
1468
1469/// Query parameters for MCP OIDC callback.
1470#[derive(Debug, Deserialize)]
1471pub struct McpCallbackQuery {
1472    pub code: Option<String>,
1473    pub state: Option<String>,
1474    pub error: Option<String>,
1475    pub error_description: Option<String>,
1476}
1477
1478/// GET /auth/mcp/login?cred=<name> — initiate per-server OIDC PKCE login.
1479///
1480/// Reads the credential config from the session's config_toml, verifies it's
1481/// `type = "web-interactive"`, then redirects to the OIDC provider.
1482async fn mcp_login_handler(
1483    State(state): State<crate::ServerState>,
1484    Query(query): Query<McpLoginQuery>,
1485    headers: axum::http::HeaderMap,
1486) -> Result<Response, AuthError> {
1487    // Require authentication — user must be logged into trustee-web
1488    let (_cookie, _user_key) = crate::auth::check_auth(
1489        &state.auth,
1490        &headers,
1491        crate::auth::actions::UPDATE_MCP_CREDENTIALS,
1492    )
1493    .await
1494    .map_err(|_| AuthError::AuthNotConfigured)?;
1495
1496    let auth = state.auth.as_ref().ok_or(AuthError::AuthNotConfigured)?;
1497
1498    // Parse MCP credential config from session's config_toml
1499    let cred_config = load_mcp_credential(&state, &query.cred).await?;
1500
1501    let (issuer_url, client_id, client_secret, scope) = match &cred_config {
1502        McpCredentialInfo::WebInteractive {
1503            issuer_url,
1504            client_id,
1505            client_secret,
1506            scope,
1507        } => (
1508            issuer_url.clone(),
1509            client_id.clone(),
1510            client_secret.clone(),
1511            scope.clone(),
1512        ),
1513        _ => {
1514            return Ok(Redirect::temporary(&format!(
1515                "/?mcp_error={}",
1516                urlencoding::encode(&format!(
1517                    "Credential '{}' is not web-interactive type",
1518                    query.cred
1519                ))
1520            ))
1521            .into_response());
1522        }
1523    };
1524
1525    // Build PKCE pair using a separate PkceCookieManager for MCP
1526    let oidc_client = OidcClient::new();
1527    let verifier = OidcClient::generate_code_verifier();
1528    let challenge = OidcClient::generate_code_challenge(&verifier);
1529    let oauth_state = OidcClient::generate_state();
1530
1531    // Build OidcClientConfig for the MCP credential's OIDC client
1532    let mcp_redirect_uri = format!(
1533        "{}/auth/mcp/callback",
1534        auth.client_config
1535            .redirect_uri
1536            .trim_end_matches('/')
1537            .trim_end_matches("/auth/callback")
1538    );
1539
1540    let mcp_client_config = OidcClientConfig {
1541        issuer_url: issuer_url.clone(),
1542        client_id: client_id.clone(),
1543        client_secret: client_secret.clone(),
1544        redirect_uri: mcp_redirect_uri.clone(),
1545        scope: scope.clone(),
1546        code_challenge_method: "S256".to_string(),
1547    };
1548
1549    // Build authorization URL
1550    let auth_url = oidc_client
1551        .build_authorization_url(&mcp_client_config, &oauth_state, Some(&challenge))
1552        .await
1553        .map_err(|e| AuthError::OidcError(e.to_string()))?;
1554
1555    // Store PKCE state + credential name in the in-memory map
1556    mcp_pkce()
1557        .insert(oauth_state.clone(), verifier.clone(), query.cred.clone())
1558        .await;
1559
1560    tracing::info!(
1561        "Initiating MCP browser login for credential '{}' (issuer={})",
1562        query.cred,
1563        issuer_url
1564    );
1565
1566    Ok(Response::builder()
1567        .status(StatusCode::TEMPORARY_REDIRECT)
1568        .header(header::LOCATION, &auth_url)
1569        .body(Body::empty())
1570        .unwrap())
1571}
1572
1573/// GET /auth/mcp/callback — handle MCP OIDC callback, store tokens.
1574async fn mcp_callback_handler(
1575    State(state): State<crate::ServerState>,
1576    Query(query): Query<McpCallbackQuery>,
1577    _headers: axum::http::HeaderMap,
1578) -> Result<Response, AuthError> {
1579    let auth = state.auth.as_ref().ok_or(AuthError::AuthNotConfigured)?;
1580
1581    // Check for errors from IdP
1582    if let Some(error) = query.error {
1583        let desc = query.error_description.unwrap_or_default();
1584        tracing::error!("MCP OIDC error: {} - {}", error, desc);
1585        return Ok(Redirect::temporary(&format!(
1586            "/?mcp_error={}&error_description={}",
1587            urlencoding::encode(&error),
1588            urlencoding::encode(&desc)
1589        ))
1590        .into_response());
1591    }
1592
1593    let code = query.code.ok_or(AuthError::MissingCode)?;
1594    let oauth_state = query.state.ok_or(AuthError::MissingState)?;
1595
1596    // Look up PKCE verifier + credential name from in-memory store
1597    let pkce_data = mcp_pkce()
1598        .take(&oauth_state)
1599        .await
1600        .ok_or(AuthError::InvalidState)?;
1601
1602    let verifier = pkce_data.verifier;
1603    let cred_name = &pkce_data.cred_name;
1604
1605    // Parse the MCP credential config to get OIDC settings for token exchange
1606    let cred_config = load_mcp_credential(&state, cred_name).await?;
1607
1608    let (issuer_url, client_id, client_secret, scope) = match &cred_config {
1609        McpCredentialInfo::WebInteractive {
1610            issuer_url,
1611            client_id,
1612            client_secret,
1613            scope,
1614        } => (
1615            issuer_url.clone(),
1616            client_id.clone(),
1617            client_secret.clone(),
1618            scope.clone(),
1619        ),
1620        _ => {
1621            return Ok(Redirect::temporary(&format!(
1622                "/?mcp_error={}",
1623                urlencoding::encode("Credential is not web-interactive type")
1624            ))
1625            .into_response());
1626        }
1627    };
1628
1629    // Build redirect URI (must match what was used in login)
1630    let mcp_redirect_uri = format!(
1631        "{}/auth/mcp/callback",
1632        auth.client_config
1633            .redirect_uri
1634            .trim_end_matches('/')
1635            .trim_end_matches("/auth/callback")
1636    );
1637
1638    let mcp_client_config = OidcClientConfig {
1639        issuer_url: issuer_url.clone(),
1640        client_id: client_id.clone(),
1641        client_secret: client_secret.clone(),
1642        redirect_uri: mcp_redirect_uri,
1643        scope: scope.clone(),
1644        code_challenge_method: "S256".to_string(),
1645    };
1646
1647    // Exchange code for tokens
1648    tracing::info!(
1649        "Exchanging MCP authorization code for tokens (credential={})",
1650        cred_name
1651    );
1652    let oidc_client = OidcClient::new();
1653    let token_response = oidc_client
1654        .exchange_code_for_tokens(&mcp_client_config, &code, Some(&verifier))
1655        .await
1656        .map_err(|e| AuthError::TokenExchangeFailed(e.to_string()))?;
1657
1658    // Compute expires_at
1659    let expires_at = {
1660        let now = std::time::SystemTime::now()
1661            .duration_since(std::time::UNIX_EPOCH)
1662            .unwrap_or_default()
1663            .as_secs();
1664        let expires_epoch = now + token_response.expires_in.unwrap_or(900);
1665        let days = expires_epoch / 86400;
1666        let rem = expires_epoch % 86400;
1667        let h = rem / 3600;
1668        let m = (rem % 3600) / 60;
1669        let s = rem % 60;
1670        let z = days as i64 + 719468;
1671        let era = if z >= 0 { z } else { z - 146096 } / 146097;
1672        let doe = (z - era * 146097) as u64;
1673        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
1674        let y = yoe as i64 + era * 400;
1675        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1676        let mp = (5 * doy + 2) / 153;
1677        let d = doy - (153 * mp + 2) / 5 + 1;
1678        let mon = if mp < 10 { mp + 3 } else { mp - 9 };
1679        let yr = if mon <= 2 { y + 1 } else { y };
1680        format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", yr, mon, d, h, m, s)
1681    };
1682
1683    // Store via FileTokenStore (same as `trustee mcp auth`)
1684    use pep::{FileTokenStore, StoredToken, TokenStore};
1685
1686    let stored = StoredToken::new(
1687        &token_response.access_token,
1688        token_response.refresh_token.clone(),
1689        "Bearer",
1690        &expires_at,
1691        token_response.scope.clone(),
1692    );
1693
1694    let agent_name = state
1695        .config_toml
1696        .as_ref()
1697        .and_then(|t| {
1698            toml::from_str::<toml::Value>(t).ok().and_then(|v| {
1699                v.get("agent")
1700                    .and_then(|a| a.get("name"))
1701                    .and_then(|n| n.as_str())
1702                    .map(String::from)
1703            })
1704        })
1705        .unwrap_or_else(|| "trustee".to_string());
1706    let token_store = FileTokenStore::new(&agent_name);
1707
1708    if let Err(e) = token_store.save(cred_name, &stored) {
1709        tracing::error!("Failed to store MCP token: {}", e);
1710        return Ok(Redirect::temporary(&format!(
1711            "/?mcp_error={}",
1712            urlencoding::encode(&format!("Failed to store token: {}", e))
1713        ))
1714        .into_response());
1715    }
1716
1717    tracing::info!(
1718        "MCP authentication successful for credential '{}' (expires {})",
1719        cred_name,
1720        expires_at
1721    );
1722
1723    Ok(Response::builder()
1724        .status(StatusCode::FOUND)
1725        .header(
1726            header::LOCATION,
1727            format!("/?mcp_connected={}", urlencoding::encode(cred_name)),
1728        )
1729        .body(Body::empty())
1730        .unwrap())
1731}
1732
1733/// GET /auth/mcp/status — return connection status for all MCP credentials.
1734/// v0.19.8: pub(crate) — the xagent impersonation lane (thq console relay)
1735/// serves the SAME handler at /xagent/{agent}/api/v1/mcp/status so the
1736/// console's MCP Connections overlay works on the split topology.
1737pub(crate) async fn mcp_status_handler(
1738    State(state): State<crate::ServerState>,
1739    headers: axum::http::HeaderMap,
1740) -> Response {
1741    use pep::{FileTokenStore, TokenStore};
1742
1743    // Require auth
1744    let (_cookie, _user_key) = match crate::auth::check_auth(
1745        &state.auth,
1746        &headers,
1747        crate::auth::actions::VIEW_MCP_CREDENTIALS,
1748    )
1749    .await
1750    {
1751        Ok(result) => result,
1752        Err(code) => {
1753            return (code, Json(serde_json::json!({"error": "Unauthorized"}))).into_response()
1754        }
1755    };
1756
1757    // Parse MCP config from the SHARED config — the session's config_toml is
1758    // a copy of it (create_session clones state.config_toml; per-user
1759    // isolation touches home_dir/project_id, not the config). Reading it
1760    // directly removes the active-session dependency (legacy routes retired,
1761    // pointer machinery removed — Ravand 2026-10-27).
1762    let config_toml = match &state.config_toml {
1763        Some(t) => t.clone(),
1764        None => return (StatusCode::INTERNAL_SERVER_ERROR, "Config not loaded").into_response(),
1765    };
1766
1767    let mcp_config: toml::Value = match toml::from_str(&config_toml) {
1768        Ok(v) => v,
1769        Err(_) => return Json(serde_json::json!([])).into_response(),
1770    };
1771
1772    // Agent name from the shared config ([agent].name) — same value the
1773    // session carried (create_session copies it from the same config).
1774    let agent_name = {
1775        let table: toml::Table = toml::from_str(&config_toml).unwrap_or_default();
1776        table
1777            .get("agent")
1778            .and_then(|a| a.get("name"))
1779            .and_then(|n| n.as_str())
1780            .unwrap_or("trustee")
1781            .to_string()
1782    };
1783    let token_store = FileTokenStore::new(&agent_name);
1784
1785    // Build server → credential mapping
1786    let servers = mcp_config
1787        .get("mcp")
1788        .and_then(|m| m.get("servers"))
1789        .and_then(|s| s.as_array());
1790    let credentials = mcp_config
1791        .get("mcp")
1792        .and_then(|m| m.get("credentials"))
1793        .and_then(|c| c.as_table());
1794
1795    let mut cred_servers: std::collections::HashMap<String, Vec<String>> =
1796        std::collections::HashMap::new();
1797    if let Some(servers) = servers {
1798        for server in servers {
1799            let name = server.get("name").and_then(|n| n.as_str()).unwrap_or("");
1800            let cred_ref = server
1801                .get("credentials")
1802                .and_then(|c| c.as_str())
1803                .unwrap_or("");
1804            if !cred_ref.is_empty() {
1805                cred_servers
1806                    .entry(cred_ref.to_string())
1807                    .or_default()
1808                    .push(name.to_string());
1809            }
1810        }
1811    }
1812
1813    let mut result = Vec::new();
1814
1815    if let Some(creds) = credentials {
1816        for (cred_name, cred_config) in creds {
1817            let cred_type = cred_config
1818                .get("type")
1819                .and_then(|t| t.as_str())
1820                .unwrap_or("unknown");
1821            let servers_using = cred_servers.get(cred_name).cloned().unwrap_or_default();
1822
1823            if cred_type == "web-session" {
1824                // Session credentials are always "connected" if auth is enabled
1825                let connected = state.auth.is_some();
1826                result.push(serde_json::json!({
1827                    "credential": cred_name,
1828                    "type": cred_type,
1829                    "connected": connected,
1830                    "servers": servers_using,
1831                }));
1832            } else if cred_type == "service-account" {
1833                // Long-lived service token, exchanged lazily (RFC 8693) by the
1834                // agent at runtime. "Connected" = the service_token resolved to
1835                // a non-empty value in this (already ${VAR}-substituted) config.
1836                let token = cred_config
1837                    .get("service_token")
1838                    .and_then(|t| t.as_str())
1839                    .unwrap_or("");
1840                result.push(serde_json::json!({
1841                    "credential": cred_name,
1842                    "type": cred_type,
1843                    "connected": !token.is_empty(),
1844                    "servers": servers_using,
1845                }));
1846            } else if cred_type == "static" {
1847                // Static token — connected when it resolved non-empty.
1848                let token = cred_config
1849                    .get("token")
1850                    .and_then(|t| t.as_str())
1851                    .unwrap_or("");
1852                result.push(serde_json::json!({
1853                    "credential": cred_name,
1854                    "type": cred_type,
1855                    "connected": !token.is_empty(),
1856                    "servers": servers_using,
1857                }));
1858            } else if cred_type == "web-interactive" || cred_type == "interactive" {
1859                // Check token store
1860                let status = match token_store.load(cred_name) {
1861                    Ok(Some(token)) => {
1862                        let expired = token.is_expired();
1863                        serde_json::json!({
1864                            "credential": cred_name,
1865                            "type": cred_type,
1866                            "connected": !expired,
1867                            "expires_at": token.expires_at,
1868                            "servers": servers_using,
1869                        })
1870                    }
1871                    _ => serde_json::json!({
1872                        "credential": cred_name,
1873                        "type": cred_type,
1874                        "connected": false,
1875                        "servers": servers_using,
1876                    }),
1877                };
1878                result.push(status);
1879            }
1880        }
1881    }
1882
1883    Json(serde_json::Value::Array(result)).into_response()
1884}
1885
1886/// POST /auth/mcp/logout?cred=<name> — remove stored MCP tokens.
1887async fn mcp_logout_handler(
1888    State(state): State<crate::ServerState>,
1889    Query(query): Query<McpLoginQuery>,
1890    headers: axum::http::HeaderMap,
1891) -> Response {
1892    use pep::{FileTokenStore, TokenStore};
1893
1894    // Require auth
1895    let (_cookie, _user_key) = match crate::auth::check_auth(
1896        &state.auth,
1897        &headers,
1898        crate::auth::actions::UPDATE_MCP_CREDENTIALS,
1899    )
1900    .await
1901    {
1902        Ok(result) => result,
1903        Err(code) => {
1904            return (code, Json(serde_json::json!({"error": "Unauthorized"}))).into_response()
1905        }
1906    };
1907
1908    // Agent name from the shared config ([agent].name) — same value the
1909    // session carried (create_session copies it from the same config).
1910    let agent_name = {
1911        let config_toml = state.config_toml.clone().unwrap_or_default();
1912        let table: toml::Table = toml::from_str(&config_toml).unwrap_or_default();
1913        table
1914            .get("agent")
1915            .and_then(|a| a.get("name"))
1916            .and_then(|n| n.as_str())
1917            .unwrap_or("trustee")
1918            .to_string()
1919    };
1920    let token_store = FileTokenStore::new(&agent_name);
1921
1922    match token_store.delete(&query.cred) {
1923        Ok(()) => {
1924            tracing::info!("Removed MCP credentials for '{}'", query.cred);
1925            Json(serde_json::json!({"success": true})).into_response()
1926        }
1927        Err(e) => {
1928            tracing::error!("Failed to remove MCP credentials: {}", e);
1929            (
1930                StatusCode::INTERNAL_SERVER_ERROR,
1931                Json(serde_json::json!({"error": e.to_string()})),
1932            )
1933                .into_response()
1934        }
1935    }
1936}
1937
1938// ---------------------------------------------------------------------------
1939// MCP auth helpers
1940// ---------------------------------------------------------------------------
1941
1942/// In-memory store for MCP PKCE state (state token → verifier + credential name).
1943/// Entries expire after 10 minutes. Not persisted across restarts.
1944struct McpPkceStore {
1945    entries: tokio::sync::Mutex<std::collections::HashMap<String, McpPkceEntry>>,
1946}
1947
1948struct McpPkceEntry {
1949    verifier: String,
1950    cred_name: String,
1951    created_at: std::time::Instant,
1952}
1953
1954impl McpPkceStore {
1955    fn new() -> Self {
1956        Self {
1957            entries: tokio::sync::Mutex::new(std::collections::HashMap::new()),
1958        }
1959    }
1960
1961    /// Insert a PKCE entry. Cleans up entries older than 10 minutes.
1962    async fn insert(&self, state: String, verifier: String, cred_name: String) {
1963        let mut map = self.entries.lock().await;
1964        // Cleanup expired entries (older than 10 min)
1965        let cutoff = std::time::Instant::now() - std::time::Duration::from_secs(600);
1966        map.retain(|_, v| v.created_at > cutoff);
1967        map.insert(
1968            state,
1969            McpPkceEntry {
1970                verifier,
1971                cred_name,
1972                created_at: std::time::Instant::now(),
1973            },
1974        );
1975    }
1976
1977    /// Take and remove a PKCE entry (single-use).
1978    async fn take(&self, state: &str) -> Option<McpPkceEntry> {
1979        let mut map = self.entries.lock().await;
1980        map.remove(state)
1981    }
1982}
1983
1984/// Global singleton PKCE store for MCP browser logins.
1985static MCP_PKCE: std::sync::OnceLock<McpPkceStore> = std::sync::OnceLock::new();
1986
1987/// Get or initialize the global MCP PKCE store.
1988fn mcp_pkce() -> &'static McpPkceStore {
1989    MCP_PKCE.get_or_init(McpPkceStore::new)
1990}
1991
1992/// Simplified MCP credential info (parsed from TOML).
1993enum McpCredentialInfo {
1994    WebInteractive {
1995        issuer_url: String,
1996        client_id: String,
1997        client_secret: Option<String>,
1998        scope: String,
1999    },
2000    Other(String),
2001}
2002
2003/// Load a specific MCP credential from the session's config_toml.
2004async fn load_mcp_credential(
2005    state: &crate::ServerState,
2006    cred_name: &str,
2007) -> Result<McpCredentialInfo, AuthError> {
2008    let config_toml = state
2009        .config_toml
2010        .clone()
2011        .ok_or(AuthError::AuthNotConfigured)?;
2012
2013    let config: toml::Value = toml::from_str(&config_toml)
2014        .map_err(|e| AuthError::OidcError(format!("Config parse error: {}", e)))?;
2015
2016    let cred = config
2017        .get("mcp")
2018        .and_then(|m| m.get("credentials"))
2019        .and_then(|c| c.as_table())
2020        .and_then(|c| c.get(cred_name))
2021        .ok_or_else(|| AuthError::OidcError(format!("Credential '{}' not found", cred_name)))?;
2022
2023    let cred_type = cred
2024        .get("type")
2025        .and_then(|t| t.as_str())
2026        .unwrap_or("unknown");
2027
2028    match cred_type {
2029        "web-interactive" => {
2030            let issuer_url = cred
2031                .get("issuer_url")
2032                .and_then(|v| v.as_str())
2033                .ok_or_else(|| AuthError::OidcError("Missing issuer_url".into()))?
2034                .to_string();
2035            let client_id = cred
2036                .get("client_id")
2037                .and_then(|v| v.as_str())
2038                .ok_or_else(|| AuthError::OidcError("Missing client_id".into()))?
2039                .to_string();
2040            let client_secret = cred
2041                .get("client_secret")
2042                .and_then(|v| v.as_str())
2043                .map(String::from);
2044            let scope = cred
2045                .get("scope")
2046                .and_then(|v| v.as_str())
2047                .unwrap_or("openid profile email")
2048                .to_string();
2049
2050            Ok(McpCredentialInfo::WebInteractive {
2051                issuer_url,
2052                client_id,
2053                client_secret,
2054                scope,
2055            })
2056        }
2057        other => Ok(McpCredentialInfo::Other(other.to_string())),
2058    }
2059}
2060
2061// ---------------------------------------------------------------------------
2062// Helpers
2063// ---------------------------------------------------------------------------
2064
2065/// Create an HttpOnly auth cookie.
2066fn create_auth_cookie(
2067    name: &str,
2068    value: &str,
2069    max_age: StdDuration,
2070    secure: bool,
2071) -> Cookie<'static> {
2072    Cookie::build((name.to_string(), value.to_string()))
2073        .path("/")
2074        .http_only(true)
2075        .same_site(SameSite::Lax)
2076        .secure(secure)
2077        .max_age(TimeDuration::seconds(max_age.as_secs() as i64))
2078        .build()
2079}
2080
2081// ---------------------------------------------------------------------------
2082// Error handling
2083// ---------------------------------------------------------------------------
2084
2085/// Authentication errors.
2086#[derive(Debug)]
2087pub enum AuthError {
2088    MissingCode,
2089    MissingState,
2090    InvalidState,
2091    OidcError(String),
2092    TokenExchangeFailed(String),
2093    AuthNotConfigured,
2094}
2095
2096impl IntoResponse for AuthError {
2097    fn into_response(self) -> Response {
2098        let (_status, msg) = match self {
2099            AuthError::MissingCode => (StatusCode::BAD_REQUEST, "Missing authorization code"),
2100            AuthError::MissingState => (StatusCode::BAD_REQUEST, "Missing state parameter"),
2101            AuthError::InvalidState => (StatusCode::BAD_REQUEST, "Invalid or expired state"),
2102            AuthError::OidcError(_) => (
2103                StatusCode::SERVICE_UNAVAILABLE,
2104                "Authentication service error",
2105            ),
2106            AuthError::TokenExchangeFailed(_) => (StatusCode::BAD_REQUEST, "Token exchange failed"),
2107            AuthError::AuthNotConfigured => {
2108                (StatusCode::NOT_IMPLEMENTED, "Authentication not configured")
2109            }
2110        };
2111        Redirect::temporary(&format!("/?error={}", urlencoding::encode(msg))).into_response()
2112    }
2113}
2114
2115#[cfg(test)]
2116mod principal_tests {
2117    use super::*;
2118    use pep::oidc::types::JwtClaims;
2119
2120    fn claims_with_role(role: serde_json::Value) -> JwtClaims {
2121        let mut c = JwtClaims::default();
2122        c.sub = "sub-uuid".to_string();
2123        c.preferred_username = Some("farzan".to_string());
2124        c.extra.insert("role".to_string(), role);
2125        c
2126    }
2127
2128    // -- dev_user_key (16D dev:agent namespace) ------------------------------
2129
2130    #[test]
2131    fn dev_agent_token_yields_agent_namespaced_key() {
2132        assert_eq!(
2133            dev_user_key("dev:agent:farzan"),
2134            Some("agent-farzan".to_string())
2135        );
2136        assert_eq!(
2137            dev_user_key("dev:agent:paydar"),
2138            Some("agent-paydar".to_string())
2139        );
2140    }
2141
2142    #[test]
2143    fn dev_agent_token_rejects_empty_and_colon_names() {
2144        assert_eq!(dev_user_key("dev:agent:"), None);
2145        assert_eq!(dev_user_key("dev:agent:  "), None);
2146        assert_eq!(
2147            dev_user_key("dev:agent:a:b"),
2148            None,
2149            "name must not contain ':'"
2150        );
2151    }
2152
2153    #[test]
2154    fn dev_human_token_format_unchanged() {
2155        assert_eq!(
2156            dev_user_key("dev:a@b.c:Some Name:someuser"),
2157            Some("dev:a@b.c".to_string())
2158        );
2159        assert_eq!(dev_user_key("dev:only:two"), None);
2160    }
2161
2162    // -- claim_role / PrincipalKind (string OR array role) --------------------
2163
2164    #[test]
2165    fn role_as_string_classifies_agent() {
2166        let c = claims_with_role(serde_json::json!("agent"));
2167        assert_eq!(claim_role(&c).as_deref(), Some("agent"));
2168        assert_eq!(AuthUser::from(c).kind, PrincipalKind::Agent);
2169    }
2170
2171    #[test]
2172    fn role_as_array_takes_first_value() {
2173        // Kanidm may deliver role as an array (pep 366e8ed lesson).
2174        let c = claims_with_role(serde_json::json!(["agent", "other"]));
2175        assert_eq!(claim_role(&c).as_deref(), Some("agent"));
2176        assert_eq!(AuthUser::from(c).kind, PrincipalKind::Agent);
2177    }
2178
2179    #[test]
2180    fn non_agent_roles_classify_human() {
2181        for role in ["user", "admin", "service"] {
2182            let c = claims_with_role(serde_json::json!(role));
2183            assert_eq!(claim_role(&c).as_deref(), Some(role));
2184            assert_eq!(AuthUser::from(c).kind, PrincipalKind::Human, "role={role}");
2185        }
2186    }
2187
2188    #[test]
2189    fn missing_or_nonstring_role_classifies_human() {
2190        let mut c = JwtClaims::default();
2191        c.sub = "sub-uuid".to_string();
2192        assert_eq!(claim_role(&c), None);
2193        assert_eq!(AuthUser::from(c.clone()).kind, PrincipalKind::Human);
2194        c.extra.insert("role".to_string(), serde_json::json!(42));
2195        assert_eq!(claim_role(&c), None, "non-string non-array role ignored");
2196    }
2197
2198    // -- jwt_user_key (PINNED: preferred_username || sub, never email) --------
2199
2200    #[test]
2201    fn user_key_prefers_preferred_username() {
2202        let mut c = JwtClaims::default();
2203        c.sub = "sub-uuid".to_string();
2204        c.preferred_username = Some("farzan".to_string());
2205        c.email = Some("rebindable@example.com".to_string());
2206        assert_eq!(jwt_user_key(&c), "farzan", "email must never be the key");
2207    }
2208
2209    #[test]
2210    fn user_key_falls_back_to_sub_on_blank_username() {
2211        let mut c = JwtClaims::default();
2212        c.sub = "sub-uuid".to_string();
2213        c.preferred_username = Some("   ".to_string());
2214        assert_eq!(jwt_user_key(&c), "sub-uuid");
2215        c.preferred_username = None;
2216        assert_eq!(jwt_user_key(&c), "sub-uuid");
2217    }
2218
2219    #[test]
2220    fn user_key_agent_pinned_to_sub_even_with_username() {
2221        // 16E: agent principals NEVER use preferred_username — a future
2222        // token-scope change must not re-home agent namespaces.
2223        let mut c = claims_with_role(serde_json::json!("agent"));
2224        c.sub = "agent-sub-uuid".to_string();
2225        c.preferred_username = Some("farzan".to_string());
2226        assert_eq!(jwt_user_key(&c), "agent-sub-uuid");
2227    }
2228
2229    #[test]
2230    fn authuser_carries_role_and_kind() {
2231        let c = claims_with_role(serde_json::json!("agent"));
2232        let u = AuthUser::from(c);
2233        assert_eq!(u.role.as_deref(), Some("agent"));
2234        assert_eq!(u.kind, PrincipalKind::Agent);
2235        assert_eq!(u.username.as_deref(), Some("farzan"));
2236    }
2237}
2238
2239#[cfg(test)]
2240mod cedar_p2_tests {
2241    use super::*;
2242    use cedar_policy::{Context, Entities, EntityUid, Request};
2243    use pep::cedar::{CedarAuthorizer, CedarConfig};
2244    use std::collections::HashMap;
2245
2246    const POLICY: &str = include_str!("../policies/trustee_default.cedar");
2247    const SCHEMA: &str = include_str!("../policies/trustee_schema.cedarschema");
2248
2249    async fn authorizer() -> CedarAuthorizer {
2250        // Unique per call: tests run concurrently and must not share files.
2251        static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2252        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2253        let dir = std::env::temp_dir().join(format!("trustee-cedar-p2-{}-{n}", std::process::id()));
2254        std::fs::create_dir_all(&dir).expect("temp dir");
2255        let policy_path = dir.join("trustee_default.cedar");
2256        let schema_path = dir.join("trustee_schema.cedarschema");
2257        std::fs::write(&policy_path, POLICY).expect("write policy");
2258        std::fs::write(&schema_path, SCHEMA).expect("write schema");
2259        let cfg = CedarConfig {
2260            policy_path,
2261            schema_path: Some(schema_path),
2262            entities_path: None,
2263            default_decision: pep::cedar::DefaultDecision::Deny,
2264            validate_on_load: true,
2265            policy_store_url: None,
2266            policy_store_token: None,
2267            embedded_policy: Some(POLICY),
2268            embedded_schema: Some(SCHEMA),
2269        };
2270        CedarAuthorizer::new_with_policy_store(cfg)
2271            .await
2272            .expect("Cedar init from shipped sources")
2273    }
2274
2275    fn claims_with_role(role: Option<&str>) -> JwtClaims {
2276        let mut c = JwtClaims::default();
2277        c.sub = "test-sub".to_string();
2278        if let Some(r) = role {
2279            c.extra.insert("role".to_string(), serde_json::json!(r));
2280        }
2281        c
2282    }
2283
2284    /// Mirrors check_cedar_authorized's request construction exactly.
2285    async fn allowed(auth: &CedarAuthorizer, role: Option<&str>, action: &str) -> bool {
2286        let claims = claims_with_role(role);
2287        let principal_entity = pep::cedar::build_principal_entity(&claims).unwrap();
2288        let app_entity = cedar_policy::Entity::new(
2289            EntityUid::from_str(r#"TrusteeApp::"default""#).unwrap(),
2290            HashMap::new(),
2291            std::collections::HashSet::new(),
2292        )
2293        .unwrap();
2294        let entities = Entities::from_entities(vec![principal_entity, app_entity], None).unwrap();
2295        let request = Request::new(
2296            pep::cedar::build_principal_uid(&claims).unwrap(),
2297            EntityUid::from_str(&format!("Action::\"{action}\"")).unwrap(),
2298            EntityUid::from_str(r#"TrusteeApp::"default""#).unwrap(),
2299            Context::empty(),
2300            None,
2301        )
2302        .unwrap();
2303        auth.is_allowed_with_entities(&request, &entities).allowed()
2304    }
2305
2306    #[tokio::test]
2307    async fn admin_allowed_including_destructive() {
2308        let auth = authorizer().await;
2309        for action in [
2310            actions::VIEW_SESSION,
2311            actions::COMMAND_SESSION,
2312            actions::DELETE_SESSION,
2313            actions::UPDATE_MCP_CREDENTIALS,
2314        ] {
2315            assert!(
2316                allowed(&auth, Some("admin"), action).await,
2317                "admin {action}"
2318            );
2319        }
2320    }
2321
2322    #[tokio::test]
2323    async fn user_full_session_management() {
2324        let auth = authorizer().await;
2325        for action in [
2326            actions::CREATE_SESSION,
2327            actions::COMMAND_SESSION,
2328            actions::DELETE_SESSION,
2329            actions::VIEW_HISTORY,
2330            actions::UPDATE_MCP_CREDENTIALS,
2331        ] {
2332            assert!(allowed(&auth, Some("user"), action).await, "user {action}");
2333        }
2334    }
2335
2336    #[tokio::test]
2337    async fn agent_working_set_including_delete() {
2338        let auth = authorizer().await;
2339        for action in [
2340            actions::CREATE_SESSION,
2341            actions::COMMAND_SESSION,
2342            actions::CANCEL_SESSION,
2343            actions::RESUME_SESSION,
2344            actions::VIEW_HISTORY,
2345            actions::UPDATE_MCP_CREDENTIALS,
2346            // Granted 2026-09-01 (trustee 0.15.2): the THQ agent console's
2347            // Terminate button dispatches AS the agent — agent-without-delete
2348            // made every console terminate 403. Containment: the agent token
2349            // scopes every session route to her OWN namespace.
2350            actions::DELETE_SESSION,
2351        ] {
2352            assert!(
2353                allowed(&auth, Some("agent"), action).await,
2354                "agent {action}"
2355            );
2356        }
2357    }
2358
2359    #[tokio::test]
2360    async fn service_read_only() {
2361        let auth = authorizer().await;
2362        for action in [
2363            actions::VIEW_SESSION,
2364            actions::LIST_SESSIONS,
2365            actions::VIEW_HISTORY,
2366        ] {
2367            assert!(
2368                allowed(&auth, Some("service"), action).await,
2369                "service {action}"
2370            );
2371        }
2372        for action in [actions::COMMAND_SESSION, actions::DELETE_SESSION] {
2373            assert!(
2374                !allowed(&auth, Some("service"), action).await,
2375                "service {action} denied"
2376            );
2377        }
2378    }
2379
2380    #[tokio::test]
2381    async fn missing_or_unknown_role_denied_everything() {
2382        let auth = authorizer().await;
2383        for role in [None, Some("intern"), Some("Admin")] {
2384            assert!(
2385                !allowed(&auth, role, actions::VIEW_SESSION).await,
2386                "role={role:?} must be denied (fail-closed default)"
2387            );
2388        }
2389    }
2390
2391    #[test]
2392    fn boot_decision_is_fail_closed() {
2393        assert!(crate::cedar_boot_decision(true, false, false).is_err());
2394        assert!(crate::cedar_boot_decision(true, false, true).is_ok());
2395        assert!(crate::cedar_boot_decision(true, true, false).is_ok());
2396        assert!(crate::cedar_boot_decision(false, false, false).is_ok());
2397    }
2398}
2399
2400/// Token validation cache (issue c41eb9d7) — pure-logic tests against a
2401/// standalone [`ValidationCache`]; no IdP, no network.
2402#[cfg(test)]
2403mod validation_cache_tests {
2404    use super::*;
2405    use std::sync::atomic::{AtomicUsize, Ordering};
2406
2407    fn claims_with(exp_in: i64, sub: &str) -> JwtClaims {
2408        let mut c = JwtClaims::default();
2409        c.exp = unix_now() + exp_in;
2410        c.sub = sub.to_string();
2411        c.preferred_username = Some("farzan".to_string());
2412        c
2413    }
2414
2415    /// ACCEPTANCE c41eb9d7: repeated polls = 1 validation, not 2.
2416    #[test]
2417    fn cache_hit_two_polls_one_validation() {
2418        let cache = ValidationCache::new();
2419        let validations = Arc::new(AtomicUsize::new(0));
2420        let key = validation_cache_key("token-A");
2421
2422        for _ in 0..2 {
2423            if cache.get(&key, unix_now()).is_some() {
2424                continue; // cache hit — poll served without validation
2425            }
2426            // stub: this block is the "real validation"
2427            validations.fetch_add(1, Ordering::SeqCst);
2428            cache.put(key, claims_with(3600, "sub-A"), unix_now());
2429        }
2430
2431        assert_eq!(
2432            validations.load(Ordering::SeqCst),
2433            1,
2434            "second poll must hit the cache, not re-validate"
2435        );
2436    }
2437
2438    /// Expiry: after valid_until the entry is a miss → re-validation.
2439    #[test]
2440    fn expired_entry_revalidates() {
2441        let cache = ValidationCache::new();
2442        let key = validation_cache_key("token-B");
2443        let now = unix_now();
2444        cache.put(key, claims_with(3600, "sub-B"), now);
2445
2446        assert!(cache.get(&key, now).is_some(), "fresh entry must hit");
2447        assert!(
2448            cache.get(&key, now + CACHE_TTL_SECS + 1).is_none(),
2449            "entry past valid_until must miss and force re-validation"
2450        );
2451    }
2452
2453    /// exp-grace: a token inside its last 120s is born stale — get() must
2454    /// never serve it, mirroring PEP's 60s skew leeway with margin.
2455    #[test]
2456    fn near_expiry_token_never_served_from_cache() {
2457        let cache = ValidationCache::new();
2458        let key = validation_cache_key("token-C");
2459        let now = unix_now();
2460        // exp in 60s → valid_until = exp - 120 < now
2461        cache.put(key, claims_with(60, "sub-C"), now);
2462        assert!(
2463            cache.get(&key, now).is_none(),
2464            "entry valid_until <= now must be rejected immediately"
2465        );
2466    }
2467
2468    /// Cap: at CACHE_MAX_ENTRIES the cache evicts instead of growing —
2469    /// correctness never depends on a hit (dropped entries re-validate).
2470    #[test]
2471    fn cap_evicts_instead_of_growing_unbounded() {
2472        let cache = ValidationCache::new();
2473        let now = unix_now();
2474        for i in 0..CACHE_MAX_ENTRIES {
2475            cache.put(
2476                validation_cache_key(&format!("tok-{i}")),
2477                claims_with(3600, "s"),
2478                now,
2479            );
2480        }
2481        // Map is all-hot → overflow clears rather than random-evicts.
2482        let overflow = validation_cache_key("tok-overflow");
2483        cache.put(overflow, claims_with(3600, "s"), now);
2484
2485        let inner = cache.inner.lock().unwrap();
2486        assert!(
2487            inner.entries.len() <= CACHE_MAX_ENTRIES,
2488            "cache must stay bounded"
2489        );
2490        assert!(
2491            inner.entries.contains_key(&overflow),
2492            "newest entry must survive"
2493        );
2494        assert!(
2495            !inner.entries.contains_key(&validation_cache_key("tok-0")),
2496            "pre-overflow entries were reset, not served stale forever"
2497        );
2498    }
2499
2500    /// INFO-vs-DEBUG gate: first sight per (sub, issuer), never again.
2501    #[test]
2502    fn first_sight_fires_once_per_sub_issuer_pair() {
2503        let cache = ValidationCache::new();
2504        assert!(cache.mark_first_sight("sub-A", "https://idp.tanbal.ir"));
2505        assert!(!cache.mark_first_sight("sub-A", "https://idp.tanbal.ir"));
2506        assert!(
2507            cache.mark_first_sight("sub-A", "https://other.tanbal.ir"),
2508            "different issuer = first sight"
2509        );
2510        assert!(
2511            cache.mark_first_sight("sub-B", "https://idp.tanbal.ir"),
2512            "different sub = first sight"
2513        );
2514    }
2515
2516    /// 128-bit truncated SHA-256: distinct tokens must not collide.
2517    #[test]
2518    fn distinct_tokens_distinct_keys() {
2519        assert_ne!(validation_cache_key("tok-1"), validation_cache_key("tok-2"));
2520        // Raw token material must not leak into the stored key
2521        assert_eq!(
2522            validation_cache_key("secret"),
2523            validation_cache_key("secret")
2524        );
2525    }
2526}