Skip to main content

plexus_auth_core/
auth.rs

1//! AuthContext and SessionValidator — relocated from plexus-core.
2//!
3//! Per AUTHZ-CORE-CRATE-1, the public type surface (fields, methods,
4//! constructors) is preserved verbatim from plexus-core's previous home at
5//! `plexus_core::plexus::auth`. The migration is mechanical; behavior is
6//! unchanged. plexus-core re-exports these from here with a `#[deprecated]`
7//! pointer at the new path so existing callers compile during the
8//! deprecation window.
9//!
10//! Future work tightens the seal on `AuthContext::new` and the field
11//! visibility (per AUTHZ-0 §"Crate-level isolation amplifies the seal").
12//! That tightening is intentionally NOT in this ticket because it would
13//! break ~30 direct construction sites across plexus-trak, plexus-transport
14//! tests, and others — a workspace-wide blast radius outside this ticket's
15//! scope. See `plans/AUTHZ/AUTHZ-CORE-CRATE-1-RUN-NOTES.md`.
16
17use async_trait::async_trait;
18use schemars::JsonSchema;
19use serde::{Deserialize, Serialize};
20use serde_json::Value;
21
22/// The metadata key under which a verified
23/// [`Principal`](crate::identity::Principal) is stamped.
24///
25/// See [`AuthContext::principal`] for why the principal lives in `metadata`
26/// rather than in a field of its own.
27pub const PRINCIPAL_CLAIM: &str = "principal";
28
29/// PERF.115-49: `raw` parsed as a principal — remembered for the last stamp
30/// this thread parsed, so a call that asks for its caller's principal three
31/// times (the liveness check, the gate's check and its own liveness check)
32/// validates it once. The memory is derived only: a private thread-local,
33/// written here and nowhere else, holding a stamp's exact text beside what
34/// [`str::parse`] made of it, and answered only for a byte-equal stamp —
35/// so it answers exactly what parsing would. Nothing outside this function
36/// can put a principal in it, and an `AuthContext` carries none of its own.
37fn parse_claim(raw: &str) -> Option<crate::identity::Principal> {
38    use crate::identity::Principal;
39    use std::cell::RefCell;
40    thread_local! {
41        static LAST: RefCell<Option<(Box<str>, Principal)>> = const { RefCell::new(None) };
42    }
43    let hit = LAST
44        .try_with(|last| last.try_borrow().ok().and_then(|l| l.as_ref().filter(|(text, _)| &**text == raw).map(|(_, p)| p.clone())))
45        .ok()
46        .flatten();
47    if hit.is_some() {
48        return hit;
49    }
50    let parsed = raw.parse::<Principal>().ok()?;
51    let _ = LAST.try_with(|last| {
52        if let Ok(mut last) = last.try_borrow_mut() {
53            *last = Some((raw.into(), parsed.clone()));
54        }
55    });
56    Some(parsed)
57}
58
59/// Per-connection authentication context, populated during WS upgrade.
60///
61/// This context is extracted from HTTP cookies (or other auth mechanisms) during
62/// the WebSocket handshake and attached to the connection. Every RPC call on that
63/// connection has access to this context.
64///
65/// # Multi-tenancy with Keycloak
66///
67/// When using Keycloak for multi-tenancy, the `AuthContext` typically contains:
68/// - `user_id`: Keycloak user ID (sub claim from JWT)
69/// - `session_id`: Keycloak session ID
70/// - `roles`: User roles within the tenant/realm
71/// - `metadata`: Additional JWT claims (realm, tenant ID, custom attributes)
72#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
73pub struct AuthContext {
74    /// User identifier (e.g., Keycloak sub claim, user UUID)
75    pub user_id: String,
76
77    /// Session identifier (e.g., Keycloak session ID)
78    pub session_id: String,
79
80    /// User roles (e.g., ["user", "admin"], Keycloak realm roles)
81    pub roles: Vec<String>,
82
83    /// Additional metadata (e.g., JWT claims, tenant/realm info, custom attributes)
84    /// For Keycloak multi-tenancy, this typically includes:
85    /// - `realm`: Keycloak realm name
86    /// - `tenant_id`: Organization/tenant identifier
87    /// - Any custom claims from the JWT token
88    pub metadata: Value,
89}
90
91impl AuthContext {
92    /// Create a new AuthContext.
93    ///
94    /// # Note
95    ///
96    /// This constructor is `pub` to preserve the existing public API across
97    /// the workspace. AUTHZ-0's structural-defense vision calls for this
98    /// constructor to be `pub(crate)`; tightening that seal lands in a
99    /// follow-up ticket because of the workspace-wide blast radius. See
100    /// `plans/AUTHZ/AUTHZ-CORE-CRATE-1-RUN-NOTES.md`.
101    pub fn new(user_id: String, session_id: String, roles: Vec<String>, metadata: Value) -> Self {
102        Self {
103            user_id,
104            session_id,
105            roles,
106            metadata,
107        }
108    }
109
110    /// Create an anonymous/unauthenticated context.
111    ///
112    /// This can be used as a fallback when methods accept `Option<&AuthContext>`
113    /// and no authentication was provided.
114    pub fn anonymous() -> Self {
115        Self {
116            user_id: "anonymous".to_string(),
117            session_id: String::new(),
118            roles: vec![],
119            metadata: Value::Null,
120        }
121    }
122
123    /// Create a context for a verified [`Principal`](crate::identity::Principal).
124    ///
125    /// The namespaced constructor: `user_id` is derived from the principal
126    /// rather than supplied, so the two cannot be set to different things.
127    /// Prefer building this through
128    /// [`Authenticated::into_auth_context`](crate::identity::Authenticated::into_auth_context),
129    /// which additionally requires a proof that authentication happened.
130    pub fn for_principal(
131        principal: &crate::identity::Principal,
132        session_id: impl Into<String>,
133        roles: Vec<String>,
134        metadata: Value,
135    ) -> Self {
136        let mut map = match metadata {
137            Value::Object(m) => m,
138            Value::Null => serde_json::Map::new(),
139            other => {
140                let mut m = serde_json::Map::new();
141                m.insert("claims".to_string(), other);
142                m
143            }
144        };
145        map.insert(
146            PRINCIPAL_CLAIM.to_string(),
147            Value::String(principal.to_string()),
148        );
149        Self {
150            user_id: principal.as_legacy_user_id(),
151            session_id: session_id.into(),
152            roles,
153            metadata: Value::Object(map),
154        }
155    }
156
157    /// The caller's namespaced [`Principal`](crate::identity::Principal).
158    ///
159    /// # Why this is a method and not a field
160    ///
161    /// PLX-82 requires this to be **additive**, and `AuthContext` has all-`pub`
162    /// fields that at least six sites across plexus-core, plexus-transport,
163    /// and plexus-macros construct with an exhaustive struct literal —
164    /// including `plexus_core::plexus::test_validator`, which is library code,
165    /// not a test. Adding a sixth field would fail to compile every one of
166    /// them, in crates this build is not permitted to modify. It would also
167    /// change the `Deserialize` and `JsonSchema` shape of a type that crosses
168    /// the wire.
169    ///
170    /// Deriving the principal instead costs nothing and buys something the
171    /// field could not: **`principal` and `user_id` cannot disagree, because
172    /// there is nowhere for them to disagree.** There is one storage location
173    /// for an idp identity, and both accessors read it.
174    ///
175    /// # Resolution order
176    ///
177    /// 1. `metadata["principal"]`, if present and parseable — this is what
178    ///    [`Authenticated::into_auth_context`] stamps, and it is the only
179    ///    route by which a non-idp principal (a `nostr:` pubkey, an
180    ///    `apikey:` id) can be carried.
181    /// 2. Otherwise `idp:<user_id>`, when `user_id` is a canonical UUID —
182    ///    the migration path for every context built before this build, and
183    ///    for any [`SessionValidator`] not yet ported to an
184    ///    [`Authenticator`](crate::identity::Authenticator).
185    ///
186    /// Returns `None` for anonymous contexts and for any `user_id` that is
187    /// not a plexus-idp UUID. `None` means "no principal can be named here",
188    /// never "authenticated as someone else".
189    ///
190    /// # This is a claim, not an authorization
191    ///
192    /// Same caveat as [`AuthContext::tenant_id`]: holding a `Principal` says
193    /// who the context names, not what it may do. The proof that
194    /// authentication occurred is
195    /// [`Authenticated`](crate::identity::Authenticated), which only an
196    /// `Authenticator` produces.
197    ///
198    /// [`Authenticated::into_auth_context`]: crate::identity::Authenticated::into_auth_context
199    pub fn principal(&self) -> Option<crate::identity::Principal> {
200        // PERF.115-49: the stamp read in place (no copy of it).
201        if let Some(raw) = self.metadata.get(PRINCIPAL_CLAIM).and_then(Value::as_str) {
202            // A present-but-unparseable stamp is a corrupt claim. Falling
203            // through to the `user_id` derivation would answer a different
204            // question than the one the stamp was trying to answer, so this
205            // is a hard `None`.
206            return parse_claim(raw);
207        }
208        crate::identity::Principal::from_legacy_user_id(&self.user_id)
209    }
210
211    /// Check if this context represents an authenticated user.
212    pub fn is_authenticated(&self) -> bool {
213        self.user_id != "anonymous" && !self.session_id.is_empty()
214    }
215
216    /// AUTH-11: whether the sign-in this context carries has passed its
217    /// [`EXPIRES_AT_KEY`] stamp (unix seconds). A context with no stamp
218    /// never expires by this test; its validator may still end it
219    /// ([`SessionValidator::alive`]).
220    pub fn expired(&self) -> bool {
221        let now = std::time::SystemTime::now()
222            .duration_since(std::time::UNIX_EPOCH)
223            .map(|d| d.as_secs() as i64)
224            .unwrap_or(i64::MAX);
225        self.metadata.get(EXPIRES_AT_KEY).and_then(Value::as_i64).is_some_and(|exp| exp <= now)
226    }
227
228    /// Check if the user has a specific role.
229    pub fn has_role(&self, role: &str) -> bool {
230        self.roles.iter().any(|r| r == role)
231    }
232
233    /// Get a metadata field as a string.
234    pub fn get_metadata_string(&self, key: &str) -> Option<String> {
235        self.metadata
236            .get(key)
237            .and_then(|v| v.as_str())
238            .map(String::from)
239    }
240
241    /// Get the tenant/realm from metadata (Keycloak multi-tenancy).
242    ///
243    /// Pre-UT-1 helper retained for compatibility. New code should prefer
244    /// [`AuthContext::tenant_id`], which returns the typed
245    /// [`TenantId`](crate::tenant::types::TenantId) and reads the
246    /// `org_id` claim first (UT-S01 D3).
247    pub fn tenant(&self) -> Option<String> {
248        self.get_metadata_string("tenant_id")
249            .or_else(|| self.get_metadata_string("realm"))
250    }
251
252    /// The caller's tenant identity as a typed
253    /// [`TenantId`](crate::tenant::types::TenantId), if present.
254    ///
255    /// Reads `metadata["org_id"]` first (the tenancy claim pinned by
256    /// UT-S01 D3 — Auth0 Organizations convention), falling back to the
257    /// legacy `metadata["tenant_id"]` key for one deprecation window
258    /// (validators write the value under both keys during that window).
259    ///
260    /// Returns `None` when neither key is present **or** when the value
261    /// fails `TenantId` validation (empty / overlong / non-printable) —
262    /// a malformed tenant claim must not flow into comparisons as if it
263    /// named a real tenant.
264    ///
265    /// Note this is the *claim*, not authorization: tenancy enforcement
266    /// routes through the sealed [`Tenant`](crate::Tenant) minted by a
267    /// [`TenantResolver`](crate::TenantResolver), and the
268    /// [`TenantGate`](crate::TenantGate) predicates compare against that.
269    pub fn tenant_id(&self) -> Option<crate::tenant::types::TenantId> {
270        self.get_metadata_string("org_id")
271            .or_else(|| self.get_metadata_string("tenant_id"))
272            .and_then(|s| crate::tenant::types::TenantId::try_new(s).ok())
273    }
274
275    /// Framework-only constructor: derive a callee `AuthContext` from a
276    /// caller context and a [`ForwardDerivation`].
277    ///
278    /// This is the **only** path that mints a callee context from a
279    /// caller's. It is `pub(crate)` to `plexus-auth-core` — no downstream
280    /// crate can reach it. A [`ForwardPolicy`] impl returns a
281    /// `ForwardDerivation` (parameters); the framework dispatch path
282    /// (AUTHLANG-3 wires this into `plexus_core::route_to_child`) is the
283    /// only caller of this constructor. Per AUTHZ-0 §"The sealed-type
284    /// pattern": the policy proposes; the framework disposes.
285    ///
286    /// The `_immediate_caller_stamp` parameter is reserved for the
287    /// principal-chain extension that AUTHLANG-3 lands (it will append the
288    /// stamp to the callee's invocation chain when `AuthContext` grows the
289    /// chain field — today's `AuthContext` does not carry one, so the
290    /// parameter is bound for forward compatibility and accepted but
291    /// otherwise ignored). Surfacing it now keeps the constructor's
292    /// signature stable across the AUTHZ-0 sealed-context migration.
293    ///
294    /// # Derivation semantics
295    ///
296    /// Each flag on the derivation maps to a logical field group on the
297    /// current `AuthContext`:
298    ///
299    /// - `keep_verified_user` — retains `user_id` and `session_id` (the
300    ///   identity of the originator). When `false`, both are reset to
301    ///   `AuthContext::anonymous`'s values (`"anonymous"` / empty).
302    /// - `keep_roles` — retains the role vector. When `false`, the
303    ///   callee's `roles` is empty.
304    /// - `keep_capabilities` — reserved for the AUTHZ-DATA / AUTHZ-CRED
305    ///   migration; today's `AuthContext` carries no capabilities field, so
306    ///   this flag is a no-op. Surfacing it keeps the v1 policy shape
307    ///   forward-compatible.
308    /// - `keep_metadata` — retains the metadata bag. When `false`, the
309    ///   callee's `metadata` is `Value::Null`.
310    ///
311    /// The constructor never grows the context: every field in the
312    /// returned `AuthContext` is either copied from `caller_ctx` or reset
313    /// to the corresponding empty value. There is no path through this
314    /// function that adds an unrelated role or fabricates a user_id.
315    ///
316    /// [`ForwardDerivation`]: crate::forward::ForwardDerivation
317    /// [`ForwardPolicy`]: crate::forward::ForwardPolicy
318    ///
319    pub(crate) fn derive_callee_context(
320        caller_ctx: &AuthContext,
321        derivation: &crate::forward::ForwardDerivation,
322        _immediate_caller_stamp: &crate::principal::Principal,
323    ) -> AuthContext {
324        let (user_id, session_id) = if derivation.keep_verified_user {
325            (caller_ctx.user_id.clone(), caller_ctx.session_id.clone())
326        } else {
327            ("anonymous".to_string(), String::new())
328        };
329        let roles = if derivation.keep_roles {
330            caller_ctx.roles.clone()
331        } else {
332            Vec::new()
333        };
334        // `keep_capabilities` is a no-op today: the current AuthContext has no
335        // capabilities field. The flag is preserved on `ForwardDerivation` for
336        // forward compatibility with the AUTHZ-DATA / AUTHZ-CRED migration.
337        let mut metadata = if derivation.keep_metadata {
338            caller_ctx.metadata.clone()
339        } else {
340            Value::Null
341        };
342        // The principal stamp lives in `metadata` (see `AuthContext::principal`),
343        // so dropping the verified user has to drop the stamp too. Without
344        // this, `keep_verified_user: false` + `keep_metadata: true` would reset
345        // `user_id` to "anonymous" while `principal()` kept answering with the
346        // caller's identity — the derivation would leak exactly the thing it
347        // was asked to strip.
348        if !derivation.keep_verified_user {
349            if let Value::Object(ref mut map) = metadata {
350                map.remove(PRINCIPAL_CLAIM);
351            }
352        } else if !derivation.keep_metadata {
353            // RETURNS-47: keeping the verified user keeps its whole identity.
354            // The principal stamp is identity, not metadata: without it a
355            // `key:` or `nostr:` caller (no idp UUID in `user_id`) is named by
356            // no one in the callee.
357            if let Some(stamp) = caller_ctx.metadata.get(PRINCIPAL_CLAIM) {
358                let mut map = serde_json::Map::new();
359                map.insert(PRINCIPAL_CLAIM.to_string(), stamp.clone());
360                metadata = Value::Object(map);
361            }
362        }
363        AuthContext {
364            user_id,
365            session_id,
366            roles,
367            metadata,
368        }
369    }
370
371    /// Scoped-callback API for deriving a callee context.
372    ///
373    /// The framework's dispatch path (plexus-core `route_to_child`) calls
374    /// this with a `ForwardDerivation` and a caller-principal stamp; the
375    /// closure receives the derived callee `AuthContext` by value and
376    /// returns whatever the dispatch yields (typically a `Future`).
377    /// Passing by value rather than reference is intentional: it allows
378    /// the closure to move the callee into an async block so dispatch can
379    /// await the child call while the callee lives inside the future's
380    /// state machine.
381    ///
382    /// This is the public entry point for AUTHLANG-3. The underlying
383    /// constructor [`derive_callee_context`] remains `pub(crate)` so the
384    /// raw "mint a callee from a caller" symbol is not callable from
385    /// outside `plexus-auth-core`. Anyone can still call `AuthContext::new`
386    /// and craft their own context from scratch — what they cannot do is
387    /// obtain one through the framework-blessed derivation path except
388    /// inside this callback, where the lifetime is scoped to the dispatch
389    /// invocation.
390    ///
391    /// Per AUTHZ-0 §"The sealed-type pattern": the policy proposes (via
392    /// `ForwardDerivation`); the framework disposes (via this callback).
393    pub fn with_callee_context<F, R>(
394        &self,
395        derivation: &crate::forward::ForwardDerivation,
396        immediate_caller_stamp: &crate::principal::Principal,
397        f: F,
398    ) -> R
399    where
400        F: FnOnce(AuthContext) -> R,
401    {
402        f(Self::derive_callee_context(self, derivation, immediate_caller_stamp))
403    }
404}
405
406/// Backends implement this trait to validate cookies/tokens during WS upgrade.
407///
408/// This trait is designed to be object-safe and work with async/await, allowing
409/// backends to use any authentication mechanism:
410/// - JWT validation (e.g., Keycloak tokens)
411/// - Database session lookups
412/// - Redis session stores
413/// - OAuth token introspection
414///
415/// # Example: Keycloak JWT Validation
416///
417/// ```rust,ignore
418/// use plexus_auth_core::{AuthContext, SessionValidator};
419/// use async_trait::async_trait;
420///
421/// struct KeycloakValidator {
422///     jwks_client: JwksClient,
423///     realm: String,
424/// }
425///
426/// #[async_trait]
427/// impl SessionValidator for KeycloakValidator {
428///     async fn validate(&self, cookie_value: &str) -> Option<AuthContext> {
429///         // Parse JWT from cookie
430///         let token = parse_jwt_from_cookie(cookie_value)?;
431///
432///         // Validate signature and claims
433///         let claims = self.jwks_client.verify(&token).await.ok()?;
434///
435///         // Extract user info and tenant from JWT claims
436///         Some(AuthContext::new(
437///             claims.sub,
438///             claims.sid.unwrap_or_default(),
439///             claims.realm_access.roles,
440///             serde_json::json!({
441///                 "realm": self.realm,
442///                 "tenant_id": claims.get("tenant_id"),
443///                 "email": claims.email,
444///             }),
445///         ))
446///     }
447/// }
448/// ```
449/// AUTH-11: the metadata key a session stamps its end under (unix seconds).
450pub const EXPIRES_AT_KEY: &str = "expires_at";
451
452#[async_trait]
453pub trait SessionValidator: Send + Sync + 'static {
454    /// Validate a cookie header value and return an AuthContext if valid.
455    ///
456    /// # Arguments
457    ///
458    /// * `cookie_value` - The raw Cookie header value (e.g., "session=abc123; path=/")
459    ///
460    /// # Returns
461    ///
462    /// - `Some(AuthContext)` if the cookie is valid and represents an authenticated session
463    /// - `None` if the cookie is invalid, expired, or represents an anonymous session
464    ///
465    /// # Implementation Notes
466    ///
467    /// - This is called during the WebSocket handshake (HTTP upgrade)
468    /// - Validation should be fast to avoid blocking the connection
469    /// - For JWT: verify signature, check expiration, extract claims
470    /// - For session-based auth: lookup session in DB/Redis
471    /// - Return None for invalid/expired credentials (connection proceeds as anonymous)
472    async fn validate(&self, cookie_value: &str) -> Option<AuthContext>;
473
474    /// AUTH-11: whether an identity this validator produced still stands —
475    /// asked while the connection it opened stays open, so a signed-out or
476    /// expired session's socket is closed rather than left to its next
477    /// call. `Err`: why not, in words for the caller.
478    ///
479    /// Default: not past its [`EXPIRES_AT_KEY`] stamp. A validator whose
480    /// sessions can end early (sign-out, revocation) must answer that here.
481    /// Memory only: it is asked often.
482    fn alive(&self, ctx: &AuthContext) -> Result<(), String> {
483        if ctx.expired() {
484            return Err("your sign-in has expired: sign in again".into());
485        }
486        Ok(())
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493
494    /// PERF.115-49: the remembered parse answers exactly what parsing
495    /// answers — for the stamp it was taken of, for another stamp, for a
496    /// corrupt one after a good one, and after a context's stamp is
497    /// rewritten in place.
498    #[test]
499    fn the_remembered_principal_is_always_the_stamps_own() {
500        let ada = format!("key:{}", "a".repeat(64));
501        let bob = format!("key:{}", "b".repeat(64));
502        let stamped = |p: &str| AuthContext::new("u".into(), "s".into(), vec![], serde_json::json!({ PRINCIPAL_CLAIM: p }));
503        let fresh = |ctx: &AuthContext| ctx.metadata[PRINCIPAL_CLAIM].as_str().and_then(|s| s.parse::<crate::identity::Principal>().ok());
504        let (a, b) = (stamped(&ada), stamped(&bob));
505        for _ in 0..3 {
506            assert_eq!(a.principal(), fresh(&a));
507            assert_eq!(b.principal(), fresh(&b));
508            assert_eq!(a.principal().unwrap().to_string(), ada);
509        }
510        // A corrupt stamp right after a good one is still `None`.
511        assert_eq!(a.principal().unwrap().to_string(), ada);
512        assert_eq!(stamped(&format!("key:{}", "A".repeat(64))).principal(), None);
513        assert_eq!(stamped(&format!("{ada}x")).principal(), None);
514        // The pub fields rewritten in place: the next answer is the new stamp's.
515        let mut c = stamped(&ada);
516        assert_eq!(c.principal().unwrap().to_string(), ada);
517        c.metadata[PRINCIPAL_CLAIM] = serde_json::Value::String(bob.clone());
518        assert_eq!(c.principal().unwrap().to_string(), bob);
519        c.metadata = serde_json::Value::Null;
520        assert_eq!(c.principal(), None);
521    }
522
523    #[test]
524    fn test_auth_context_creation() {
525        let ctx = AuthContext::new(
526            "user-123".to_string(),
527            "sess-456".to_string(),
528            vec!["admin".to_string()],
529            serde_json::json!({"tenant_id": "acme"}),
530        );
531
532        assert_eq!(ctx.user_id, "user-123");
533        assert_eq!(ctx.session_id, "sess-456");
534        assert!(ctx.has_role("admin"));
535        assert!(!ctx.has_role("user"));
536        assert_eq!(ctx.tenant(), Some("acme".to_string()));
537        assert!(ctx.is_authenticated());
538    }
539
540    #[test]
541    fn test_auth_context_clone() {
542        let ctx = AuthContext::new(
543            "alice".to_string(),
544            "sess-1".to_string(),
545            vec!["admin".to_string()],
546            serde_json::json!({"org": "acme"}),
547        );
548
549        let cloned = ctx.clone();
550        assert_eq!(ctx.user_id, cloned.user_id);
551        assert_eq!(ctx.session_id, cloned.session_id);
552        assert_eq!(ctx.roles, cloned.roles);
553    }
554
555    #[test]
556    fn test_anonymous_context() {
557        let ctx = AuthContext::anonymous();
558        assert_eq!(ctx.user_id, "anonymous");
559        assert!(!ctx.is_authenticated());
560        assert!(ctx.roles.is_empty());
561    }
562
563    #[test]
564    fn test_role_checking() {
565        let ctx = AuthContext::new(
566            "user-1".to_string(),
567            "sess-1".to_string(),
568            vec!["user".to_string(), "editor".to_string()],
569            Value::Null,
570        );
571
572        assert!(ctx.has_role("user"));
573        assert!(ctx.has_role("editor"));
574        assert!(!ctx.has_role("admin"));
575    }
576
577    #[test]
578    fn test_metadata_access() {
579        let ctx = AuthContext::new(
580            "user-1".to_string(),
581            "sess-1".to_string(),
582            vec![],
583            serde_json::json!({
584                "tenant_id": "org-123",
585                "realm": "production",
586                "email": "user@example.com"
587            }),
588        );
589
590        assert_eq!(
591            ctx.get_metadata_string("tenant_id"),
592            Some("org-123".to_string())
593        );
594        assert_eq!(
595            ctx.get_metadata_string("realm"),
596            Some("production".to_string())
597        );
598        assert_eq!(
599            ctx.get_metadata_string("email"),
600            Some("user@example.com".to_string())
601        );
602        assert_eq!(ctx.get_metadata_string("nonexistent"), None);
603    }
604
605
606    #[test]
607    fn derive_callee_context_identity_only_strips_roles_and_metadata() {
608        use crate::forward::ForwardDerivation;
609        use crate::principal::Principal;
610
611        let caller = AuthContext::new(
612            "alice".to_string(),
613            "sess-1".to_string(),
614            vec!["admin".to_string(), "editor".to_string()],
615            serde_json::json!({"tenant_id": "acme"}),
616        );
617        let stamp = Principal::anonymous_sealed();
618        let callee = AuthContext::derive_callee_context(
619            &caller,
620            &ForwardDerivation::IDENTITY_ONLY,
621            &stamp,
622        );
623        assert_eq!(callee.user_id, "alice");
624        assert_eq!(callee.session_id, "sess-1");
625        assert!(callee.roles.is_empty());
626        assert_eq!(callee.metadata, Value::Null);
627    }
628
629    #[test]
630    fn derive_callee_context_pass_through_retains_all_fields() {
631        use crate::forward::ForwardDerivation;
632        use crate::principal::Principal;
633
634        let caller = AuthContext::new(
635            "alice".to_string(),
636            "sess-1".to_string(),
637            vec!["admin".to_string()],
638            serde_json::json!({"tenant_id": "acme", "k": "v"}),
639        );
640        let stamp = Principal::anonymous_sealed();
641        let callee = AuthContext::derive_callee_context(
642            &caller,
643            &ForwardDerivation::PASS_THROUGH,
644            &stamp,
645        );
646        assert_eq!(callee.user_id, caller.user_id);
647        assert_eq!(callee.session_id, caller.session_id);
648        assert_eq!(callee.roles, caller.roles);
649        assert_eq!(callee.metadata, caller.metadata);
650    }
651
652    #[test]
653    fn derive_callee_context_anonymous_drops_everything() {
654        use crate::forward::ForwardDerivation;
655        use crate::principal::Principal;
656
657        let caller = AuthContext::new(
658            "alice".to_string(),
659            "sess-1".to_string(),
660            vec!["admin".to_string()],
661            serde_json::json!({"tenant_id": "acme"}),
662        );
663        let stamp = Principal::anonymous_sealed();
664        let callee = AuthContext::derive_callee_context(
665            &caller,
666            &ForwardDerivation::ANONYMOUS,
667            &stamp,
668        );
669        assert_eq!(callee.user_id, "anonymous");
670        assert_eq!(callee.session_id, "");
671        assert!(callee.roles.is_empty());
672        assert_eq!(callee.metadata, Value::Null);
673        assert!(!callee.is_authenticated());
674    }
675
676    #[test]
677    fn with_callee_context_invokes_closure_with_derived_callee() {
678        use crate::forward::ForwardDerivation;
679        use crate::principal::Principal;
680
681        let caller = AuthContext::new(
682            "alice".to_string(),
683            "sess-1".to_string(),
684            vec!["admin".to_string()],
685            serde_json::json!({"tenant_id": "org-1"}),
686        );
687        let stamp = Principal::anonymous_sealed();
688
689        let observed_user_id =
690            caller.with_callee_context(&ForwardDerivation::IDENTITY_ONLY, &stamp, |callee| {
691                assert!(callee.roles.is_empty());
692                assert_eq!(callee.metadata, Value::Null);
693                callee.user_id
694            });
695
696        assert_eq!(observed_user_id, "alice");
697    }
698
699    #[test]
700    fn with_callee_context_returns_closure_value() {
701        use crate::forward::ForwardDerivation;
702        use crate::principal::Principal;
703
704        let caller = AuthContext::anonymous();
705        let stamp = Principal::anonymous_sealed();
706        let answer =
707            caller.with_callee_context(&ForwardDerivation::PASS_THROUGH, &stamp, |_| 42_u32);
708        assert_eq!(answer, 42);
709    }
710
711    // RETURNS-47: identity-only keeps the caller's identity whole. The
712    // principal stamp lives in the metadata it otherwise drops, so a `key:`
713    // or `nostr:` caller (whose `user_id` is no idp UUID) lost its name in
714    // the child: `principal()` answered `None`.
715    #[test]
716    fn identity_only_keeps_the_callers_principal_stamp() {
717        use crate::forward::ForwardDerivation;
718        use crate::principal::Principal;
719
720        let subject: crate::identity::Principal =
721            "key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".parse().unwrap();
722        let caller = AuthContext::for_principal(&subject, "s1", vec!["viewer".into()], serde_json::json!({ "k": "v" }));
723        let callee = AuthContext::derive_callee_context(&caller, &ForwardDerivation::IDENTITY_ONLY, &Principal::anonymous_sealed());
724        assert_eq!(callee.principal(), Some(subject), "the identity, whole");
725        assert!(callee.roles.is_empty());
726        assert_eq!(callee.get_metadata_string("k"), None, "and nothing else of the metadata");
727        assert!(callee.is_authenticated());
728    }
729
730    #[test]
731    fn derive_callee_context_never_grows_context() {
732        // Sanity: the constructor cannot fabricate fields that did not
733        // exist on the caller. Starting from anonymous, even pass_through
734        // produces anonymous — the derivation can keep what the caller
735        // had, but never add what the caller lacked.
736        use crate::forward::ForwardDerivation;
737        use crate::principal::Principal;
738
739        let caller = AuthContext::anonymous();
740        let stamp = Principal::anonymous_sealed();
741        let callee = AuthContext::derive_callee_context(
742            &caller,
743            &ForwardDerivation::PASS_THROUGH,
744            &stamp,
745        );
746        assert_eq!(callee.user_id, "anonymous");
747        assert!(callee.roles.is_empty());
748        assert_eq!(callee.metadata, Value::Null);
749        assert!(!callee.is_authenticated());
750    }
751
752    // PLX-82: the principal stamp lives in `metadata`, so a derivation that
753    // drops the verified user must drop the stamp with it. Without the
754    // removal in `derive_callee_context`, PASS_THROUGH-with-anonymous-identity
755    // would reset `user_id` to "anonymous" while `principal()` kept answering
756    // with the caller — leaking exactly what was asked to be stripped.
757    #[test]
758    fn dropping_the_verified_user_also_drops_the_principal_stamp() {
759        use crate::forward::ForwardDerivation;
760        use crate::identity::Principal as Subject;
761        use crate::principal::Principal;
762
763        let subject: Subject = "idp:6ba7b810-9dad-11d1-80b4-00c04fd430c8".parse().unwrap();
764        let caller = AuthContext::for_principal(
765            &subject,
766            "sess-1",
767            vec!["admin".to_string()],
768            serde_json::json!({"org_id": "acme"}),
769        );
770        assert_eq!(caller.principal(), Some(subject.clone()));
771
772        let stamp = Principal::anonymous_sealed();
773
774        // Kept: identity survives, and both views agree.
775        let kept =
776            AuthContext::derive_callee_context(&caller, &ForwardDerivation::PASS_THROUGH, &stamp);
777        assert_eq!(kept.principal(), Some(subject));
778        assert_eq!(kept.user_id, "6ba7b810-9dad-11d1-80b4-00c04fd430c8");
779
780        // Dropped: `user_id` is anonymized AND the stamp is gone.
781        let dropped =
782            AuthContext::derive_callee_context(&caller, &ForwardDerivation::ANONYMOUS, &stamp);
783        assert_eq!(dropped.user_id, "anonymous");
784        assert_eq!(dropped.principal(), None);
785
786        // The dangerous combination specifically: metadata kept, identity not.
787        let mixed = ForwardDerivation {
788            keep_verified_user: false,
789            keep_roles: false,
790            keep_capabilities: false,
791            keep_metadata: true,
792        };
793        let mixed = AuthContext::derive_callee_context(&caller, &mixed, &stamp);
794        assert_eq!(mixed.user_id, "anonymous");
795        assert_eq!(
796            mixed.principal(),
797            None,
798            "keep_metadata must not smuggle the caller's principal through"
799        );
800        // Non-identity metadata is still retained.
801        assert_eq!(mixed.get_metadata_string("org_id").as_deref(), Some("acme"));
802    }
803
804    #[test]
805    fn for_principal_and_new_agree_on_an_idp_identity() {
806        use crate::identity::Principal as Subject;
807
808        let uuid = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
809        let subject: Subject = format!("idp:{uuid}").parse().unwrap();
810
811        let stamped = AuthContext::for_principal(&subject, "s", vec![], Value::Null);
812        let legacy = AuthContext::new(uuid.to_string(), "s".to_string(), vec![], Value::Null);
813
814        assert_eq!(stamped.user_id, legacy.user_id);
815        assert_eq!(stamped.principal(), legacy.principal());
816    }
817
818    #[test]
819    fn tenant_id_prefers_org_id_claim() {
820        // UT-1 / UT-S01 D3: `org_id` is the tenancy claim; `tenant_id` is
821        // the one-release deprecation alias.
822        let ctx = AuthContext::new(
823            "alice".to_string(),
824            "sess-1".to_string(),
825            vec![],
826            serde_json::json!({"org_id": "org_acme", "tenant_id": "legacy"}),
827        );
828        assert_eq!(
829            ctx.tenant_id().map(|t| t.as_str().to_string()),
830            Some("org_acme".to_string())
831        );
832    }
833
834    #[test]
835    fn tenant_id_falls_back_to_legacy_tenant_id_claim() {
836        let ctx = AuthContext::new(
837            "alice".to_string(),
838            "sess-1".to_string(),
839            vec![],
840            serde_json::json!({"tenant_id": "acme"}),
841        );
842        assert_eq!(
843            ctx.tenant_id().map(|t| t.as_str().to_string()),
844            Some("acme".to_string())
845        );
846    }
847
848    #[test]
849    fn tenant_id_is_none_when_absent_or_malformed() {
850        let absent = AuthContext::new(
851            "alice".to_string(),
852            "sess-1".to_string(),
853            vec![],
854            serde_json::json!({"realm": "prod"}),
855        );
856        assert!(absent.tenant_id().is_none());
857
858        // Malformed (control byte) must not surface as a usable TenantId.
859        let malformed = AuthContext::new(
860            "alice".to_string(),
861            "sess-1".to_string(),
862            vec![],
863            serde_json::json!({"org_id": "evil\u{0000}org"}),
864        );
865        assert!(malformed.tenant_id().is_none());
866    }
867
868    #[test]
869    fn test_tenant_from_metadata() {
870        // tenant_id takes precedence
871        let ctx1 = AuthContext::new(
872            "user-1".to_string(),
873            "sess-1".to_string(),
874            vec![],
875            serde_json::json!({"tenant_id": "org-123", "realm": "prod"}),
876        );
877        assert_eq!(ctx1.tenant(), Some("org-123".to_string()));
878
879        // Falls back to realm if no tenant_id
880        let ctx2 = AuthContext::new(
881            "user-1".to_string(),
882            "sess-1".to_string(),
883            vec![],
884            serde_json::json!({"realm": "prod"}),
885        );
886        assert_eq!(ctx2.tenant(), Some("prod".to_string()));
887
888        // None if neither present
889        let ctx3 = AuthContext::new(
890            "user-1".to_string(),
891            "sess-1".to_string(),
892            vec![],
893            Value::Null,
894        );
895        assert_eq!(ctx3.tenant(), None);
896    }
897}