Skip to main content

plexus_auth_core/
credential.rs

1//! `Credential<T>`, `CredentialMinter`, and `CredentialMetadata` — sealed
2//! framework-level credential primitive.
3//!
4//! Per `AUTHZ-CRED-CORE-1` and AUTHZ-0 principle 6 ("the user's safety property
5//! is unforgeable"), a credential value is unforgeable from activation code.
6//! The compiler enforces this: there is no public constructor for
7//! [`Credential<T>`] reachable from outside `plexus-auth-core`, no public
8//! mutator, no `Default`, no `Deserialize`. The only path to producing a
9//! `Credential<T>` is via [`CredentialMinter::mint`], whose constructor is
10//! itself `pub(crate)` — the framework's dispatch layer (`plexus-core` /
11//! `plexus-transport`, in a follow-up ticket) is the only caller that can
12//! obtain a minter, and activation code receives an immutable reference.
13//!
14//! # Sealing summary (per AUTHZ-0 §"Crate-level isolation amplifies the seal")
15//!
16//! | Protection           | Mechanism                                      |
17//! |----------------------|------------------------------------------------|
18//! | No fabrication       | `Credential::new_sealed` is `pub(crate)`       |
19//! | No backdoor From/Into| Orphan rules forbid foreign-trait impls        |
20//! | No accidental Default| Not derived                                    |
21//! | No leaky Deserialize | Not derived; serialize-only round-trip         |
22//! | No mutation          | Fields private; no `&mut` accessors            |
23//! | No raw secret on wire| Custom `Serialize` emits a sentinel by default |
24//!
25//! # Sentinel-emitting serialization (Tier B Q-WIRE-3)
26//!
27//! `Credential<T>`'s `Serialize` impl emits, by default, a sentinel reference
28//! of the shape `{"$credential": "<id>"}` rather than the inner value. The
29//! framework's dispatch layer (per `AUTHZ-CRED-CORE-2`) flips a thread-local
30//! toggle via an RAII guard for the duration of envelope-building; while the
31//! toggle is set, the same `Serialize` impl additionally captures the value
32//! into a dispatch-side sidecar (see `with_dispatch_capture` — crate-private,
33//! reachable only inside `plexus-auth-core`). When the
34//! toggle is unset (the default — any naive `serde_json::to_value(&payload)`
35//! from application code, audit-log writers, or trace formatters), only the
36//! sentinel is emitted; the inner value never appears in the produced JSON.
37//!
38//! The toggle's setter is `pub(crate)`. Activation code has no public path
39//! to it. The guard's `Drop` impl clears the toggle even on panic so a
40//! mid-serialization panic cannot leak the value.
41//!
42//! See `tests/compile_fail/credential_*.rs` for the structural enforcement
43//! asserts.
44
45use std::cell::RefCell;
46use std::collections::HashMap;
47use std::sync::atomic::{AtomicU64, Ordering};
48
49use chrono::{DateTime, Utc};
50use schemars::JsonSchema;
51use serde::ser::{SerializeMap, Serializer};
52use serde::{Deserialize, Serialize};
53
54// ---------------------------------------------------------------------------
55// Strong-typed newtypes (per the strong-typing skill).
56//
57// Every metadata field that would otherwise be a bare `String` is a newtype
58// so the compiler catches accidental misuse. These mirror the names pinned
59// by AUTHZ-S01-output §1 and CLIENTS-S01-output §1; when those upstream
60// types land in shared crates this module's `pub use` aliases get retargeted
61// (see ticket §"Risks" #3 — local-stub-now / refactor-on-fast-follow).
62// ---------------------------------------------------------------------------
63
64macro_rules! string_newtype {
65    (
66        $(#[$meta:meta])*
67        $name:ident
68    ) => {
69        $(#[$meta])*
70        #[derive(
71            Debug,
72            Clone,
73            PartialEq,
74            Eq,
75            Hash,
76            PartialOrd,
77            Ord,
78            Serialize,
79            Deserialize,
80            JsonSchema,
81        )]
82        #[serde(transparent)]
83        pub struct $name(String);
84
85        impl $name {
86            /// Wrap a string as a typed value.
87            pub fn new(s: impl Into<String>) -> Self {
88                Self(s.into())
89            }
90
91            /// Borrow the underlying string.
92            pub fn as_str(&self) -> &str {
93                &self.0
94            }
95
96            /// Consume into the underlying string.
97            pub fn into_string(self) -> String {
98                self.0
99            }
100        }
101
102        impl std::fmt::Display for $name {
103            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104                f.write_str(&self.0)
105            }
106        }
107
108        impl From<String> for $name {
109            fn from(s: String) -> Self {
110                Self(s)
111            }
112        }
113
114        impl From<&str> for $name {
115            fn from(s: &str) -> Self {
116                Self(s.to_owned())
117            }
118        }
119    };
120}
121
122// MethodPath, HeaderName, CookieName are re-exported from `crate::capabilities`
123// (AUTHZ-CORE-3, which landed first). The wire-validated `try_new` constructors
124// live there.
125pub use crate::capabilities::{CookieName, HeaderName, MethodPath};
126
127string_newtype! {
128    /// Atomic capability identifier, e.g. `cone.send_message`. Canonical
129    /// `Scope` newtype pinned by AUTHZ-S01-output §1. The grammar-validated
130    /// constructor (`Scope::try_new`), wildcard predicate (`is_wildcard`),
131    /// and segment-bounded matching (`Scope::matches`) live in
132    /// `crate::scope_registry` (AUTHZ-CORE-4). The macro-generated
133    /// `Scope::new` below stays unvalidated for wire-decoded values;
134    /// registry construction goes through `try_new`.
135    Scope
136}
137
138string_newtype! {
139    /// Backend Origin identifier (typically a URL like `ws://localhost:4444`).
140    /// Local stub for the canonical `Origin` newtype pinned by
141    /// CLIENTS-S01-output §1. NOTE: the workspace also has an unrelated
142    /// `plexus_core::types::Origin` (plugin-id + method, not URL-shaped); the
143    /// AUTHZ-CRED design uses the URL-shaped Origin from CLIENTS-S01.
144    Origin
145}
146
147string_newtype! {
148    /// Credential attach-time prefix, e.g. `"Bearer "` (trailing space
149    /// included). Pinned by AUTHZ-CRED-S01-output §2.
150    CredentialScheme
151}
152
153string_newtype! {
154    /// Opaque kind name for `CredentialKind::Other`. The framework's
155    /// compatibility logic treats `Other`-kinded credentials as untagged for
156    /// the purposes of `requires_credential` matching (per Tier B Q-FLOW-2).
157    CredentialKindName
158}
159
160string_newtype! {
161    /// Parameter name for in-RPC-parameter and first-frame attachment sites.
162    ParamName
163}
164
165string_newtype! {
166    /// Per-response credential identifier (the `<id>` in the
167    /// `{"$credential": "<id>"}` sentinel). Generated by the framework's
168    /// dispatch layer at envelope-build time; opaque to activations.
169    CredentialId
170}
171
172// ---------------------------------------------------------------------------
173// CredentialKind — closed enum (Tier B Q-FLOW-2).
174// ---------------------------------------------------------------------------
175
176/// What kind of credential this is. Tags storage decisions and drives the
177/// selection filter (`AUTHZ-CRED-CLI-3`). **Closed** for v1 — third crates
178/// cannot extend the enum; backends with bespoke schemes use the
179/// [`CredentialKind::Other`] escape valve.
180///
181/// The cost of going `Other` is loss of generic client integration — a method
182/// requiring `Bearer` will not auto-attach an `Other`-kinded credential.
183#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
184#[serde(tag = "kind", rename_all = "snake_case")]
185pub enum CredentialKind {
186    /// Static or short-lived bearer token (JWT, opaque token).
187    Bearer,
188    /// Cookie-shaped session credential (server may issue `Set-Cookie`).
189    Cookie,
190    /// OAuth/OIDC access token (paired with refresh; `refresh_via` populated).
191    OauthAccess,
192    /// OAuth/OIDC refresh token. Long-lived, used to mint new
193    /// [`CredentialKind::OauthAccess`] credentials.
194    OauthRefresh,
195    /// OIDC ID token (informational identity assertion; not for auth).
196    OidcId,
197    /// AWS STS credential set (composite: access_key_id + secret + token + exp).
198    AwsSts,
199    /// Macaroon-style capability token with caveats.
200    Macaroon,
201    /// Custom kind, for backends with bespoke schemes; stored opaquely.
202    Other {
203        /// Opaque name supplied by the backend.
204        name: CredentialKindName,
205    },
206}
207
208// ---------------------------------------------------------------------------
209// AttachmentSite — closed enum.
210// ---------------------------------------------------------------------------
211
212/// Where the credential is attached on the wire when sent on subsequent
213/// calls. The framework's client-side replay machinery reads this to build
214/// the outbound request.
215#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
216#[serde(tag = "site", rename_all = "snake_case")]
217pub enum AttachmentSite {
218    /// HTTP header. e.g. `Authorization: <scheme><value>`.
219    Header {
220        /// The header name (e.g. `authorization`).
221        name: HeaderName,
222    },
223    /// HTTP cookie. e.g. `Cookie: plexus_session=<value>`.
224    Cookie {
225        /// The cookie name (e.g. `plexus_session`).
226        name: CookieName,
227    },
228    /// First-frame WS auth: included as a parameter to a setup method.
229    FirstFrame {
230        /// The method that the client calls first on the WS connection.
231        setup_method: MethodPath,
232        /// The parameter on that setup call where the credential is passed.
233        param: ParamName,
234    },
235    /// In-RPC parameter: each call receives this credential as a named
236    /// parameter on the inbound activation. Used for backends without HTTP
237    /// cookie/header support (e.g., pure stdio).
238    InRpcParam {
239        /// The parameter name on every credential-requiring method.
240        param: ParamName,
241    },
242}
243
244// ---------------------------------------------------------------------------
245// CredentialIssuer.
246// ---------------------------------------------------------------------------
247
248/// Identity of the issuing party: the Origin the credential was issued from
249/// and the method that issued it. Drives the named-session auto-naming
250/// algorithm (AUTHZ-CRED-S01-output §5) and ties the credential to its
251/// lineage in audit.
252#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
253pub struct CredentialIssuer {
254    /// Backend Origin that issued this credential.
255    pub origin: Origin,
256    /// Method whose return type carries this credential field.
257    pub method: MethodPath,
258}
259
260impl CredentialIssuer {
261    /// Construct a `CredentialIssuer` value. Public — the issuer is not a
262    /// secret; activation code may construct one to pass into mint (the
263    /// `Credential<T>` itself remains sealed).
264    pub fn new(origin: Origin, method: MethodPath) -> Self {
265        Self { origin, method }
266    }
267}
268
269// ---------------------------------------------------------------------------
270// CredentialMetadata — the framework's contract surface.
271// ---------------------------------------------------------------------------
272
273/// What this credential is and how to attach it on subsequent calls.
274///
275/// Every metadata field is a typed newtype, never a bare string. The
276/// [`CredentialMetadata::sensitive`] field is always `true`; it exists on the
277/// struct so the metadata is the single source of truth for the redaction
278/// pipeline (AUTHZ-PRIVACY-1).
279///
280/// Metadata is **fixed at mint time**: a `Credential<T>` exposes its metadata
281/// via [`Credential::metadata`], but there is no mutable accessor.
282#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
283pub struct CredentialMetadata {
284    /// What kind of credential this is. Tags storage decisions and drives
285    /// selection.
286    pub kind: CredentialKind,
287
288    /// Where the credential is attached on the wire when sent on subsequent
289    /// calls.
290    pub attach_as: AttachmentSite,
291
292    /// Optional prefix prepended to the value at attach time (e.g.,
293    /// `"Bearer "` for `Authorization: Bearer <token>`). Stored in the
294    /// metadata so the client doesn't have to guess.
295    pub scheme: Option<CredentialScheme>,
296
297    /// Which scopes this credential authorizes. Empty set means "scope
298    /// decision is server-side; client doesn't filter."
299    pub scopes: Vec<Scope>,
300
301    /// Hard expiry of the credential value, if known at issue time. Used
302    /// for proactive refresh and for dropping stale stored credentials.
303    pub expires_at: Option<DateTime<Utc>>,
304
305    /// Optional refresh hint: if this credential expires, call this method
306    /// to obtain a fresh one. The named-session framework handles the swap;
307    /// activation code is uninvolved.
308    pub refresh_via: Option<MethodPath>,
309
310    /// Optional revocation hint: calling this method invalidates the
311    /// credential server-side.
312    pub revoke_via: Option<MethodPath>,
313
314    /// Identity of the issuing party.
315    pub issuer: CredentialIssuer,
316
317    /// Sensitivity marker for the redaction pipeline (AUTHZ-PRIVACY-1).
318    /// Always `true`; present for type-system uniformity so any code that
319    /// reads the metadata has a single source of truth.
320    pub sensitive: bool,
321}
322
323impl CredentialMetadata {
324    /// Construct a fresh `CredentialMetadata`. The `sensitive` flag is always
325    /// initialized to `true`; the field exists so callers reading metadata
326    /// can treat it as the single source of truth without consulting outside
327    /// state.
328    ///
329    /// Public — the metadata is not a secret. The seal is on the credential
330    /// VALUE, not on the metadata that describes it.
331    #[allow(clippy::too_many_arguments)]
332    pub fn new(
333        kind: CredentialKind,
334        attach_as: AttachmentSite,
335        scheme: Option<CredentialScheme>,
336        scopes: Vec<Scope>,
337        expires_at: Option<DateTime<Utc>>,
338        refresh_via: Option<MethodPath>,
339        revoke_via: Option<MethodPath>,
340        issuer: CredentialIssuer,
341    ) -> Self {
342        Self {
343            kind,
344            attach_as,
345            scheme,
346            scopes,
347            expires_at,
348            refresh_via,
349            revoke_via,
350            issuer,
351            sensitive: true,
352        }
353    }
354}
355
356// ---------------------------------------------------------------------------
357// Credential<T> — the sealed wrapper.
358// ---------------------------------------------------------------------------
359
360/// A sealed credential value. The inner `T` is constructable only via a
361/// [`CredentialMinter`] — itself only obtainable as a function parameter
362/// injected by the framework into credential-issuing methods.
363///
364/// Activation code can:
365///   - Construct via `minter.mint(payload, metadata)` (the framework witnesses
366///     the construction)
367///   - Read metadata via [`Credential::metadata`] (immutable reference)
368///   - Serialize via `serde_json::to_value(&cred)` — this produces ONLY the
369///     sentinel `{"$credential": "<id>"}`; the inner value never appears.
370///
371/// Activation code CANNOT:
372///   - Construct from raw bytes (no public `new` / `From<T>`)
373///   - Mutate the inner value (no `&mut` accessor)
374///   - Read the inner value via `serde_json::to_value` (the custom `Serialize`
375///     impl writes the sentinel, not the value)
376///   - Deserialize from raw JSON (`Deserialize` is intentionally absent)
377///
378/// # Sealing
379///
380/// `Credential<T>::new_sealed` is `pub(crate)`. Only [`CredentialMinter`]
381/// inside this crate calls it. The compile-fail tests in
382/// `tests/compile_fail/credential_*.rs` assert that external construction
383/// is rejected.
384#[derive(Debug, Clone)]
385pub struct Credential<T> {
386    /// The inner credential value. Private — the only public accessor is
387    /// the custom `Serialize` impl, which writes the sentinel by default
388    /// and routes the value into the sidecar only when the dispatch-side
389    /// capture toggle is active.
390    inner: T,
391
392    /// The metadata fixed at mint time.
393    metadata: CredentialMetadata,
394
395    /// Stable per-credential id used in the `{"$credential": "<id>"}`
396    /// sentinel. Generated at mint time; opaque to activations.
397    id: CredentialId,
398}
399
400impl<T> Credential<T> {
401    /// Mint a new `Credential<T>`. Crate-private — only [`CredentialMinter`]
402    /// inside `plexus-auth-core` calls this. External crates cannot reach it
403    /// (compile-fail tests assert this).
404    pub(crate) fn new_sealed(inner: T, metadata: CredentialMetadata, id: CredentialId) -> Self {
405        Self {
406            inner,
407            metadata,
408            id,
409        }
410    }
411
412    /// Immutable accessor for the metadata. There is no mutable counterpart —
413    /// metadata is fixed at mint time.
414    pub fn metadata(&self) -> &CredentialMetadata {
415        &self.metadata
416    }
417
418    /// The credential's stable id (used in the wire sentinel).
419    pub fn id(&self) -> &CredentialId {
420        &self.id
421    }
422
423    /// Framework-internal accessor for the inner value. `pub(crate)` to
424    /// `plexus-auth-core` so the dispatch-bridge code inside this crate can
425    /// extract the value for sidecar emission. Activation code has no
426    /// public path to this method.
427    ///
428    /// Per ticket §"Risks" #2, the cross-crate accessor for the dispatch
429    /// layer in plexus-core will be added as a follow-up via a sealed marker
430    /// trait the dispatch crate implements; this `pub(crate)` accessor is
431    /// the first step.
432    ///
433    /// `dead_code` is allowed because the dispatch-layer caller lands in
434    /// `AUTHZ-CRED-CORE-2`; the accessor is exercised by this crate's unit
435    /// tests but has no production consumer until then.
436    #[allow(dead_code)]
437    pub(crate) fn inner(&self) -> &T {
438        &self.inner
439    }
440}
441
442// `Default` is intentionally NOT derived. A default credential would be an
443// unsigned, anonymously-minted value with no metadata — a security footgun.
444// Compile-fail test `tests/compile_fail/credential_no_default.rs` asserts.
445
446// `Deserialize` is intentionally NOT derived. Raw JSON must never fabricate
447// a sealed credential value; the only path to one is `CredentialMinter::mint`.
448
449// ---------------------------------------------------------------------------
450// Audit-side projection.
451// ---------------------------------------------------------------------------
452
453impl<T> Credential<T> {
454    /// Project to the metadata for audit-record emission. Read-only; the
455    /// returned reference is the metadata exactly as fixed at mint time.
456    ///
457    /// Equivalent to [`Self::metadata`], named separately to make the
458    /// audit-side projection grep-discoverable. Per
459    /// AUTHZ-CRED-S01-output §8, the audit pipeline records
460    /// `credentials_issued: Vec<CredentialMetadata>` — this is the projection
461    /// that produces it. The inner credential value is never included.
462    pub fn audit_projection(&self) -> &CredentialMetadata {
463        &self.metadata
464    }
465}
466
467// ---------------------------------------------------------------------------
468// Sentinel-emitting Serialize impl (Tier B Q-WIRE-3).
469// ---------------------------------------------------------------------------
470
471/// The shape of a credential captured into the dispatch-side sidecar.
472///
473/// `value` holds the JSON-encoded inner credential payload; `metadata` rides
474/// alongside; `id` is the stable per-credential identifier matching the
475/// `{"$credential": "<id>"}` sentinel emitted inline in the body. Only
476/// emitted into the sidecar when the dispatch capture toggle is active;
477/// otherwise the credential's `Serialize` impl emits only the sentinel.
478///
479/// The `id` field carries the same `CredentialId` that the sidecar's
480/// internal `HashMap` uses as its key. It is duplicated onto the
481/// `CapturedCredential` itself so the public scoped-callback API
482/// ([`run_with_credential_capture`]) can return a `Vec<CapturedCredential>`
483/// that is self-describing — callers do not need to track the id
484/// separately.
485#[derive(Debug, Clone)]
486pub struct CapturedCredential {
487    /// Stable per-credential id matching the `{"$credential": "<id>"}`
488    /// sentinel emitted inline.
489    pub id: CredentialId,
490    /// JSON-encoded inner value. Stored as `serde_json::Value` so the
491    /// dispatch wrapper can re-emit it in the envelope without re-serializing
492    /// the typed value through a second pass.
493    pub value: serde_json::Value,
494    /// The metadata as fixed at mint time.
495    pub metadata: CredentialMetadata,
496}
497
498/// Sidecar collector populated by the credential `Serialize` impl while a
499/// [`DispatchCaptureGuard`] is active. The dispatch layer reads the
500/// collected map after serialization completes and emits it as the
501/// `_credentials` envelope key (AUTHZ-CRED-S01-output §3, Q-WIRE-1).
502#[derive(Debug, Default)]
503pub struct DispatchSidecar {
504    /// Map of credential id → captured value+metadata.
505    map: HashMap<CredentialId, CapturedCredential>,
506}
507
508impl DispatchSidecar {
509    /// Construct an empty sidecar.
510    pub fn new() -> Self {
511        Self::default()
512    }
513
514    /// Drain the collected entries. The dispatch layer calls this after the
515    /// outer `Serialize` pass completes.
516    pub fn drain(&mut self) -> HashMap<CredentialId, CapturedCredential> {
517        std::mem::take(&mut self.map)
518    }
519
520    /// Whether the sidecar has captured any credential during the active
521    /// dispatch pass.
522    pub fn is_empty(&self) -> bool {
523        self.map.is_empty()
524    }
525
526    /// Number of captured credentials.
527    pub fn len(&self) -> usize {
528        self.map.len()
529    }
530}
531
532thread_local! {
533    /// While `Some(sidecar)`, the credential `Serialize` impl writes the
534    /// inner value into the sidecar AND emits the sentinel inline. While
535    /// `None` (the default — application code, audit writers, naive
536    /// `serde_json::to_value` calls), only the sentinel is emitted; the
537    /// value never appears in the produced JSON.
538    ///
539    /// There is no public setter for activation code. The only path to
540    /// install a sidecar is via [`DispatchCaptureGuard::install`], whose
541    /// constructor is `pub(crate)` and reachable only from the
542    /// dispatch-bridge code in this crate.
543    static DISPATCH_SIDECAR: RefCell<Option<DispatchSidecar>> = const { RefCell::new(None) };
544}
545
546/// Counter for auto-generated credential ids. The framework's dispatch
547/// layer is the only caller; activations never see this directly.
548static CREDENTIAL_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
549
550fn next_credential_id() -> CredentialId {
551    let n = CREDENTIAL_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
552    CredentialId::new(format!("cred_{n}"))
553}
554
555/// RAII guard that activates dispatch-side capture for the lifetime of the
556/// guard. The constructor is `pub(crate)`: activation code cannot create
557/// one. The dispatch layer (`plexus-core` / `plexus-transport`, via a
558/// `pub(crate)`-exposed helper in this crate) is the only caller.
559///
560/// On `Drop`, the guard clears the thread-local even if the wrapped
561/// operation panicked, so a mid-serialization panic cannot leak the value
562/// onto a subsequent reentrant call.
563pub struct DispatchCaptureGuard {
564    /// The previous sidecar (if any) is restored on drop, supporting nested
565    /// dispatch passes (rare but well-defined).
566    previous: Option<DispatchSidecar>,
567}
568
569impl DispatchCaptureGuard {
570    /// Install a fresh sidecar for the lifetime of the returned guard.
571    /// `pub(crate)` — activation code has no path to construct one.
572    ///
573    /// `dead_code` is allowed because the dispatch-layer caller lands in
574    /// `AUTHZ-CRED-CORE-2`; the guard must exist now so the compile-fail
575    /// tests can assert external code cannot reach it.
576    #[allow(dead_code)]
577    pub(crate) fn install() -> Self {
578        let previous = DISPATCH_SIDECAR.with(|cell| {
579            let prev = cell.borrow_mut().take();
580            *cell.borrow_mut() = Some(DispatchSidecar::new());
581            prev
582        });
583        Self { previous }
584    }
585
586    /// Drain the captured credentials from the active sidecar. Returns
587    /// `None` if (unexpectedly) no sidecar is installed. `pub(crate)` for
588    /// the same reason as [`Self::install`].
589    #[allow(dead_code)]
590    pub(crate) fn drain(&self) -> Option<HashMap<CredentialId, CapturedCredential>> {
591        DISPATCH_SIDECAR.with(|cell| cell.borrow_mut().as_mut().map(|s| s.drain()))
592    }
593}
594
595impl Drop for DispatchCaptureGuard {
596    fn drop(&mut self) {
597        // Restore the previous sidecar (or clear). Done unconditionally so a
598        // panic mid-serialization cannot leave the toggle dangling.
599        let prev = self.previous.take();
600        DISPATCH_SIDECAR.with(|cell| {
601            *cell.borrow_mut() = prev;
602        });
603    }
604}
605
606/// Convenience helper: run `f` with a fresh dispatch sidecar installed, then
607/// return both `f`'s output and the captured credentials.
608///
609/// `pub(crate)` — same reason as [`DispatchCaptureGuard`].
610///
611/// # Panic-safety
612///
613/// If `f` panics, the guard's `Drop` impl clears the thread-local before
614/// the panic unwinds past this function, so a subsequent reentrant call
615/// observes a clean state. See the unit test
616/// `dispatch_capture_resets_on_panic` for the assertion.
617#[allow(dead_code)]
618pub(crate) fn with_dispatch_capture<F, R>(f: F) -> (R, HashMap<CredentialId, CapturedCredential>)
619where
620    F: FnOnce() -> R,
621{
622    let guard = DispatchCaptureGuard::install();
623    let out = f();
624    let captured = guard.drain().unwrap_or_default();
625    drop(guard);
626    (out, captured)
627}
628
629/// Public scoped-callback entry point for dispatch-time credential capture.
630///
631/// Mirrors the AUTHLANG-3 [`crate::auth::AuthContext::with_callee_context`]
632/// pattern: the framework operation (installing the
633/// [`DispatchCaptureGuard`]) is exposed to other crates ONLY for the
634/// duration of a caller-supplied closure. External callers cannot retain
635/// the guard past the function return — the seal property is "the guard's
636/// lifetime is bounded by the function call."
637///
638/// # Behavior
639///
640/// 1. Installs a fresh [`DispatchCaptureGuard`] on the current thread.
641/// 2. Runs `f`.
642/// 3. Drains the captured credentials from the guard's sidecar.
643/// 4. Drops the guard (restoring any previously-installed sidecar).
644/// 5. Returns `(f_output, Vec<CapturedCredential>)`.
645///
646/// Each returned [`CapturedCredential`] carries its own [`CredentialId`]
647/// matching the `{"$credential": "<id>"}` sentinel emitted inline in the
648/// serialized body, so the caller can correlate sidecar entries with
649/// sentinels without tracking a side map.
650///
651/// # Nested invocations
652///
653/// Nested calls to `run_with_credential_capture` install a fresh inner
654/// sidecar; inner credentials drain to the inner caller and the outer
655/// continues with its own (still-pending) sidecar after the inner
656/// returns. The two sidecars never interleave — the [`DispatchCaptureGuard`]'s
657/// `Drop` impl restores the previously-installed sidecar.
658///
659/// # Panic safety
660///
661/// If `f` panics, the guard's `Drop` impl clears the thread-local on
662/// unwind so a subsequent reentrant call observes a clean state. The
663/// partial sidecar is not delivered to the caller — capture is
664/// all-or-nothing per envelope by design.
665///
666/// # Sync-only (v1)
667///
668/// `f` is a synchronous `FnOnce`. If `f` returns a `Future`, the future
669/// executes AFTER the guard is dropped — credentials minted inside an
670/// awaited continuation are not captured. CRED-CORE-2's dispatch wrapper
671/// serializes synchronously into a buffer, so the synchronous shape
672/// suffices for v1. An async-aware variant (`run_with_credential_capture_async`)
673/// can land in a follow-up if a dispatch path needs awaiting inside the
674/// capture scope.
675///
676/// # Why scoped-callback, not a `pub install`?
677///
678/// Per AUTHZ-0 §"Sealed-type pattern": the policy proposes; the framework
679/// disposes. Exposing a raw `pub fn install() -> DispatchCaptureGuard`
680/// would let activation code retain a guard for an unbounded lifetime
681/// and observe credentials minted by unrelated framework code on the
682/// same thread. The scoped-callback shape pins the guard's lifetime to
683/// the closure, which is the actual seal property we need.
684///
685/// See `plans/AUTHZ/AUTHZ-CRED-CORE-1B.md` for the design rationale.
686pub fn run_with_credential_capture<F, R>(f: F) -> (R, Vec<CapturedCredential>)
687where
688    F: FnOnce() -> R,
689{
690    let guard = DispatchCaptureGuard::install();
691    let out = f();
692    let captured_map = guard.drain().unwrap_or_default();
693    drop(guard);
694    // Sort by id for deterministic ordering. Credential ids are assigned
695    // by an atomic counter in mint order, so this is also mint order.
696    let mut captured: Vec<CapturedCredential> = captured_map.into_values().collect();
697    captured.sort_by(|a, b| a.id.as_str().cmp(b.id.as_str()));
698    (out, captured)
699}
700
701impl<T> Serialize for Credential<T>
702where
703    T: Serialize,
704{
705    /// Emits the sentinel `{"$credential": "<id>"}` always.
706    ///
707    /// If a dispatch-capture guard is active on the current thread, the
708    /// inner value is ALSO captured into the sidecar (keyed by id) so the
709    /// dispatch wrapper can emit it under the envelope's `_credentials`
710    /// key. Application code that calls `serde_json::to_value(&credential)`
711    /// without a guard sees only the sentinel — the inner value never
712    /// appears in the produced JSON.
713    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
714    where
715        S: Serializer,
716    {
717        // Capture into the sidecar if active. We do this BEFORE writing the
718        // sentinel so a serialization failure mid-write does not leave a
719        // half-captured value visible to the dispatch wrapper.
720        //
721        // Serializing the inner value to a `serde_json::Value` here is a
722        // necessary step because the outer Serializer may not be JSON
723        // (e.g., bincode used by an audit sink, MessagePack); the sidecar
724        // is JSON-only by design (the envelope is JSON-RPC), so we lift
725        // the inner value to JSON for sidecar storage regardless of the
726        // outer serializer's target format.
727        DISPATCH_SIDECAR.with(|cell| {
728            let mut borrow = cell.borrow_mut();
729            if let Some(sidecar) = borrow.as_mut() {
730                // Failure to JSON-serialize the inner value is non-fatal for
731                // the sentinel emission — the dispatch wrapper sees the
732                // missing entry and surfaces a structured error later. We
733                // store a `null` placeholder so the id is reserved even on
734                // serialization failure (rare; T is constrained Serialize).
735                let value = serde_json::to_value(&self.inner).unwrap_or(serde_json::Value::Null);
736                sidecar.map.insert(
737                    self.id.clone(),
738                    CapturedCredential {
739                        id: self.id.clone(),
740                        value,
741                        metadata: self.metadata.clone(),
742                    },
743                );
744            }
745        });
746
747        // Emit the sentinel. Always — whether or not a guard is active, the
748        // outer JSON document contains only `{"$credential": "<id>"}` where
749        // the credential lived. The inner value never inlines here.
750        let mut map = serializer.serialize_map(Some(1))?;
751        map.serialize_entry("$credential", self.id.as_str())?;
752        map.end()
753    }
754}
755
756// ---------------------------------------------------------------------------
757// CredentialMinter — the framework's injected service.
758// ---------------------------------------------------------------------------
759
760/// The framework-issued service that mints sealed [`Credential<T>`] values.
761///
762/// `CredentialMinter`'s constructor is `pub(crate)` — only `plexus-auth-core`
763/// can produce one. The framework's dispatch layer (per `AUTHZ-CRED-CORE-2`)
764/// injects a `&CredentialMinter` into credential-issuing methods; activation
765/// code receives the reference but cannot construct its own minter, nor
766/// extend the seal by aliasing the type.
767///
768/// The minter ties construction to the originating method invocation so
769/// audit can attribute the issuance. v1 carries the issuer hint as a stored
770/// field on the minter so [`CredentialMinter::mint_with_issuer`] does not
771/// require it as a separate argument; richer audit context (call id,
772/// invocation chain position) is added in `AUTHZ-CRED-CORE-2` when the
773/// dispatch-layer wiring lands.
774#[derive(Debug, Clone)]
775pub struct CredentialMinter {
776    /// The issuer that subsequent mints stamp onto every credential's
777    /// metadata when [`CredentialMinter::mint_with_issuer`] is used (the
778    /// variant that takes pre-built metadata bypasses this field).
779    default_issuer: CredentialIssuer,
780}
781
782impl CredentialMinter {
783    /// Construct a minter scoped to a particular issuer. Crate-private —
784    /// only the framework's dispatch layer (in a follow-up ticket) calls
785    /// this; activation code receives a reference, never constructs one.
786    ///
787    /// `dead_code` is allowed because the dispatch-layer caller lands in
788    /// `AUTHZ-CRED-CORE-2`. The constructor must exist now so the
789    /// compile-fail tests have something to point at.
790    #[allow(dead_code)]
791    pub(crate) fn new_sealed(default_issuer: CredentialIssuer) -> Self {
792        Self { default_issuer }
793    }
794
795    /// Test-only constructor exposed under the `test-support` feature.
796    ///
797    /// Production builds never see this method — the `test-support`
798    /// feature is documented as a `dev-dependency`-only flag (see
799    /// `Cargo.toml`). The `#[doc(hidden)]` attribute keeps it out of
800    /// rustdoc so the public API surface still reads as
801    /// "no constructor reachable from outside the crate."
802    ///
803    /// Added by AUTHZ-CRED-CORE-1B so plexus-core can write end-to-end
804    /// tests of the dispatch-time credential interception path that
805    /// require minting a real `Credential<T>`.
806    #[cfg(feature = "test-support")]
807    #[doc(hidden)]
808    pub fn new_for_test(default_issuer: CredentialIssuer) -> Self {
809        Self { default_issuer }
810    }
811
812    /// The default issuer the minter stamps onto credentials minted via
813    /// [`CredentialMinter::mint_with_issuer`]. Useful for audit hooks.
814    pub fn issuer(&self) -> &CredentialIssuer {
815        &self.default_issuer
816    }
817
818    /// Mint a sealed [`Credential<T>`] from a raw payload and pre-built
819    /// metadata.
820    ///
821    /// This is the **only** public path from a raw `T` to a sealed
822    /// `Credential<T>`. Activation code calls it via the framework-injected
823    /// `&CredentialMinter` reference.
824    pub fn mint<T>(&self, payload: T, metadata: CredentialMetadata) -> Credential<T> {
825        let id = next_credential_id();
826        Credential::new_sealed(payload, metadata, id)
827    }
828
829    /// Mint a sealed [`Credential<T>`] from a raw payload, populating the
830    /// metadata's `issuer` field from the minter's [`Self::issuer`]. The
831    /// caller supplies everything else.
832    #[allow(clippy::too_many_arguments)]
833    pub fn mint_with_issuer<T>(
834        &self,
835        payload: T,
836        kind: CredentialKind,
837        attach_as: AttachmentSite,
838        scheme: Option<CredentialScheme>,
839        scopes: Vec<Scope>,
840        expires_at: Option<DateTime<Utc>>,
841        refresh_via: Option<MethodPath>,
842        revoke_via: Option<MethodPath>,
843    ) -> Credential<T> {
844        let metadata = CredentialMetadata::new(
845            kind,
846            attach_as,
847            scheme,
848            scopes,
849            expires_at,
850            refresh_via,
851            revoke_via,
852            self.default_issuer.clone(),
853        );
854        self.mint(payload, metadata)
855    }
856}
857
858// ---------------------------------------------------------------------------
859// CredentialFieldMarker — registry entry emitted by `#[derive(Credentials)]`.
860// ---------------------------------------------------------------------------
861
862/// A single registry entry describing one `#[credential(...)]`-annotated
863/// field on a credential-bearing type. The
864/// `#[derive(plexus_macros::Credentials)]` macro emits a per-type free
865/// function `__plexus_credential_marker_for_<TypeIdent>() ->
866/// Vec<CredentialFieldMarker>` returning these entries in stable
867/// declaration order.
868///
869/// # Shape
870///
871/// The fields below mirror the macro's emission contract (see
872/// `plexus-macros/src/credential.rs::emit_field_marker_initializer`):
873///
874/// - [`Self::variant`] — `Some(variant_name)` for enums, `None` for structs.
875/// - [`Self::field`] — the field's identifier, e.g. `"session"`. For tuple
876///   fields, the zero-based index as a string ("0", "1", ...).
877/// - [`Self::kind`] — credential kind (`Bearer`, `Cookie`, `OauthAccess`, ...).
878/// - [`Self::attach_as`] — where the credential is attached on the wire.
879/// - [`Self::scheme`] — optional attach-time prefix (e.g. `"Bearer "`).
880/// - [`Self::scopes`] — declared scopes for the credential.
881/// - [`Self::refresh_via`] — optional method to refresh an expired credential.
882/// - [`Self::revoke_via`] — optional method to revoke the credential.
883///
884/// # Aggregating into `CredentialMetadata`
885///
886/// The marker carries the credential's *static* metadata as declared at the
887/// field. The full [`CredentialMetadata`] form additionally requires
888/// `expires_at` (known only at mint time) and `issuer` (known only at runtime
889/// from the originating method). [`Self::to_metadata`] composes a partial
890/// `CredentialMetadata` value, leaving `expires_at` and `issuer` to be
891/// supplied by the dispatch layer.
892///
893/// # Consumers
894///
895/// - `AUTHZ-CRED-CORE-3` (schema-build credential reflection): reads markers
896///   to project credential metadata into the IR / `MethodSchema`.
897/// - Backends instrumenting the registry for diagnostic purposes.
898///
899/// # `parent_type_id` (deferred)
900///
901/// The ticket described a `parent_type_id: std::any::TypeId` field for
902/// `TypeId`-keyed registry lookup. The macro's v1 emission keys the registry
903/// by *function name* (`__plexus_credential_marker_for_<TypeIdent>`), not by
904/// `TypeId`; adding `parent_type_id` to this struct would require either
905/// (a) a `T: 'static` bound at the derive site, threading it through the
906/// macro, or (b) materializing the `TypeId` in the emitted function and
907/// stamping it onto every entry. Both are additive; neither is needed by the
908/// current consumer set (`AUTHZ-CRED-CORE-3`'s schema projection works from
909/// the function-name surface). Tracked as the follow-up note in
910/// `AUTHZ-CRED-MACRO-1-RUN-NOTES.md`.
911///
912/// Similarly, a `field_index: u16` is implicit in the slice index returned
913/// from the registry function; callers needing index can `.iter().enumerate()`.
914///
915/// # `TypeId` cross-compilation-unit caveat
916///
917/// When `parent_type_id` lands in a follow-up: `std::any::TypeId` is
918/// documented as stable *within a single compiled binary*, not across
919/// independently compiled libraries or Rust versions. The v1 use case
920/// (one binary registering markers and reading them in the same binary) is
921/// fine; cross-binary registry sharing would require a hashed name or a
922/// stable type-id scheme.
923#[derive(Debug, Clone)]
924pub struct CredentialFieldMarker {
925    /// For enums: the variant name where the field lives. For structs:
926    /// `None`.
927    pub variant: Option<&'static str>,
928
929    /// The field's identifier (e.g. `"session"`). For tuple fields, the
930    /// zero-based index rendered as a string.
931    pub field: &'static str,
932
933    /// Credential kind (Bearer, Cookie, OauthAccess, ...).
934    pub kind: CredentialKind,
935
936    /// Where on the wire the credential is attached when sent on subsequent
937    /// calls.
938    pub attach_as: AttachmentSite,
939
940    /// Optional attach-time prefix (e.g. `"Bearer "` for
941    /// `Authorization: Bearer <token>`).
942    pub scheme: Option<CredentialScheme>,
943
944    /// Declared scopes for the credential. Empty if not specified.
945    pub scopes: Vec<Scope>,
946
947    /// Optional method-path the framework calls to refresh this credential
948    /// when it expires.
949    pub refresh_via: Option<MethodPath>,
950
951    /// Optional method-path the framework calls to revoke this credential
952    /// server-side.
953    pub revoke_via: Option<MethodPath>,
954}
955
956impl CredentialFieldMarker {
957    /// Construct a marker. Public — registry entries are user-facing
958    /// metadata, not a sealed primitive. The macro emits struct-literal
959    /// initializers; this constructor exists for backend code that builds
960    /// markers programmatically.
961    #[allow(clippy::too_many_arguments)]
962    pub fn new(
963        variant: Option<&'static str>,
964        field: &'static str,
965        kind: CredentialKind,
966        attach_as: AttachmentSite,
967        scheme: Option<CredentialScheme>,
968        scopes: Vec<Scope>,
969        refresh_via: Option<MethodPath>,
970        revoke_via: Option<MethodPath>,
971    ) -> Self {
972        Self {
973            variant,
974            field,
975            kind,
976            attach_as,
977            scheme,
978            scopes,
979            refresh_via,
980            revoke_via,
981        }
982    }
983
984    /// Compose a [`CredentialMetadata`] from this marker plus the runtime-
985    /// supplied pieces (`expires_at` from mint time, `issuer` from the
986    /// invoking method's context).
987    ///
988    /// The marker carries the *static* metadata declared at the field; the
989    /// dispatch layer supplies the dynamic pieces. Together they fully
990    /// reconstruct the metadata that [`CredentialMinter::mint`] would mint.
991    pub fn to_metadata(
992        &self,
993        expires_at: Option<chrono::DateTime<chrono::Utc>>,
994        issuer: CredentialIssuer,
995    ) -> CredentialMetadata {
996        CredentialMetadata::new(
997            self.kind.clone(),
998            self.attach_as.clone(),
999            self.scheme.clone(),
1000            self.scopes.clone(),
1001            expires_at,
1002            self.refresh_via.clone(),
1003            self.revoke_via.clone(),
1004            issuer,
1005        )
1006    }
1007}
1008
1009// ---------------------------------------------------------------------------
1010// CredentialsRegistry — autoref-specialized marker-slice dispatch wiring the
1011// macro-emitted credential registry to consumer codegen (AUTHZ-CRED-MACRO-3).
1012// ---------------------------------------------------------------------------
1013
1014/// Trait that types deriving `#[derive(plexus_macros::Credentials)]` opt into
1015/// by providing their static credential-marker slice.
1016///
1017/// Consumers do not implement this trait by hand; the
1018/// `#[derive(plexus_macros::Credentials)]` macro emits the impl with the
1019/// populated `credential_markers()` body. Types that do NOT derive
1020/// `Credentials` do not implement this trait at all — instead, the
1021/// `#[plexus_macros::activation]` call site dispatches to the blanket
1022/// fallback [`CredentialsRegistryFallback`] which returns an empty slice.
1023///
1024/// # Why a separate marker trait?
1025///
1026/// The autoref-specialization trick (see [`CredentialsRegistryProbe`])
1027/// uses TWO impls on `CredentialsRegistryProbe<T>`:
1028///
1029/// 1. An inherent impl gated on `T: HasCredentialMarkers` — populated path.
1030/// 2. A trait impl on `&CredentialsRegistryProbe<T>` — empty fallback path.
1031///
1032/// Inherent impls are constrained to the type's home crate (orphan rule
1033/// E0116); the user's `#[derive(Credentials)]` cannot write
1034/// `impl CredentialsRegistryProbe<UserType>` because `CredentialsRegistryProbe`
1035/// lives in `plexus_auth_core`. The marker trait sidesteps this: the user's
1036/// derive emits a normal trait impl `impl HasCredentialMarkers for UserType`
1037/// (orphan-allowed), and `plexus_auth_core`'s generic inherent impl
1038/// `impl<T: HasCredentialMarkers> CredentialsRegistryProbe<T>` does the
1039/// dispatch.
1040pub trait HasCredentialMarkers {
1041    /// Return the static slice of credential-field markers for this type.
1042    /// Emitted by the `#[derive(Credentials)]` macro; not implemented by
1043    /// hand.
1044    fn credential_markers() -> &'static [CredentialFieldMarker];
1045}
1046
1047/// Type-erased "probe" used by the autoref-specialization trick to dispatch
1048/// to either the populated marker slice (when `T: HasCredentialMarkers`) or
1049/// the empty fallback (otherwise).
1050///
1051/// Consumers do not construct this directly; the `#[plexus_macros::method]`
1052/// codegen emits the call site
1053/// `(&CredentialsRegistryProbe::<ReturnType>::new()).marker_slice()`. Rust's
1054/// method-resolution rules prefer inherent methods over trait methods, so
1055/// the inherent `marker_slice` on `CredentialsRegistryProbe<T>` (gated on
1056/// `T: HasCredentialMarkers`) wins when the return type derives
1057/// `Credentials`. Otherwise autoref kicks in and the trait method on
1058/// `&CredentialsRegistryProbe<T>` provides the empty-slice fallback.
1059///
1060/// # Why autoref-specialization?
1061///
1062/// The straightforward shape — a trait `CredentialsRegistry` with a default
1063/// `marker_slice()` method — requires either (a) a blanket `impl<T>` (which
1064/// then cannot be overridden by the derive without nightly specialization),
1065/// or (b) every consumer type explicitly implementing the trait (which would
1066/// be a breaking change for the entire workspace). The probe-with-autoref
1067/// pattern preserves stable Rust, requires zero opt-in from non-deriving
1068/// types, and lets the macro emit a normal trait impl (orphan-allowed) on
1069/// the user's type to drive the specialized inherent path.
1070///
1071/// See `plans/AUTHZ/AUTHZ-CRED-MACRO-3-RUN-NOTES.md` for the design rationale
1072/// and alternatives considered.
1073#[doc(hidden)]
1074pub struct CredentialsRegistryProbe<T: ?Sized>(::core::marker::PhantomData<fn() -> T>);
1075
1076impl<T: ?Sized> CredentialsRegistryProbe<T> {
1077    /// Construct a fresh probe value. Free of runtime cost — the inner
1078    /// `PhantomData` carries no data, only the type parameter.
1079    #[doc(hidden)]
1080    pub const fn new() -> Self {
1081        Self(::core::marker::PhantomData)
1082    }
1083}
1084
1085impl<T: ?Sized> Default for CredentialsRegistryProbe<T> {
1086    fn default() -> Self {
1087        Self::new()
1088    }
1089}
1090
1091/// Specialized inherent path: when `T: HasCredentialMarkers`, the probe
1092/// exposes the populated marker slice via `T::credential_markers()`.
1093/// Rust prefers this inherent method over the trait method from the
1094/// fallback impl, so types that derive `Credentials` always hit this path.
1095impl<T: HasCredentialMarkers + ?Sized> CredentialsRegistryProbe<T> {
1096    /// Forward to `T::credential_markers()`. The probe call site never
1097    /// names this method directly; macro-emitted code at the activation
1098    /// site calls `(&probe).marker_slice()`, and autoref-resolution picks
1099    /// this inherent method over the trait fallback.
1100    #[doc(hidden)]
1101    pub fn marker_slice(&self) -> &'static [CredentialFieldMarker] {
1102        T::credential_markers()
1103    }
1104}
1105
1106/// Fallback path: when `T` does NOT implement `HasCredentialMarkers`, the
1107/// inherent `marker_slice` doesn't apply, autoref kicks in, and the
1108/// reference-typed trait impl below supplies the empty-slice default.
1109///
1110/// Consumers do not name this trait; the `#[plexus_macros::activation]`
1111/// codegen brings it into scope via a `use` declaration inside the
1112/// macro-generated `compute_method_schemas` body, so the same call site
1113/// (`(&probe).marker_slice()`) works whether the return type derives
1114/// `Credentials` or not.
1115pub trait CredentialsRegistryFallback {
1116    /// Empty-slice fallback. Pre-AUTHZ-CRED-MACRO-3 behavior — every
1117    /// method's `MethodSchema.credentials` was `[]`; the fallback preserves
1118    /// that for types that don't derive `Credentials`.
1119    fn marker_slice(&self) -> &'static [CredentialFieldMarker] {
1120        &[]
1121    }
1122}
1123
1124// Blanket impl on `&CredentialsRegistryProbe<T>` — autoref lands here for
1125// types that don't have the `HasCredentialMarkers` inherent path.
1126impl<T: ?Sized> CredentialsRegistryFallback for &CredentialsRegistryProbe<T> {}
1127
1128/// Deprecated alias kept while consumers migrate to the new
1129/// [`CredentialsRegistryFallback`] name.
1130///
1131/// The original AUTHZ-CRED-MACRO-3 trait shape was named
1132/// `CredentialsRegistry`; renaming it to
1133/// [`CredentialsRegistryFallback`] makes the trait's role at the call site
1134/// (fallback path only) explicit. This alias preserves call sites that
1135/// already wrote `use plexus_auth_core::CredentialsRegistry`.
1136#[deprecated(
1137    since = "0.1.0",
1138    note = "Use `CredentialsRegistryFallback` instead (renamed for clarity)."
1139)]
1140pub trait CredentialsRegistry: CredentialsRegistryFallback {}
1141
1142#[allow(deprecated)]
1143impl<T: CredentialsRegistryFallback + ?Sized> CredentialsRegistry for T {}
1144
1145// ---------------------------------------------------------------------------
1146// Unit tests.
1147// ---------------------------------------------------------------------------
1148
1149#[cfg(test)]
1150mod tests {
1151    use super::*;
1152
1153    fn sample_issuer() -> CredentialIssuer {
1154        CredentialIssuer::new(
1155            Origin::new("ws://localhost:4444"),
1156            MethodPath::try_new("auth.login").unwrap(),
1157        )
1158    }
1159
1160    fn sample_metadata() -> CredentialMetadata {
1161        CredentialMetadata::new(
1162            CredentialKind::Bearer,
1163            AttachmentSite::Header {
1164                name: HeaderName::try_new("authorization").unwrap(),
1165            },
1166            Some(CredentialScheme::new("Bearer ")),
1167            vec![Scope::new("cone.send_message")],
1168            None,
1169            Some(MethodPath::try_new("auth.refresh").unwrap()),
1170            Some(MethodPath::try_new("auth.logout").unwrap()),
1171            sample_issuer(),
1172        )
1173    }
1174
1175    #[test]
1176    fn minter_mints_credential_via_internal_api() {
1177        // Acceptance criterion 2 + the ticket's "CredentialMinter mints
1178        // successfully via internal API" test.
1179        let minter = CredentialMinter::new_sealed(sample_issuer());
1180        let cred: Credential<String> =
1181            minter.mint("eyJhbGciOiJIUzI1NiIs...token".to_string(), sample_metadata());
1182        // The credential carries the metadata verbatim.
1183        assert_eq!(cred.metadata().kind, CredentialKind::Bearer);
1184        // The audit projection equals the metadata.
1185        assert_eq!(cred.audit_projection(), cred.metadata());
1186        // The inner accessor is reachable from inside the crate (this test
1187        // lives inside `plexus-auth-core`).
1188        assert_eq!(cred.inner(), "eyJhbGciOiJIUzI1NiIs...token");
1189    }
1190
1191    #[test]
1192    fn metadata_sensitive_is_always_true() {
1193        let m = sample_metadata();
1194        assert!(m.sensitive, "sensitive must be initialized to true");
1195    }
1196
1197    #[test]
1198    fn credential_id_is_unique_per_mint() {
1199        let minter = CredentialMinter::new_sealed(sample_issuer());
1200        let c1: Credential<String> = minter.mint("a".to_string(), sample_metadata());
1201        let c2: Credential<String> = minter.mint("b".to_string(), sample_metadata());
1202        assert_ne!(c1.id(), c2.id());
1203    }
1204
1205    #[test]
1206    fn serialize_outside_dispatch_emits_only_sentinel() {
1207        // Acceptance criterion 9: serde_json::to_value(&credential) outside
1208        // dispatch context produces an object containing the $credential
1209        // sentinel and NO inner value.
1210        let minter = CredentialMinter::new_sealed(sample_issuer());
1211        let cred: Credential<String> =
1212            minter.mint("super-secret-token".to_string(), sample_metadata());
1213        let v = serde_json::to_value(&cred).expect("serialize");
1214        // The serialized form is exactly `{"$credential": "<id>"}`.
1215        let obj = v.as_object().expect("object");
1216        assert_eq!(obj.len(), 1, "sentinel is the only key");
1217        let id = obj
1218            .get("$credential")
1219            .and_then(|v| v.as_str())
1220            .expect("$credential id is a string");
1221        assert_eq!(id, cred.id().as_str());
1222        // The inner value never appears in the serialized form.
1223        let serialized = serde_json::to_string(&cred).expect("string");
1224        assert!(
1225            !serialized.contains("super-secret-token"),
1226            "inner value must not appear in default serialization, got: {serialized}"
1227        );
1228    }
1229
1230    #[test]
1231    fn serialize_inside_dispatch_captures_value_into_sidecar() {
1232        // Acceptance criterion 10: when the dispatch-side thread-local is
1233        // active under a scoped guard, the inner value is captured into a
1234        // sidecar AND the sentinel is emitted inline. When inactive, only
1235        // the sentinel is emitted.
1236        let minter = CredentialMinter::new_sealed(sample_issuer());
1237        let cred: Credential<String> =
1238            minter.mint("dispatch-secret".to_string(), sample_metadata());
1239
1240        let (json_value, captured) = with_dispatch_capture(|| {
1241            serde_json::to_value(&cred).expect("serialize under guard")
1242        });
1243
1244        // The outer JSON still contains only the sentinel.
1245        let obj = json_value.as_object().expect("object");
1246        assert!(obj.contains_key("$credential"));
1247        assert!(!obj.contains_key("inner"));
1248
1249        // The sidecar captured the inner value keyed by id.
1250        assert_eq!(captured.len(), 1);
1251        let entry = captured.get(cred.id()).expect("captured by id");
1252        assert_eq!(
1253            entry.value,
1254            serde_json::Value::String("dispatch-secret".into())
1255        );
1256        assert_eq!(entry.metadata.kind, CredentialKind::Bearer);
1257
1258        // After the guard drops, a subsequent serialization is back to
1259        // sentinel-only (no value capture).
1260        let plain = serde_json::to_value(&cred).expect("serialize after guard");
1261        assert!(plain
1262            .as_object()
1263            .expect("object")
1264            .contains_key("$credential"));
1265        // And the inner value does not appear in the plain serialization.
1266        let plain_str = serde_json::to_string(&plain).unwrap();
1267        assert!(!plain_str.contains("dispatch-secret"));
1268    }
1269
1270    #[test]
1271    fn dispatch_capture_resets_on_panic() {
1272        // Acceptance criterion 11: the toggle's guard is reset on drop even
1273        // when the wrapped operation panics. A subsequent serialization
1274        // must see a clean state (no leaking into a stale sidecar).
1275        let minter = CredentialMinter::new_sealed(sample_issuer());
1276        let cred: Credential<String> =
1277            minter.mint("panic-time-secret".to_string(), sample_metadata());
1278
1279        // Run a closure that installs the guard then panics. We use
1280        // catch_unwind so the test framework doesn't abort.
1281        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1282            let _guard = DispatchCaptureGuard::install();
1283            // Confirm capture is active.
1284            DISPATCH_SIDECAR.with(|cell| {
1285                assert!(cell.borrow().is_some(), "sidecar installed");
1286            });
1287            panic!("simulated panic mid-serialization");
1288        }));
1289
1290        // After the panic, the thread-local must be clean.
1291        DISPATCH_SIDECAR.with(|cell| {
1292            assert!(
1293                cell.borrow().is_none(),
1294                "sidecar must be cleared on panic — got Some"
1295            );
1296        });
1297
1298        // And a subsequent default serialization still emits the sentinel.
1299        let v = serde_json::to_value(&cred).expect("serialize after panic");
1300        let obj = v.as_object().expect("object");
1301        assert!(obj.contains_key("$credential"));
1302        // No stray value capture from a leaked sidecar.
1303        assert!(!serde_json::to_string(&v)
1304            .unwrap()
1305            .contains("panic-time-secret"));
1306    }
1307
1308    #[test]
1309    fn audit_projection_yields_metadata_only() {
1310        // Acceptance criterion 12: the audit projection produces only the
1311        // metadata; the inner value never appears in audit output.
1312        let minter = CredentialMinter::new_sealed(sample_issuer());
1313        let cred: Credential<String> =
1314            minter.mint("audit-secret".to_string(), sample_metadata());
1315        let projection: &CredentialMetadata = cred.audit_projection();
1316        // The projection is metadata-equivalent...
1317        let audit_json = serde_json::to_string(projection).expect("audit serialize");
1318        // ...and does not contain the inner value.
1319        assert!(
1320            !audit_json.contains("audit-secret"),
1321            "audit projection must not include inner value, got: {audit_json}"
1322        );
1323        // It does include the metadata's `kind`.
1324        assert!(audit_json.contains("\"kind\""));
1325    }
1326
1327    #[test]
1328    fn metadata_serialization_round_trips() {
1329        // The ticket's third explicit test in the Acceptance gate: metadata
1330        // serialization round-trips.
1331        let original = sample_metadata();
1332        let json = serde_json::to_string(&original).expect("serialize");
1333        let parsed: CredentialMetadata = serde_json::from_str(&json).expect("deserialize");
1334        assert_eq!(parsed, original);
1335    }
1336
1337    #[test]
1338    fn metadata_round_trips_with_oauth_other_variant() {
1339        // Tier B Q-FLOW-2: the `Other { name }` escape valve round-trips.
1340        let mut m = sample_metadata();
1341        m.kind = CredentialKind::Other {
1342            name: CredentialKindName::new("trak.custom"),
1343        };
1344        let json = serde_json::to_string(&m).expect("serialize");
1345        let parsed: CredentialMetadata = serde_json::from_str(&json).expect("deserialize");
1346        assert_eq!(parsed, m);
1347    }
1348
1349    #[test]
1350    fn attachment_site_variants_round_trip() {
1351        // Each AttachmentSite variant serializes and deserializes cleanly.
1352        let variants = vec![
1353            AttachmentSite::Header {
1354                name: HeaderName::try_new("authorization").unwrap(),
1355            },
1356            AttachmentSite::Cookie {
1357                name: CookieName::try_new("plexus_session").unwrap(),
1358            },
1359            AttachmentSite::FirstFrame {
1360                setup_method: MethodPath::try_new("auth.connect").unwrap(),
1361                param: ParamName::new("token"),
1362            },
1363            AttachmentSite::InRpcParam {
1364                param: ParamName::new("session_token"),
1365            },
1366        ];
1367        for site in variants {
1368            let json = serde_json::to_string(&site).expect("serialize");
1369            let parsed: AttachmentSite = serde_json::from_str(&json).expect("deserialize");
1370            assert_eq!(parsed, site);
1371        }
1372    }
1373
1374    #[test]
1375    fn credential_kind_round_trips_all_variants() {
1376        // The closed enum has 8 variants; each serializes and deserializes.
1377        let variants = vec![
1378            CredentialKind::Bearer,
1379            CredentialKind::Cookie,
1380            CredentialKind::OauthAccess,
1381            CredentialKind::OauthRefresh,
1382            CredentialKind::OidcId,
1383            CredentialKind::AwsSts,
1384            CredentialKind::Macaroon,
1385            CredentialKind::Other {
1386                name: CredentialKindName::new("custom_scheme"),
1387            },
1388        ];
1389        for k in variants {
1390            let json = serde_json::to_string(&k).expect("serialize");
1391            let parsed: CredentialKind = serde_json::from_str(&json).expect("deserialize");
1392            assert_eq!(parsed, k);
1393        }
1394    }
1395
1396    #[test]
1397    fn newtypes_serialize_transparently() {
1398        // strong-typing skill: newtypes carry `#[serde(transparent)]` so they
1399        // serialize as bare strings, not as `{"0": "..."}`.
1400        let s = serde_json::to_string(&Scope::new("cone.send_message")).unwrap();
1401        assert_eq!(s, "\"cone.send_message\"");
1402        let h = serde_json::to_string(&HeaderName::try_new("authorization").unwrap()).unwrap();
1403        assert_eq!(h, "\"authorization\"");
1404    }
1405
1406    #[test]
1407    fn nested_struct_with_credential_field_serializes_sentinel() {
1408        // Demonstrates the headline behavior: a domain struct containing a
1409        // `Credential<T>` field serializes that field as a sentinel ref,
1410        // even though the rest of the struct serializes normally.
1411        #[derive(Serialize)]
1412        struct LoginEvent {
1413            user_id: String,
1414            session: Credential<String>,
1415        }
1416        let minter = CredentialMinter::new_sealed(sample_issuer());
1417        let event = LoginEvent {
1418            user_id: "alice".to_string(),
1419            session: minter.mint("jwt-bytes".to_string(), sample_metadata()),
1420        };
1421        let json = serde_json::to_value(&event).expect("serialize");
1422        let session_field = json.get("session").expect("session field");
1423        let sentinel = session_field
1424            .get("$credential")
1425            .and_then(|v| v.as_str())
1426            .expect("sentinel string");
1427        assert_eq!(sentinel, event.session.id().as_str());
1428        // The user_id is normal.
1429        assert_eq!(json.get("user_id").and_then(|v| v.as_str()), Some("alice"));
1430        // The inner JWT bytes do not appear.
1431        let s = serde_json::to_string(&event).unwrap();
1432        assert!(!s.contains("jwt-bytes"), "inner JWT must not appear: {s}");
1433    }
1434
1435    #[test]
1436    fn nested_struct_with_credential_emits_sidecar_under_guard() {
1437        // Mirrors the previous test but with the dispatch guard active —
1438        // the sidecar captures the inner value while the outer JSON still
1439        // contains only the sentinel.
1440        #[derive(Serialize)]
1441        struct LoginEvent {
1442            user_id: String,
1443            session: Credential<String>,
1444        }
1445        let minter = CredentialMinter::new_sealed(sample_issuer());
1446        let event = LoginEvent {
1447            user_id: "bob".to_string(),
1448            session: minter.mint("oauth-access".to_string(), sample_metadata()),
1449        };
1450        let (json, captured) =
1451            with_dispatch_capture(|| serde_json::to_value(&event).expect("serialize"));
1452        // Outer JSON: still sentinel.
1453        assert!(json.get("session").unwrap().get("$credential").is_some());
1454        // Sidecar: captured the value.
1455        let id = event.session.id();
1456        let entry = captured.get(id).expect("captured");
1457        assert_eq!(
1458            entry.value,
1459            serde_json::Value::String("oauth-access".into())
1460        );
1461    }
1462
1463    // -----------------------------------------------------------------
1464    // AUTHZ-CRED-CORE-1B: scoped-callback public entry point.
1465    // -----------------------------------------------------------------
1466
1467    #[test]
1468    fn run_with_credential_capture_empty_returns_no_captures() {
1469        // Acceptance criterion 2 (empty case): `f` produces no
1470        // `Credential<T>` values; the returned Vec is empty and the
1471        // closure's output is propagated.
1472        let (out, captured) = run_with_credential_capture(|| {
1473            // Serialize a plain payload that contains no credentials.
1474            let v = serde_json::to_value(serde_json::json!({"x": 1})).unwrap();
1475            v
1476        });
1477        assert_eq!(out, serde_json::json!({"x": 1}));
1478        assert!(
1479            captured.is_empty(),
1480            "no credentials emitted -> empty Vec; got {captured:?}"
1481        );
1482    }
1483
1484    #[test]
1485    fn run_with_credential_capture_populated_returns_real_captures() {
1486        // Acceptance criterion 2 (populated case): `f` calls
1487        // `Credential<T>::serialize` while the guard is installed; the
1488        // returned Vec contains the captured credentials with their ids,
1489        // values, and metadata. The outer serialization still produces
1490        // sentinels — the value lives only in the sidecar.
1491        let minter = CredentialMinter::new_sealed(sample_issuer());
1492        let cred: Credential<String> =
1493            minter.mint("populated-secret".to_string(), sample_metadata());
1494        let cred_id = cred.id().clone();
1495
1496        let (json_value, captured) =
1497            run_with_credential_capture(|| serde_json::to_value(&cred).expect("serialize"));
1498
1499        // Outer JSON: sentinel-only.
1500        let obj = json_value.as_object().expect("object");
1501        assert_eq!(obj.len(), 1);
1502        assert_eq!(
1503            obj.get("$credential").and_then(|v| v.as_str()),
1504            Some(cred_id.as_str())
1505        );
1506
1507        // Sidecar Vec: one entry, value+metadata+id present.
1508        assert_eq!(captured.len(), 1);
1509        let entry = &captured[0];
1510        assert_eq!(entry.id, cred_id);
1511        assert_eq!(
1512            entry.value,
1513            serde_json::Value::String("populated-secret".into())
1514        );
1515        assert_eq!(entry.metadata.kind, CredentialKind::Bearer);
1516    }
1517
1518    #[test]
1519    fn run_with_credential_capture_nested_sidecars_do_not_interleave() {
1520        // Ticket §Risks #1: nested invocations install fresh inner
1521        // sidecars; inner captures drain to the inner caller; the outer
1522        // continues with its own (still-pending) sidecar after the inner
1523        // returns. The two sidecars never interleave.
1524        let minter = CredentialMinter::new_sealed(sample_issuer());
1525        let outer_cred: Credential<String> =
1526            minter.mint("outer-secret".to_string(), sample_metadata());
1527        let inner_cred: Credential<String> =
1528            minter.mint("inner-secret".to_string(), sample_metadata());
1529        let outer_id = outer_cred.id().clone();
1530        let inner_id = inner_cred.id().clone();
1531
1532        let (outer_result, outer_captured) = run_with_credential_capture(|| {
1533            // Serialize outer credential under the outer guard.
1534            let _outer_json = serde_json::to_value(&outer_cred).expect("outer serialize");
1535
1536            // Now nest a fresh scope; the inner credential should be
1537            // captured ONLY by the inner guard.
1538            let (inner_json, inner_captured) =
1539                run_with_credential_capture(|| serde_json::to_value(&inner_cred).expect("inner"));
1540            assert_eq!(inner_captured.len(), 1, "inner scope captures inner only");
1541            assert_eq!(inner_captured[0].id, inner_id);
1542            assert_eq!(
1543                inner_captured[0].value,
1544                serde_json::Value::String("inner-secret".into())
1545            );
1546
1547            // After the inner scope returns, outer captures must still
1548            // include only the outer credential (the inner sidecar drained
1549            // to its caller; the outer sidecar — which is now active again
1550            // — still holds outer's capture).
1551            (_outer_json, inner_json)
1552        });
1553
1554        // Outer sidecar: outer credential only (the inner drained
1555        // separately).
1556        assert_eq!(
1557            outer_captured.len(),
1558            1,
1559            "outer scope contains outer only; got {outer_captured:?}"
1560        );
1561        assert_eq!(outer_captured[0].id, outer_id);
1562        assert_eq!(
1563            outer_captured[0].value,
1564            serde_json::Value::String("outer-secret".into())
1565        );
1566
1567        // The closure returned both serialized values.
1568        let (outer_json, inner_json) = outer_result;
1569        assert_eq!(
1570            outer_json.get("$credential").and_then(|v| v.as_str()),
1571            Some(outer_id.as_str())
1572        );
1573        assert_eq!(
1574            inner_json.get("$credential").and_then(|v| v.as_str()),
1575            Some(inner_id.as_str())
1576        );
1577    }
1578
1579    #[test]
1580    fn run_with_credential_capture_resets_on_panic() {
1581        // Ticket §"Required behavior": if `f` panics, the guard's `Drop`
1582        // releases the toggle on unwind; subsequent reentrant calls see
1583        // a clean state.
1584        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1585            run_with_credential_capture(|| {
1586                // Active sidecar.
1587                DISPATCH_SIDECAR.with(|cell| assert!(cell.borrow().is_some()));
1588                panic!("simulated panic inside run_with_credential_capture");
1589            });
1590        }));
1591
1592        // After the panic, the thread-local must be clean.
1593        DISPATCH_SIDECAR.with(|cell| {
1594            assert!(
1595                cell.borrow().is_none(),
1596                "sidecar must be cleared on panic"
1597            );
1598        });
1599
1600        // And a subsequent call works cleanly.
1601        let (out, captured) = run_with_credential_capture(|| 7_u32);
1602        assert_eq!(out, 7);
1603        assert!(captured.is_empty());
1604    }
1605
1606    #[test]
1607    fn run_with_credential_capture_isolated_per_thread() {
1608        // Ticket §Risks #3: the existing guard uses a thread-local;
1609        // multi-threaded dispatch must isolate per-task captures. Two
1610        // threads each running their own `run_with_credential_capture`
1611        // see only their own credentials.
1612        use std::sync::Arc;
1613        use std::thread;
1614
1615        let minter = Arc::new(CredentialMinter::new_sealed(sample_issuer()));
1616        let m1 = minter.clone();
1617        let m2 = minter.clone();
1618
1619        let h1 = thread::spawn(move || {
1620            let cred: Credential<String> =
1621                m1.mint("thread-1-secret".to_string(), sample_metadata());
1622            let id = cred.id().clone();
1623            let (_v, captured) =
1624                run_with_credential_capture(|| serde_json::to_value(&cred).unwrap());
1625            (id, captured)
1626        });
1627        let h2 = thread::spawn(move || {
1628            let cred: Credential<String> =
1629                m2.mint("thread-2-secret".to_string(), sample_metadata());
1630            let id = cred.id().clone();
1631            let (_v, captured) =
1632                run_with_credential_capture(|| serde_json::to_value(&cred).unwrap());
1633            (id, captured)
1634        });
1635
1636        let (id1, c1) = h1.join().unwrap();
1637        let (id2, c2) = h2.join().unwrap();
1638
1639        assert_eq!(c1.len(), 1, "thread 1 captures only its own credential");
1640        assert_eq!(c1[0].id, id1);
1641        assert_eq!(c1[0].value, serde_json::Value::String("thread-1-secret".into()));
1642
1643        assert_eq!(c2.len(), 1, "thread 2 captures only its own credential");
1644        assert_eq!(c2[0].id, id2);
1645        assert_eq!(c2[0].value, serde_json::Value::String("thread-2-secret".into()));
1646
1647        assert_ne!(id1, id2);
1648    }
1649
1650    #[test]
1651    fn multiple_credentials_get_distinct_ids() {
1652        // OAuth-style multi-credential return: each Credential<T> in the
1653        // event gets its own id and own sidecar entry under the guard.
1654        #[derive(Serialize)]
1655        struct TokenSet {
1656            access: Credential<String>,
1657            refresh: Credential<String>,
1658        }
1659        let minter = CredentialMinter::new_sealed(sample_issuer());
1660        let mut m_refresh = sample_metadata();
1661        m_refresh.kind = CredentialKind::OauthRefresh;
1662        let event = TokenSet {
1663            access: minter.mint("access-tok".to_string(), sample_metadata()),
1664            refresh: minter.mint("refresh-tok".to_string(), m_refresh),
1665        };
1666        assert_ne!(event.access.id(), event.refresh.id());
1667        let (_json, captured) =
1668            with_dispatch_capture(|| serde_json::to_value(&event).expect("serialize"));
1669        assert_eq!(captured.len(), 2);
1670        assert!(captured.contains_key(event.access.id()));
1671        assert!(captured.contains_key(event.refresh.id()));
1672    }
1673
1674    #[test]
1675    fn credential_field_marker_constructs_via_new_and_struct_literal() {
1676        // Acceptance criteria 2 + 3 (this ticket): the canonical
1677        // `CredentialFieldMarker` is constructible from outside crate code
1678        // via both struct-literal (because fields are `pub`) and `new`.
1679        let m1 = CredentialFieldMarker::new(
1680            None,
1681            "session",
1682            CredentialKind::Bearer,
1683            AttachmentSite::Header {
1684                name: HeaderName::try_new("authorization").unwrap(),
1685            },
1686            Some(CredentialScheme::new("Bearer ")),
1687            vec![Scope::new("cone.send_message")],
1688            Some(MethodPath::try_new("auth.refresh").unwrap()),
1689            Some(MethodPath::try_new("auth.logout").unwrap()),
1690        );
1691        assert_eq!(m1.field, "session");
1692        assert!(m1.variant.is_none());
1693        assert!(matches!(m1.kind, CredentialKind::Bearer));
1694        assert!(matches!(m1.attach_as, AttachmentSite::Header { .. }));
1695        assert_eq!(m1.scheme.as_ref().map(|s| s.as_str()), Some("Bearer "));
1696        assert_eq!(m1.scopes.len(), 1);
1697
1698        // Struct-literal construction also works (this is the form the
1699        // macro emits).
1700        let m2 = CredentialFieldMarker {
1701            variant: Some("Issued"),
1702            field: "session",
1703            kind: CredentialKind::Bearer,
1704            attach_as: AttachmentSite::Header {
1705                name: HeaderName::try_new("authorization").unwrap(),
1706            },
1707            scheme: None,
1708            scopes: vec![],
1709            refresh_via: None,
1710            revoke_via: None,
1711        };
1712        assert_eq!(m2.variant, Some("Issued"));
1713        assert_eq!(m2.field, "session");
1714    }
1715
1716    #[test]
1717    fn credential_field_marker_composes_metadata() {
1718        // The marker carries the static metadata; `to_metadata` composes
1719        // a full `CredentialMetadata` with the runtime-supplied pieces.
1720        let marker = CredentialFieldMarker::new(
1721            None,
1722            "session",
1723            CredentialKind::Bearer,
1724            AttachmentSite::Header {
1725                name: HeaderName::try_new("authorization").unwrap(),
1726            },
1727            Some(CredentialScheme::new("Bearer ")),
1728            vec![Scope::new("cone.send_message")],
1729            None,
1730            None,
1731        );
1732        let issuer = CredentialIssuer::new(
1733            Origin::new("ws://localhost:4444"),
1734            MethodPath::try_new("auth.login").unwrap(),
1735        );
1736        let metadata = marker.to_metadata(None, issuer.clone());
1737        assert_eq!(metadata.kind, CredentialKind::Bearer);
1738        assert_eq!(metadata.issuer, issuer);
1739        assert!(metadata.sensitive, "always true per CredentialMetadata::new");
1740    }
1741
1742    // -----------------------------------------------------------------------
1743    // CredentialsRegistry — autoref-specialized fallback tests
1744    // (AUTHZ-CRED-MACRO-3).
1745    // -----------------------------------------------------------------------
1746
1747    /// Types that do NOT implement [`HasCredentialMarkers`] fall through to
1748    /// the [`CredentialsRegistryFallback`] blanket impl, which returns an
1749    /// empty slice. This is the "plain return type" path at the
1750    /// `#[plexus_macros::method]` call site.
1751    #[test]
1752    fn credentials_registry_fallback_returns_empty_slice() {
1753        // Bring the fallback trait into scope so its `marker_slice`
1754        // is callable via autoref — this mirrors what the macro emits.
1755        use super::CredentialsRegistryFallback as _;
1756
1757        struct PlainType;
1758        let probe = CredentialsRegistryProbe::<PlainType>::new();
1759        // Autoref: `&probe` resolves to the fallback impl on
1760        // `&CredentialsRegistryProbe<T>`.
1761        let markers: &'static [CredentialFieldMarker] = (&probe).marker_slice();
1762        assert!(markers.is_empty(), "plain type yields empty marker slice");
1763    }
1764
1765    /// The probe is constructible for arbitrary types, including types that
1766    /// are not `Sized` and types that come from other crates. Smoke-checks
1767    /// `CredentialsRegistryProbe::new()` is `const`.
1768    #[test]
1769    fn credentials_registry_probe_constructible_for_arbitrary_types() {
1770        let _: CredentialsRegistryProbe<String> = CredentialsRegistryProbe::new();
1771        let _: CredentialsRegistryProbe<Vec<u8>> = CredentialsRegistryProbe::new();
1772        // `const` smoke-check.
1773        const _: CredentialsRegistryProbe<()> = CredentialsRegistryProbe::new();
1774    }
1775
1776    /// Types that implement [`HasCredentialMarkers`] hit the specialized
1777    /// inherent `marker_slice` on `CredentialsRegistryProbe<T>` — the
1778    /// "wired return type" path at the `#[plexus_macros::method]` call site.
1779    /// Demonstrates the autoref-specialization win.
1780    #[test]
1781    fn credentials_registry_specialized_path_returns_populated_slice() {
1782        use super::CredentialsRegistryFallback as _;
1783
1784        struct WiredType;
1785
1786        // Lazy static slice, mirroring what the derive macro will emit via
1787        // `OnceLock::get_or_init(|| credential_markers_for_<Type>())`.
1788        impl HasCredentialMarkers for WiredType {
1789            fn credential_markers() -> &'static [CredentialFieldMarker] {
1790                use std::sync::OnceLock;
1791                static M: OnceLock<Vec<CredentialFieldMarker>> = OnceLock::new();
1792                M.get_or_init(|| {
1793                    vec![CredentialFieldMarker::new(
1794                        None,
1795                        "session",
1796                        CredentialKind::Bearer,
1797                        AttachmentSite::Header {
1798                            name: HeaderName::try_new("authorization").unwrap(),
1799                        },
1800                        Some(CredentialScheme::new("Bearer ")),
1801                        vec![],
1802                        None,
1803                        None,
1804                    )]
1805                })
1806                .as_slice()
1807            }
1808        }
1809
1810        let probe = CredentialsRegistryProbe::<WiredType>::new();
1811
1812        // Direct call on the probe (no autoref): the inherent method gated
1813        // on `T: HasCredentialMarkers` resolves first.
1814        let m = probe.marker_slice();
1815        assert_eq!(m.len(), 1);
1816        assert_eq!(m[0].field, "session");
1817        assert!(matches!(m[0].kind, CredentialKind::Bearer));
1818
1819        // Same call with leading `&`: autoref-resolution still prefers the
1820        // inherent (gated) method over the `&CredentialsRegistryProbe<T>`
1821        // fallback impl. This is the actual call shape used by the macro.
1822        let m2 = (&probe).marker_slice();
1823        assert_eq!(
1824            m2.len(),
1825            1,
1826            "inherent specialized path wins over blanket fallback via autoref"
1827        );
1828        assert_eq!(m2[0].field, "session");
1829    }
1830
1831    /// Sanity-check the deprecated alias `CredentialsRegistry` still works
1832    /// for back-compat with any in-flight call sites that used the original
1833    /// name.
1834    #[test]
1835    #[allow(deprecated)]
1836    fn credentials_registry_deprecated_alias_compiles() {
1837        struct PlainType;
1838        let probe = CredentialsRegistryProbe::<PlainType>::new();
1839        // Bring the deprecated alias into scope. The supertrait relationship
1840        // (alias: Fallback) means autoref still finds the empty-slice path.
1841        use super::CredentialsRegistry as _;
1842        let markers = (&probe).marker_slice();
1843        assert!(markers.is_empty());
1844    }
1845}