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`] — service-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/// BIDIR-5 / BIDIR-8: the gate's rules for a duplex call — who sends, who answers,
134/// how much, and what crosses a hop.
135pub mod duplex;
136
137/// AUTH-2: grants, roles, memberships, ceilings, and the gate.
138pub mod grants;
139
140pub use audit::{
141 AuditDecision, AuditQueue, AuditDenyReason, AuditRecord, AuditRecordKind, AuditSink, ForwardPolicyApplied,
142 RoleName, ScopeCheck, SensitiveField, SessionId, TracingAuditSink, UserId,
143};
144pub use auth::{AuthContext, SessionValidator, PRINCIPAL_CLAIM};
145// NOTE: `identity::Principal` is deliberately NOT re-exported here. The crate
146// root's `Principal` is the sealed caller-stamp (`principal::Principal`), and
147// the subject-name type is reached only as `plexus_auth_core::identity::Principal`
148// — the same disambiguation-by-module-path that `plexus-core` uses. See the
149// `identity` module docs for the full resolution of the name collision.
150pub use capabilities::{
151 AuthMechanism, BackendAuthCapabilities, BackendAuthCapabilitiesError, ClientId, ClientIdError,
152 CookieName, CookieNameError, HeaderName, HeaderNameError, IssuerUrl, IssuerUrlError,
153 MethodPath, MethodPathError,
154};
155#[allow(deprecated)]
156pub use credential::CredentialsRegistry;
157pub use credential::{
158 AttachmentSite, CapturedCredential, Credential, CredentialFieldMarker, CredentialId,
159 CredentialIssuer, CredentialKind, CredentialKindName, CredentialMetadata, CredentialMinter,
160 CredentialScheme, CredentialsRegistryFallback, CredentialsRegistryProbe, DispatchSidecar,
161 HasCredentialMarkers, Origin, ParamName, Scope,
162};
163pub use forward::{
164 Anonymous, CallSite, ForwardDerivation, ForwardPolicy, ForwardPolicyName, IdentityOnly,
165 PassThrough, ANONYMOUS_NAME, IDENTITY_ONLY_NAME, PASS_THROUGH_NAME,
166};
167pub use grants::{
168 AddressError, CallAddress, Ceiling, DispatchedCall, CeilingError, Fingerprint, Gate, Grant, GrantSet, Membership, Memberships, Reach, Refusal,
169 Resolve, RoleOrGrant, RoleTable, RoleTableError, Roles, ScopeRef, ADMIN, CEILING_KEY,
170};
171pub use oidc::{
172 Audience, AudienceError, FetchError, FetchedDocument, JwksFetcher, OidcConfig, OidcError,
173 OidcSessionValidator, OidcValidator, VerifiedToken,
174};
175pub use principal::{Principal, ServiceIdentity};
176pub use scope_registry::{
177 Role, RoleNameError, ScopeError, ScopeRegistry, ScopeRegistryBuilder, ScopeRegistryError,
178};
179pub use tenant::{
180 ClaimTenantResolver, GateDenial, Scoped, SingleTenantResolver, Tenant, TenantBoundary,
181 TenantError, TenantGate, TenantId, TenantResolver, TenantRole, TenantScopedStore, TenantTagged,
182 Tenanted, UnknownRole,
183};
184pub use verified_user::VerifiedUser;
185
186/// README.md's example, run by `cargo test --doc`.
187#[cfg(doctest)]
188#[doc = include_str!("../README.md")]
189pub struct ReadmeDoctests;