pub struct AuthContext {
pub user_id: String,
pub session_id: String,
pub roles: Vec<String>,
pub metadata: Value,
}Expand description
Per-connection authentication context, populated during WS upgrade.
This context is extracted from HTTP cookies (or other auth mechanisms) during the WebSocket handshake and attached to the connection. Every RPC call on that connection has access to this context.
§Multi-tenancy with Keycloak
When using Keycloak for multi-tenancy, the AuthContext typically contains:
user_id: Keycloak user ID (sub claim from JWT)session_id: Keycloak session IDroles: User roles within the tenant/realmmetadata: Additional JWT claims (realm, tenant ID, custom attributes)
Fields§
§user_id: StringUser identifier (e.g., Keycloak sub claim, user UUID)
session_id: StringSession identifier (e.g., Keycloak session ID)
roles: Vec<String>User roles (e.g., [“user”, “admin”], Keycloak realm roles)
metadata: ValueAdditional metadata (e.g., JWT claims, tenant/realm info, custom attributes) For Keycloak multi-tenancy, this typically includes:
realm: Keycloak realm nametenant_id: Organization/tenant identifier- Any custom claims from the JWT token
Implementations§
Source§impl AuthContext
impl AuthContext
Sourcepub fn new(
user_id: String,
session_id: String,
roles: Vec<String>,
metadata: Value,
) -> Self
pub fn new( user_id: String, session_id: String, roles: Vec<String>, metadata: Value, ) -> Self
Create a new AuthContext.
§Note
This constructor is pub to preserve the existing public API across
the workspace. AUTHZ-0’s structural-defense vision calls for this
constructor to be pub(crate); tightening that seal lands in a
follow-up ticket because of the workspace-wide blast radius. See
plans/AUTHZ/AUTHZ-CORE-CRATE-1-RUN-NOTES.md.
Sourcepub fn anonymous() -> Self
pub fn anonymous() -> Self
Create an anonymous/unauthenticated context.
This can be used as a fallback when methods accept Option<&AuthContext>
and no authentication was provided.
Sourcepub fn for_principal(
principal: &Principal,
session_id: impl Into<String>,
roles: Vec<String>,
metadata: Value,
) -> Self
pub fn for_principal( principal: &Principal, session_id: impl Into<String>, roles: Vec<String>, metadata: Value, ) -> Self
Create a context for a verified Principal.
The namespaced constructor: user_id is derived from the principal
rather than supplied, so the two cannot be set to different things.
Prefer building this through
Authenticated::into_auth_context,
which additionally requires a proof that authentication happened.
Sourcepub fn principal(&self) -> Option<Principal>
pub fn principal(&self) -> Option<Principal>
The caller’s namespaced Principal.
§Why this is a method and not a field
PLX-82 requires this to be additive, and AuthContext has all-pub
fields that at least six sites across plexus-core, plexus-transport,
and plexus-macros construct with an exhaustive struct literal —
including plexus_core::plexus::test_validator, which is library code,
not a test. Adding a sixth field would fail to compile every one of
them, in crates this build is not permitted to modify. It would also
change the Deserialize and JsonSchema shape of a type that crosses
the wire.
Deriving the principal instead costs nothing and buys something the
field could not: principal and user_id cannot disagree, because
there is nowhere for them to disagree. There is one storage location
for an idp identity, and both accessors read it.
§Resolution order
metadata["principal"], if present and parseable — this is whatAuthenticated::into_auth_contextstamps, and it is the only route by which a non-idp principal (anostr:pubkey, anapikey:id) can be carried.- Otherwise
idp:<user_id>, whenuser_idis a canonical UUID — the migration path for every context built before this build, and for anySessionValidatornot yet ported to anAuthenticator.
Returns None for anonymous contexts and for any user_id that is
not a plexus-idp UUID. None means “no principal can be named here”,
never “authenticated as someone else”.
§This is a claim, not an authorization
Same caveat as AuthContext::tenant_id: holding a Principal says
who the context names, not what it may do. The proof that
authentication occurred is
Authenticated, which only an
Authenticator produces.
Sourcepub fn is_authenticated(&self) -> bool
pub fn is_authenticated(&self) -> bool
Check if this context represents an authenticated user.
Sourcepub fn expired(&self) -> bool
pub fn expired(&self) -> bool
AUTH-11: whether the sign-in this context carries has passed its
EXPIRES_AT_KEY stamp (unix seconds). A context with no stamp
never expires by this test; its validator may still end it
(SessionValidator::alive).
Sourcepub fn get_metadata_string(&self, key: &str) -> Option<String>
pub fn get_metadata_string(&self, key: &str) -> Option<String>
Get a metadata field as a string.
Sourcepub fn tenant(&self) -> Option<String>
pub fn tenant(&self) -> Option<String>
Get the tenant/realm from metadata (Keycloak multi-tenancy).
Pre-UT-1 helper retained for compatibility. New code should prefer
AuthContext::tenant_id, which returns the typed
TenantId and reads the
org_id claim first (UT-S01 D3).
Sourcepub fn tenant_id(&self) -> Option<TenantId>
pub fn tenant_id(&self) -> Option<TenantId>
The caller’s tenant identity as a typed
TenantId, if present.
Reads metadata["org_id"] first (the tenancy claim pinned by
UT-S01 D3 — Auth0 Organizations convention), falling back to the
legacy metadata["tenant_id"] key for one deprecation window
(validators write the value under both keys during that window).
Returns None when neither key is present or when the value
fails TenantId validation (empty / overlong / non-printable) —
a malformed tenant claim must not flow into comparisons as if it
named a real tenant.
Note this is the claim, not authorization: tenancy enforcement
routes through the sealed Tenant minted by a
TenantResolver, and the
TenantGate predicates compare against that.
Sourcepub fn with_callee_context<F, R>(
&self,
derivation: &ForwardDerivation,
immediate_caller_stamp: &Principal,
f: F,
) -> Rwhere
F: FnOnce(AuthContext) -> R,
pub fn with_callee_context<F, R>(
&self,
derivation: &ForwardDerivation,
immediate_caller_stamp: &Principal,
f: F,
) -> Rwhere
F: FnOnce(AuthContext) -> R,
Scoped-callback API for deriving a callee context.
The framework’s dispatch path (plexus-core route_to_child) calls
this with a ForwardDerivation and a caller-principal stamp; the
closure receives the derived callee AuthContext by value and
returns whatever the dispatch yields (typically a Future).
Passing by value rather than reference is intentional: it allows
the closure to move the callee into an async block so dispatch can
await the child call while the callee lives inside the future’s
state machine.
This is the public entry point for AUTHLANG-3. The underlying
constructor [derive_callee_context] remains pub(crate) so the
raw “mint a callee from a caller” symbol is not callable from
outside plexus-auth-core. Anyone can still call AuthContext::new
and craft their own context from scratch — what they cannot do is
obtain one through the framework-blessed derivation path except
inside this callback, where the lifetime is scoped to the dispatch
invocation.
Per AUTHZ-0 §“The sealed-type pattern”: the policy proposes (via
ForwardDerivation); the framework disposes (via this callback).
Trait Implementations§
Source§impl Clone for AuthContext
impl Clone for AuthContext
Source§impl Debug for AuthContext
impl Debug for AuthContext
Source§impl<'de> Deserialize<'de> for AuthContext
impl<'de> Deserialize<'de> for AuthContext
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl JsonSchema for AuthContext
impl JsonSchema for AuthContext
Source§fn schema_id() -> Cow<'static, str>
fn schema_id() -> Cow<'static, str>
Source§fn json_schema(generator: &mut SchemaGenerator) -> Schema
fn json_schema(generator: &mut SchemaGenerator) -> Schema
Source§fn inline_schema() -> bool
fn inline_schema() -> bool
$ref keyword. Read more