Skip to main content

plexus_auth_core/
lib.rs

1//! Sealed-type primitives for the Plexus auth framework.
2//!
3//! This crate exists to host the Plexus authentication primitives —
4//! `AuthContext`, `VerifiedUser`, `Principal`, and the forthcoming
5//! `Credential<T>`, `Tenanted<S>`, `ForwardDerivation` — behind a crate
6//! boundary that no consuming crate can bypass. The crate boundary, plus
7//! Rust's orphan rules, plus crate-private constructors, escalate the
8//! sealed-type defense from procedural (visibility within plexus-core) to
9//! structural (visibility across crates).
10//!
11//! See `plans/AUTHZ/AUTHZ-0.md` §"Crate-level isolation amplifies the seal"
12//! for the full rationale.
13//!
14//! # Public surface
15//!
16//! - [`AuthContext`] — the runtime auth value carried with every method
17//!   invocation. The shape and current public API are preserved verbatim
18//!   from `plexus-core`'s `plexus::auth` module to keep this migration
19//!   mechanical; tightening the seal on `AuthContext::new` and field
20//!   visibility is tracked as follow-up work (see
21//!   `plans/AUTHZ/AUTHZ-CORE-CRATE-1-RUN-NOTES.md`).
22//! - [`SessionValidator`] — the trait perimeter validators implement.
23//! - [`VerifiedUser`] — sealed proof that an IdP-signed token was verified.
24//! - [`Principal`] — sealed authenticated-actor identity (user, service, anon).
25//! - [`BackendAuthCapabilities`] — capability-advertisement payload served
26//!   at `_info` so generic clients can discover supported auth mechanisms
27//!   (AUTHZ-CORE-3). Composed of [`AuthMechanism`] variants
28//!   (`Bearer`, `Cookie`, `Oidc`, `Anonymous`) and the strong-typed
29//!   primitives [`MethodPath`], [`IssuerUrl`], [`ClientId`],
30//!   [`CookieName`], [`HeaderName`].
31//! - [`Tenant`] — sealed unit of data isolation (AUTHZ-0 layer 4). The
32//!   constructor is crate-private; the only path to a `Tenant` value is
33//!   through the framework's [`TenantResolver`].
34//! - [`TenantResolver`] — derives a `Tenant` from a verified
35//!   `AuthContext`. Reference impls: [`ClaimTenantResolver`] (the 80%
36//!   case; default claim key `org_id` per UT-S01 D3) and
37//!   [`SingleTenantResolver`] (explicit single-tenant opt-out).
38//! - [`TenantId`] — the public, validated identifier newtype for tenant
39//!   identity (UT-1): claim values and stored resource tags. Data, not
40//!   proof — see its docs for the distinction from [`Tenant`].
41//! - [`TenantGate`] — the generalized tenant-isolation predicate layer
42//!   extracted from plexus-trak's reference gate (UT-1): reads scoped
43//!   not-found, writes forbidden, anonymous writes unauthenticated.
44//!   Backends tag resources via [`TenantTagged`] and convert
45//!   [`GateDenial`] into their wire errors.
46//! - [`oidc`] — the OIDC validator (UT-1, UT-S01 D1): discovery → JWKS
47//!   (cached per AUTH-8) → local RS256 validation of
48//!   `iss`/`aud`/`exp`/`iat` → mints the sealed [`VerifiedUser`] with the
49//!   `org_id` tenant. [`OidcSessionValidator`] adapts it to the
50//!   [`SessionValidator`] perimeter.
51//! - [`Credential`] — sealed framework-level credential primitive. The only
52//!   path to a `Credential<T>` value is through [`CredentialMinter::mint`],
53//!   itself reachable only by accepting a framework-injected reference. The
54//!   custom `Serialize` impl emits a sentinel `{"$credential": "<id>"}` by
55//!   default; the dispatch layer routes the inner value to a sidecar via an
56//!   RAII guard while it builds the wire envelope (Tier B Q-WIRE-3).
57//! - [`CredentialMinter`] — the injected service that mints credentials.
58//! - [`CredentialMetadata`] — typed contract describing what the credential
59//!   is and how to attach it on subsequent calls (kind, attach site, scheme,
60//!   scopes, expiry, refresh/revoke hints, issuer, sensitivity).
61//! - [`AuditRecord`] — the audit primitive consumed by AUTHZ default-deny
62//!   dispatch (AUTHZ-CORE-5) and AUTHLANG-3's forwarding-policy path. Carries
63//!   the principal chain, decision, reason, latency, and correlation ID for
64//!   one scope check. [`AuditSink`] is the framework's persistence trait;
65//!   [`TracingAuditSink`] is the default impl emitting `tracing::info!`
66//!   events under `target = "plexus::audit"`.
67//! - [`grants`] (AUTH-2) — [`Grant`] (`<activation>.<method>`, inherent),
68//!   [`ScopeRef`], [`GrantSet`], [`Membership`], [`Ceiling`], the service
69//!   traits [`Memberships`] / [`Roles`] / [`Resolve`], and the [`Gate`] whose
70//!   [`Gate::check`] answers a call with a [`Reach`] or a [`Refusal`].
71//! - [`ScopeRegistry`] — hub-level roles→scopes source of truth (R-0,
72//!   reviving AUTHZ-CORE-4 + CORE-6). [`Role`]s are named scope-sets with
73//!   transitive, build-time-cycle-rejected inheritance; [`Scope`] gains the
74//!   grammar-validated `try_new` and segment-bounded wildcard
75//!   [`Scope::matches`]; [`RoleName`] gains `try_new`. The dispatch gate
76//!   (R-5) computes `effective_scopes(AuthContext.roles)` and checks
77//!   `Scope::matches(required)`.
78//!
79//! # Sealing protections (per AUTHZ-0)
80//!
81//! `VerifiedUser` and `Principal` are introduced here with the strict seal
82//! the AUTHZ-0 doc calls for:
83//!
84//! 1. **No fabrication.** Constructors are `pub(crate)` and callable only
85//!    from inside `plexus-auth-core`. The trybuild test
86//!    `tests/compile_fail/seal_*.rs` asserts this.
87//! 2. **No backdoor `From`/`Into`.** Orphan rules forbid implementing
88//!    foreign traits for foreign types from a third crate; only this crate
89//!    can add such impls.
90//! 3. **No accidental `Default`.** Explicitly NOT derived.
91//! 4. **No leaky `Deserialize`.** Not derived for these types; raw JSON
92//!    cannot fabricate a sealed value.
93//! 5. **No mutation.** Fields are private; no setters; even with a sealed
94//!    value in hand, no caller can mutate it.
95//!
96//! `AuthContext` retains its current public constructors (`new`,
97//! `anonymous`) and `pub` fields for now, to preserve the public API that
98//! callers across the workspace depend on. The crate boundary still gives
99//! `AuthContext` the orphan-rule protection (no foreign `From`/`Into` from
100//! third crates) and a single audit point for the type. Tightening the
101//! `AuthContext` seal to match `VerifiedUser`/`Principal` is the next step
102//! in the auth track and lands as a follow-up ticket.
103
104/// Crate version, populated at compile time from `CARGO_PKG_VERSION`.
105///
106/// Exposed so the `plexus-rpc` umbrella can stamp it into the
107/// `Capabilities` manifest backends embed in `_info`. See UMB-2.
108pub const VERSION: &str = env!("CARGO_PKG_VERSION");
109
110pub mod audit;
111pub mod auth;
112pub mod capabilities;
113pub mod credential;
114/// Namespaced identity and pluggable authentication (PLX-82).
115///
116/// Read [`identity`]'s module docs before using either `Principal`: this crate
117/// has two, they mean different things, and the module header is where that
118/// is written down.
119pub mod identity;
120pub mod oidc;
121pub mod principal;
122pub mod scope_registry;
123pub mod tenant;
124pub mod verified_user;
125
126/// IDENTITY-13: provider adapters, one per identity provider, each turning
127/// its credential into Plexus types at a service's boundary.
128#[cfg(feature = "adapters")]
129pub mod adapters;
130
131pub mod forward;
132
133/// AUTH-2: grants, roles, memberships, ceilings, and the gate.
134pub mod grants;
135
136pub use audit::{
137    AuditDecision, AuditDenyReason, AuditRecord, AuditRecordKind, AuditSink, ForwardPolicyApplied,
138    RoleName, ScopeCheck, SensitiveField, SessionId, TracingAuditSink, UserId,
139};
140pub use auth::{AuthContext, SessionValidator, PRINCIPAL_CLAIM};
141// NOTE: `identity::Principal` is deliberately NOT re-exported here. The crate
142// root's `Principal` is the sealed caller-stamp (`principal::Principal`), and
143// the subject-name type is reached only as `plexus_auth_core::identity::Principal`
144// — the same disambiguation-by-module-path that `plexus-core` uses. See the
145// `identity` module docs for the full resolution of the name collision.
146pub use capabilities::{
147    AuthMechanism, BackendAuthCapabilities, BackendAuthCapabilitiesError, ClientId, ClientIdError,
148    CookieName, CookieNameError, HeaderName, HeaderNameError, IssuerUrl, IssuerUrlError,
149    MethodPath, MethodPathError,
150};
151#[allow(deprecated)]
152pub use credential::CredentialsRegistry;
153pub use credential::{
154    AttachmentSite, CapturedCredential, Credential, CredentialFieldMarker, CredentialId,
155    CredentialIssuer, CredentialKind, CredentialKindName, CredentialMetadata, CredentialMinter,
156    CredentialScheme, CredentialsRegistryFallback, CredentialsRegistryProbe, DispatchSidecar,
157    HasCredentialMarkers, Origin, ParamName, Scope,
158};
159pub use forward::{
160    Anonymous, CallSite, ForwardDerivation, ForwardPolicy, ForwardPolicyName, IdentityOnly,
161    PassThrough, ANONYMOUS_NAME, IDENTITY_ONLY_NAME, PASS_THROUGH_NAME,
162};
163pub use grants::{
164    Ceiling, CeilingError, Gate, Grant, GrantSet, Membership, Memberships, Reach, Refusal, Resolve,
165    RoleOrGrant, RoleTable, RoleTableError, Roles, ScopeRef, ADMIN, CEILING_KEY,
166};
167pub use oidc::{
168    Audience, AudienceError, FetchError, FetchedDocument, JwksFetcher, OidcConfig, OidcError,
169    OidcSessionValidator, OidcValidator, VerifiedToken,
170};
171pub use principal::{Principal, ServiceIdentity};
172pub use scope_registry::{
173    Role, RoleNameError, ScopeError, ScopeRegistry, ScopeRegistryBuilder, ScopeRegistryError,
174};
175pub use tenant::{
176    ClaimTenantResolver, GateDenial, Scoped, SingleTenantResolver, Tenant, TenantBoundary,
177    TenantError, TenantGate, TenantId, TenantResolver, TenantRole, TenantScopedStore, TenantTagged,
178    Tenanted, UnknownRole,
179};
180pub use verified_user::VerifiedUser;