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 } else if !derivation.keep_metadata {
325 // RETURNS-47: keeping the verified user keeps its whole identity.
326 // The principal stamp is identity, not metadata: without it a
327 // `key:` or `nostr:` caller (no idp UUID in `user_id`) is named by
328 // no one in the callee.
329 if let Some(stamp) = caller_ctx.metadata.get(PRINCIPAL_CLAIM) {
330 let mut map = serde_json::Map::new();
331 map.insert(PRINCIPAL_CLAIM.to_string(), stamp.clone());
332 metadata = Value::Object(map);
333 }
334 }
335 AuthContext {
336 user_id,
337 session_id,
338 roles,
339 metadata,
340 }
341 }
342
343 /// Scoped-callback API for deriving a callee context.
344 ///
345 /// The framework's dispatch path (plexus-core `route_to_child`) calls
346 /// this with a `ForwardDerivation` and a caller-principal stamp; the
347 /// closure receives the derived callee `AuthContext` by value and
348 /// returns whatever the dispatch yields (typically a `Future`).
349 /// Passing by value rather than reference is intentional: it allows
350 /// the closure to move the callee into an async block so dispatch can
351 /// await the child call while the callee lives inside the future's
352 /// state machine.
353 ///
354 /// This is the public entry point for AUTHLANG-3. The underlying
355 /// constructor [`derive_callee_context`] remains `pub(crate)` so the
356 /// raw "mint a callee from a caller" symbol is not callable from
357 /// outside `plexus-auth-core`. Anyone can still call `AuthContext::new`
358 /// and craft their own context from scratch — what they cannot do is
359 /// obtain one through the framework-blessed derivation path except
360 /// inside this callback, where the lifetime is scoped to the dispatch
361 /// invocation.
362 ///
363 /// Per AUTHZ-0 §"The sealed-type pattern": the policy proposes (via
364 /// `ForwardDerivation`); the framework disposes (via this callback).
365 pub fn with_callee_context<F, R>(
366 &self,
367 derivation: &crate::forward::ForwardDerivation,
368 immediate_caller_stamp: &crate::principal::Principal,
369 f: F,
370 ) -> R
371 where
372 F: FnOnce(AuthContext) -> R,
373 {
374 f(Self::derive_callee_context(self, derivation, immediate_caller_stamp))
375 }
376}
377
378/// Backends implement this trait to validate cookies/tokens during WS upgrade.
379///
380/// This trait is designed to be object-safe and work with async/await, allowing
381/// backends to use any authentication mechanism:
382/// - JWT validation (e.g., Keycloak tokens)
383/// - Database session lookups
384/// - Redis session stores
385/// - OAuth token introspection
386///
387/// # Example: Keycloak JWT Validation
388///
389/// ```rust,ignore
390/// use plexus_auth_core::{AuthContext, SessionValidator};
391/// use async_trait::async_trait;
392///
393/// struct KeycloakValidator {
394/// jwks_client: JwksClient,
395/// realm: String,
396/// }
397///
398/// #[async_trait]
399/// impl SessionValidator for KeycloakValidator {
400/// async fn validate(&self, cookie_value: &str) -> Option<AuthContext> {
401/// // Parse JWT from cookie
402/// let token = parse_jwt_from_cookie(cookie_value)?;
403///
404/// // Validate signature and claims
405/// let claims = self.jwks_client.verify(&token).await.ok()?;
406///
407/// // Extract user info and tenant from JWT claims
408/// Some(AuthContext::new(
409/// claims.sub,
410/// claims.sid.unwrap_or_default(),
411/// claims.realm_access.roles,
412/// serde_json::json!({
413/// "realm": self.realm,
414/// "tenant_id": claims.get("tenant_id"),
415/// "email": claims.email,
416/// }),
417/// ))
418/// }
419/// }
420/// ```
421/// AUTH-11: the metadata key a session stamps its end under (unix seconds).
422pub const EXPIRES_AT_KEY: &str = "expires_at";
423
424#[async_trait]
425pub trait SessionValidator: Send + Sync + 'static {
426 /// Validate a cookie header value and return an AuthContext if valid.
427 ///
428 /// # Arguments
429 ///
430 /// * `cookie_value` - The raw Cookie header value (e.g., "session=abc123; path=/")
431 ///
432 /// # Returns
433 ///
434 /// - `Some(AuthContext)` if the cookie is valid and represents an authenticated session
435 /// - `None` if the cookie is invalid, expired, or represents an anonymous session
436 ///
437 /// # Implementation Notes
438 ///
439 /// - This is called during the WebSocket handshake (HTTP upgrade)
440 /// - Validation should be fast to avoid blocking the connection
441 /// - For JWT: verify signature, check expiration, extract claims
442 /// - For session-based auth: lookup session in DB/Redis
443 /// - Return None for invalid/expired credentials (connection proceeds as anonymous)
444 async fn validate(&self, cookie_value: &str) -> Option<AuthContext>;
445
446 /// AUTH-11: whether an identity this validator produced still stands —
447 /// asked while the connection it opened stays open, so a signed-out or
448 /// expired session's socket is closed rather than left to its next
449 /// call. `Err`: why not, in words for the caller.
450 ///
451 /// Default: not past its [`EXPIRES_AT_KEY`] stamp. A validator whose
452 /// sessions can end early (sign-out, revocation) must answer that here.
453 /// Memory only: it is asked often.
454 fn alive(&self, ctx: &AuthContext) -> Result<(), String> {
455 if ctx.expired() {
456 return Err("your sign-in has expired: sign in again".into());
457 }
458 Ok(())
459 }
460}
461
462#[cfg(test)]
463mod tests {
464 use super::*;
465
466 #[test]
467 fn test_auth_context_creation() {
468 let ctx = AuthContext::new(
469 "user-123".to_string(),
470 "sess-456".to_string(),
471 vec!["admin".to_string()],
472 serde_json::json!({"tenant_id": "acme"}),
473 );
474
475 assert_eq!(ctx.user_id, "user-123");
476 assert_eq!(ctx.session_id, "sess-456");
477 assert!(ctx.has_role("admin"));
478 assert!(!ctx.has_role("user"));
479 assert_eq!(ctx.tenant(), Some("acme".to_string()));
480 assert!(ctx.is_authenticated());
481 }
482
483 #[test]
484 fn test_auth_context_clone() {
485 let ctx = AuthContext::new(
486 "alice".to_string(),
487 "sess-1".to_string(),
488 vec!["admin".to_string()],
489 serde_json::json!({"org": "acme"}),
490 );
491
492 let cloned = ctx.clone();
493 assert_eq!(ctx.user_id, cloned.user_id);
494 assert_eq!(ctx.session_id, cloned.session_id);
495 assert_eq!(ctx.roles, cloned.roles);
496 }
497
498 #[test]
499 fn test_anonymous_context() {
500 let ctx = AuthContext::anonymous();
501 assert_eq!(ctx.user_id, "anonymous");
502 assert!(!ctx.is_authenticated());
503 assert!(ctx.roles.is_empty());
504 }
505
506 #[test]
507 fn test_role_checking() {
508 let ctx = AuthContext::new(
509 "user-1".to_string(),
510 "sess-1".to_string(),
511 vec!["user".to_string(), "editor".to_string()],
512 Value::Null,
513 );
514
515 assert!(ctx.has_role("user"));
516 assert!(ctx.has_role("editor"));
517 assert!(!ctx.has_role("admin"));
518 }
519
520 #[test]
521 fn test_metadata_access() {
522 let ctx = AuthContext::new(
523 "user-1".to_string(),
524 "sess-1".to_string(),
525 vec![],
526 serde_json::json!({
527 "tenant_id": "org-123",
528 "realm": "production",
529 "email": "user@example.com"
530 }),
531 );
532
533 assert_eq!(
534 ctx.get_metadata_string("tenant_id"),
535 Some("org-123".to_string())
536 );
537 assert_eq!(
538 ctx.get_metadata_string("realm"),
539 Some("production".to_string())
540 );
541 assert_eq!(
542 ctx.get_metadata_string("email"),
543 Some("user@example.com".to_string())
544 );
545 assert_eq!(ctx.get_metadata_string("nonexistent"), None);
546 }
547
548
549 #[test]
550 fn derive_callee_context_identity_only_strips_roles_and_metadata() {
551 use crate::forward::ForwardDerivation;
552 use crate::principal::Principal;
553
554 let caller = AuthContext::new(
555 "alice".to_string(),
556 "sess-1".to_string(),
557 vec!["admin".to_string(), "editor".to_string()],
558 serde_json::json!({"tenant_id": "acme"}),
559 );
560 let stamp = Principal::anonymous_sealed();
561 let callee = AuthContext::derive_callee_context(
562 &caller,
563 &ForwardDerivation::IDENTITY_ONLY,
564 &stamp,
565 );
566 assert_eq!(callee.user_id, "alice");
567 assert_eq!(callee.session_id, "sess-1");
568 assert!(callee.roles.is_empty());
569 assert_eq!(callee.metadata, Value::Null);
570 }
571
572 #[test]
573 fn derive_callee_context_pass_through_retains_all_fields() {
574 use crate::forward::ForwardDerivation;
575 use crate::principal::Principal;
576
577 let caller = AuthContext::new(
578 "alice".to_string(),
579 "sess-1".to_string(),
580 vec!["admin".to_string()],
581 serde_json::json!({"tenant_id": "acme", "k": "v"}),
582 );
583 let stamp = Principal::anonymous_sealed();
584 let callee = AuthContext::derive_callee_context(
585 &caller,
586 &ForwardDerivation::PASS_THROUGH,
587 &stamp,
588 );
589 assert_eq!(callee.user_id, caller.user_id);
590 assert_eq!(callee.session_id, caller.session_id);
591 assert_eq!(callee.roles, caller.roles);
592 assert_eq!(callee.metadata, caller.metadata);
593 }
594
595 #[test]
596 fn derive_callee_context_anonymous_drops_everything() {
597 use crate::forward::ForwardDerivation;
598 use crate::principal::Principal;
599
600 let caller = AuthContext::new(
601 "alice".to_string(),
602 "sess-1".to_string(),
603 vec!["admin".to_string()],
604 serde_json::json!({"tenant_id": "acme"}),
605 );
606 let stamp = Principal::anonymous_sealed();
607 let callee = AuthContext::derive_callee_context(
608 &caller,
609 &ForwardDerivation::ANONYMOUS,
610 &stamp,
611 );
612 assert_eq!(callee.user_id, "anonymous");
613 assert_eq!(callee.session_id, "");
614 assert!(callee.roles.is_empty());
615 assert_eq!(callee.metadata, Value::Null);
616 assert!(!callee.is_authenticated());
617 }
618
619 #[test]
620 fn with_callee_context_invokes_closure_with_derived_callee() {
621 use crate::forward::ForwardDerivation;
622 use crate::principal::Principal;
623
624 let caller = AuthContext::new(
625 "alice".to_string(),
626 "sess-1".to_string(),
627 vec!["admin".to_string()],
628 serde_json::json!({"tenant_id": "org-1"}),
629 );
630 let stamp = Principal::anonymous_sealed();
631
632 let observed_user_id =
633 caller.with_callee_context(&ForwardDerivation::IDENTITY_ONLY, &stamp, |callee| {
634 assert!(callee.roles.is_empty());
635 assert_eq!(callee.metadata, Value::Null);
636 callee.user_id
637 });
638
639 assert_eq!(observed_user_id, "alice");
640 }
641
642 #[test]
643 fn with_callee_context_returns_closure_value() {
644 use crate::forward::ForwardDerivation;
645 use crate::principal::Principal;
646
647 let caller = AuthContext::anonymous();
648 let stamp = Principal::anonymous_sealed();
649 let answer =
650 caller.with_callee_context(&ForwardDerivation::PASS_THROUGH, &stamp, |_| 42_u32);
651 assert_eq!(answer, 42);
652 }
653
654 // RETURNS-47: identity-only keeps the caller's identity whole. The
655 // principal stamp lives in the metadata it otherwise drops, so a `key:`
656 // or `nostr:` caller (whose `user_id` is no idp UUID) lost its name in
657 // the child: `principal()` answered `None`.
658 #[test]
659 fn identity_only_keeps_the_callers_principal_stamp() {
660 use crate::forward::ForwardDerivation;
661 use crate::principal::Principal;
662
663 let subject: crate::identity::Principal =
664 "key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".parse().unwrap();
665 let caller = AuthContext::for_principal(&subject, "s1", vec!["viewer".into()], serde_json::json!({ "k": "v" }));
666 let callee = AuthContext::derive_callee_context(&caller, &ForwardDerivation::IDENTITY_ONLY, &Principal::anonymous_sealed());
667 assert_eq!(callee.principal(), Some(subject), "the identity, whole");
668 assert!(callee.roles.is_empty());
669 assert_eq!(callee.get_metadata_string("k"), None, "and nothing else of the metadata");
670 assert!(callee.is_authenticated());
671 }
672
673 #[test]
674 fn derive_callee_context_never_grows_context() {
675 // Sanity: the constructor cannot fabricate fields that did not
676 // exist on the caller. Starting from anonymous, even pass_through
677 // produces anonymous — the derivation can keep what the caller
678 // had, but never add what the caller lacked.
679 use crate::forward::ForwardDerivation;
680 use crate::principal::Principal;
681
682 let caller = AuthContext::anonymous();
683 let stamp = Principal::anonymous_sealed();
684 let callee = AuthContext::derive_callee_context(
685 &caller,
686 &ForwardDerivation::PASS_THROUGH,
687 &stamp,
688 );
689 assert_eq!(callee.user_id, "anonymous");
690 assert!(callee.roles.is_empty());
691 assert_eq!(callee.metadata, Value::Null);
692 assert!(!callee.is_authenticated());
693 }
694
695 // PLX-82: the principal stamp lives in `metadata`, so a derivation that
696 // drops the verified user must drop the stamp with it. Without the
697 // removal in `derive_callee_context`, PASS_THROUGH-with-anonymous-identity
698 // would reset `user_id` to "anonymous" while `principal()` kept answering
699 // with the caller — leaking exactly what was asked to be stripped.
700 #[test]
701 fn dropping_the_verified_user_also_drops_the_principal_stamp() {
702 use crate::forward::ForwardDerivation;
703 use crate::identity::Principal as Subject;
704 use crate::principal::Principal;
705
706 let subject: Subject = "idp:6ba7b810-9dad-11d1-80b4-00c04fd430c8".parse().unwrap();
707 let caller = AuthContext::for_principal(
708 &subject,
709 "sess-1",
710 vec!["admin".to_string()],
711 serde_json::json!({"org_id": "acme"}),
712 );
713 assert_eq!(caller.principal(), Some(subject.clone()));
714
715 let stamp = Principal::anonymous_sealed();
716
717 // Kept: identity survives, and both views agree.
718 let kept =
719 AuthContext::derive_callee_context(&caller, &ForwardDerivation::PASS_THROUGH, &stamp);
720 assert_eq!(kept.principal(), Some(subject));
721 assert_eq!(kept.user_id, "6ba7b810-9dad-11d1-80b4-00c04fd430c8");
722
723 // Dropped: `user_id` is anonymized AND the stamp is gone.
724 let dropped =
725 AuthContext::derive_callee_context(&caller, &ForwardDerivation::ANONYMOUS, &stamp);
726 assert_eq!(dropped.user_id, "anonymous");
727 assert_eq!(dropped.principal(), None);
728
729 // The dangerous combination specifically: metadata kept, identity not.
730 let mixed = ForwardDerivation {
731 keep_verified_user: false,
732 keep_roles: false,
733 keep_capabilities: false,
734 keep_metadata: true,
735 };
736 let mixed = AuthContext::derive_callee_context(&caller, &mixed, &stamp);
737 assert_eq!(mixed.user_id, "anonymous");
738 assert_eq!(
739 mixed.principal(),
740 None,
741 "keep_metadata must not smuggle the caller's principal through"
742 );
743 // Non-identity metadata is still retained.
744 assert_eq!(mixed.get_metadata_string("org_id").as_deref(), Some("acme"));
745 }
746
747 #[test]
748 fn for_principal_and_new_agree_on_an_idp_identity() {
749 use crate::identity::Principal as Subject;
750
751 let uuid = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
752 let subject: Subject = format!("idp:{uuid}").parse().unwrap();
753
754 let stamped = AuthContext::for_principal(&subject, "s", vec![], Value::Null);
755 let legacy = AuthContext::new(uuid.to_string(), "s".to_string(), vec![], Value::Null);
756
757 assert_eq!(stamped.user_id, legacy.user_id);
758 assert_eq!(stamped.principal(), legacy.principal());
759 }
760
761 #[test]
762 fn tenant_id_prefers_org_id_claim() {
763 // UT-1 / UT-S01 D3: `org_id` is the tenancy claim; `tenant_id` is
764 // the one-release deprecation alias.
765 let ctx = AuthContext::new(
766 "alice".to_string(),
767 "sess-1".to_string(),
768 vec![],
769 serde_json::json!({"org_id": "org_acme", "tenant_id": "legacy"}),
770 );
771 assert_eq!(
772 ctx.tenant_id().map(|t| t.as_str().to_string()),
773 Some("org_acme".to_string())
774 );
775 }
776
777 #[test]
778 fn tenant_id_falls_back_to_legacy_tenant_id_claim() {
779 let ctx = AuthContext::new(
780 "alice".to_string(),
781 "sess-1".to_string(),
782 vec![],
783 serde_json::json!({"tenant_id": "acme"}),
784 );
785 assert_eq!(
786 ctx.tenant_id().map(|t| t.as_str().to_string()),
787 Some("acme".to_string())
788 );
789 }
790
791 #[test]
792 fn tenant_id_is_none_when_absent_or_malformed() {
793 let absent = AuthContext::new(
794 "alice".to_string(),
795 "sess-1".to_string(),
796 vec![],
797 serde_json::json!({"realm": "prod"}),
798 );
799 assert!(absent.tenant_id().is_none());
800
801 // Malformed (control byte) must not surface as a usable TenantId.
802 let malformed = AuthContext::new(
803 "alice".to_string(),
804 "sess-1".to_string(),
805 vec![],
806 serde_json::json!({"org_id": "evil\u{0000}org"}),
807 );
808 assert!(malformed.tenant_id().is_none());
809 }
810
811 #[test]
812 fn test_tenant_from_metadata() {
813 // tenant_id takes precedence
814 let ctx1 = AuthContext::new(
815 "user-1".to_string(),
816 "sess-1".to_string(),
817 vec![],
818 serde_json::json!({"tenant_id": "org-123", "realm": "prod"}),
819 );
820 assert_eq!(ctx1.tenant(), Some("org-123".to_string()));
821
822 // Falls back to realm if no tenant_id
823 let ctx2 = AuthContext::new(
824 "user-1".to_string(),
825 "sess-1".to_string(),
826 vec![],
827 serde_json::json!({"realm": "prod"}),
828 );
829 assert_eq!(ctx2.tenant(), Some("prod".to_string()));
830
831 // None if neither present
832 let ctx3 = AuthContext::new(
833 "user-1".to_string(),
834 "sess-1".to_string(),
835 vec![],
836 Value::Null,
837 );
838 assert_eq!(ctx3.tenant(), None);
839 }
840}