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