Skip to main content

plexus_auth_core/identity/
authenticator.rs

1//! The [`Authenticator`] seam: credential material in, verified
2//! [`Principal`] out.
3//!
4//! # Why a trait
5//!
6//! Before this module, "is this caller who they say they are" was answered by
7//! whatever [`SessionValidator`](crate::SessionValidator) a backend happened
8//! to install, and each validator hard-wired its own credential handling —
9//! plexus-idp's, for example, parsed a cookie, tried an RS256 JWT, then fell
10//! back to an API-key lookup, all inside one `validate` method. There was no
11//! place to *add* a credential kind, only a place to edit one.
12//!
13//! An `Authenticator` is one credential kind's verifier. A backend composes
14//! several into an [`AuthenticatorChain`], which is itself a
15//! `SessionValidator` — so the new seam plugs into the existing perimeter
16//! without any transport change.
17//!
18//! # The shape that keeps NIP-42 out of the trait
19//!
20//! Three facts make a self-sovereign, challenge-response credential
21//! expressible without touching [`Authenticator`]:
22//!
23//! 1. [`Presentation`] carries a
24//!    [`SignedChallenge`](Presentation::SignedChallenge) variant. A NIP-42
25//!    authenticator reads `scheme == "nip42"`, `key_id` (the hex pubkey),
26//!    `challenge` (the relay-issued nonce), and `signature` — no new variant
27//!    needed, and `#[non_exhaustive]` means adding one later is not breaking
28//!    anyway.
29//! 2. [`Principal`] already namespaces `nostr:<64-hex>`, so the *output* type
30//!    needs no widening.
31//! 3. [`Authenticator::accepts`] lets each impl claim only its own material,
32//!    so a chain can hold verifiers with completely unrelated proof models.
33//!
34//! # What is proof and what is data
35//!
36//! A [`Principal`] is a *name* — anyone can parse one out of a string.
37//! [`Authenticated`] is the *proof*: its only constructor is
38//! [`Authenticated::new`], and by convention the sole callers are
39//! `Authenticator` impls that have verified the material they were handed.
40//! Downstream code should take `Authenticated`, not `Principal`, when it
41//! wants to know that a check happened.
42
43use std::sync::Arc;
44
45use async_trait::async_trait;
46use serde_json::{Map, Value};
47
48use super::linking::{CredentialClass, CredentialLink};
49use super::principal::{Issuer, Principal};
50use crate::auth::{AuthContext, SessionValidator, PRINCIPAL_CLAIM};
51
52/// Credential material as a transport presented it.
53///
54/// The variants describe *carriers and proof shapes*, not products: `Bearer`
55/// is "an opaque token in the `Authorization` header", not "a JWT". Which
56/// [`Authenticator`] handles a given presentation is decided by
57/// [`Authenticator::accepts`], never by the variant alone — an API key and a
58/// JWT both arrive as `Bearer` in practice, and both authenticators get a
59/// look.
60#[derive(Debug, Clone, PartialEq, Eq)]
61#[non_exhaustive]
62pub enum Presentation {
63    /// A bearer token, as extracted from `Authorization: Bearer <token>`.
64    Bearer {
65        /// The raw token, already stripped of the `Bearer ` prefix.
66        token: String,
67    },
68
69    /// An API key presented in a dedicated header or query parameter.
70    ApiKey {
71        /// The raw key, exactly as presented (never the digest — the
72        /// authenticator owns the digest function).
73        key: String,
74    },
75
76    /// A raw `Cookie:` header value, with all its pairs intact.
77    Cookie {
78        /// The unparsed header value, e.g. `"a=1; access_token=eyJ…"`.
79        header: String,
80    },
81
82    /// A signed challenge-response: the caller proved possession of a key by
83    /// signing a server-issued nonce.
84    ///
85    /// This is the variant that makes NIP-42, WebAuthn, and mTLS-style proofs
86    /// expressible without changing [`Authenticator`]. The fields are
87    /// deliberately scheme-agnostic strings; the authenticator that claims a
88    /// `scheme` owns their interpretation.
89    SignedChallenge {
90        /// Names the proof scheme, e.g. `"nip42"`. An authenticator matches
91        /// on this in [`Authenticator::accepts`].
92        scheme: String,
93        /// The public identifier of the signing key (for nostr, the 64-hex
94        /// x-only pubkey — which is also the `nostr:` principal subject).
95        key_id: String,
96        /// The server-issued nonce that was signed.
97        challenge: String,
98        /// The signature over `challenge`, in the scheme's own encoding.
99        signature: String,
100    },
101}
102
103impl Presentation {
104    /// A short, non-secret label for logs and audit records.
105    ///
106    /// Never includes the material itself — a `Debug` of a `Presentation`
107    /// does, so prefer this in anything that is written down.
108    pub fn kind_label(&self) -> &str {
109        match self {
110            Self::Bearer { .. } => "bearer",
111            Self::ApiKey { .. } => "apikey",
112            Self::Cookie { .. } => "cookie",
113            Self::SignedChallenge { scheme, .. } => scheme,
114        }
115    }
116}
117
118/// Why an [`Authenticator`] refused to vouch for a [`Presentation`].
119///
120/// The distinction that matters most for a chain is
121/// [`Unsupported`](AuthnRejection::Unsupported) versus everything else:
122/// `Unsupported` means "not my credential kind, ask the next one", while every
123/// other variant means "this *was* mine and it failed". A chain that treated
124/// them alike would let a revoked API key fall through to a validator that
125/// happened to accept it.
126#[derive(Debug, Clone, PartialEq, Eq)]
127#[non_exhaustive]
128pub enum AuthnRejection {
129    /// This authenticator does not handle this credential kind. Advisory —
130    /// a chain moves on.
131    Unsupported {
132        /// The authenticator that declined.
133        authenticator: String,
134        /// The presentation's [`kind_label`](Presentation::kind_label).
135        presented: String,
136    },
137
138    /// The material was structurally wrong: unparseable token, missing
139    /// cookie, subject that does not fit the issuer's grammar.
140    Malformed(String),
141
142    /// The material was well-formed and genuine but past its validity window.
143    Expired,
144
145    /// A signature or MAC did not verify. Distinct from `Malformed` so audit
146    /// can separate "garbage" from "forgery attempt".
147    SignatureInvalid,
148
149    /// Well-formed material naming something the store has never seen.
150    UnknownCredential,
151
152    /// Known material that has been explicitly withdrawn.
153    Revoked,
154
155    /// The authenticator could not reach the store, key set, or issuer it
156    /// needed. **Not** an authentication failure — callers should surface
157    /// this as a 5xx, not a 401.
158    Backend(String),
159}
160
161impl std::fmt::Display for AuthnRejection {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        match self {
164            Self::Unsupported {
165                authenticator,
166                presented,
167            } => write!(
168                f,
169                "authenticator `{authenticator}` does not handle `{presented}` material"
170            ),
171            Self::Malformed(why) => write!(f, "malformed credential: {why}"),
172            Self::Expired => f.write_str("credential expired"),
173            Self::SignatureInvalid => f.write_str("credential signature did not verify"),
174            Self::UnknownCredential => f.write_str("unknown credential"),
175            Self::Revoked => f.write_str("credential revoked"),
176            Self::Backend(why) => write!(f, "authenticator backend error: {why}"),
177        }
178    }
179}
180
181impl std::error::Error for AuthnRejection {}
182
183impl AuthnRejection {
184    /// Build an [`Unsupported`](AuthnRejection::Unsupported) rejection.
185    pub fn unsupported(authenticator: impl Into<String>, presented: &Presentation) -> Self {
186        Self::Unsupported {
187            authenticator: authenticator.into(),
188            presented: presented.kind_label().to_string(),
189        }
190    }
191
192    /// Is this "wrong credential kind, try the next authenticator"?
193    pub fn is_unsupported(&self) -> bool {
194        matches!(self, Self::Unsupported { .. })
195    }
196
197    /// Is this an infrastructure failure rather than a rejected caller?
198    pub fn is_backend_failure(&self) -> bool {
199        matches!(self, Self::Backend(_))
200    }
201}
202
203/// Proof that some [`Authenticator`] verified credential material, together
204/// with what it learned.
205///
206/// The claims bag carries the tenant *hint* (`org_id`) among other things.
207/// It is a hint and not an authorization: tenancy enforcement still routes
208/// through [`TenantResolver`](crate::TenantResolver) and
209/// [`TenantGate`](crate::TenantGate), and this build does not change that
210/// (orgs/membership are M4).
211#[derive(Debug, Clone)]
212pub struct Authenticated {
213    principal: Principal,
214    session_id: String,
215    roles: Vec<String>,
216    claims: Value,
217}
218
219impl Authenticated {
220    /// Record a successful authentication.
221    ///
222    /// Called by [`Authenticator`] impls **after** verifying material. The
223    /// constructor is public because authenticators live in other crates
224    /// (plexus-idp's does), so this type is a convention-backed proof rather
225    /// than a crate-sealed one like [`VerifiedUser`](crate::VerifiedUser).
226    /// The strong seal is deliberately deferred: making it crate-private here
227    /// would make the trait unimplementable outside `plexus-auth-core`, which
228    /// is exactly the pluggability this build exists to add.
229    pub fn new(
230        principal: Principal,
231        session_id: impl Into<String>,
232        roles: Vec<String>,
233        claims: Value,
234    ) -> Self {
235        Self {
236            principal,
237            session_id: session_id.into(),
238            roles,
239            claims,
240        }
241    }
242
243    /// The verified subject.
244    pub fn principal(&self) -> &Principal {
245        &self.principal
246    }
247
248    /// The session identifier, empty for stateless credentials (JWTs, API
249    /// keys) exactly as today's validators leave it.
250    pub fn session_id(&self) -> &str {
251        &self.session_id
252    }
253
254    /// Roles asserted by the credential.
255    pub fn roles(&self) -> &[String] {
256        &self.roles
257    }
258
259    /// Additional verified claims (`org_id`, `username`, …).
260    pub fn claims(&self) -> &Value {
261        &self.claims
262    }
263
264    /// Project this proof into the runtime [`AuthContext`].
265    ///
266    /// This is the one place the two identity representations are tied
267    /// together, and it is why they cannot diverge:
268    ///
269    /// - `user_id` is [`Principal::as_legacy_user_id`] — for an idp
270    ///   principal that is the bare UUID, byte-identical to what plexus-idp
271    ///   writes today.
272    /// - the full namespaced principal is stamped into
273    ///   `metadata["principal"]`.
274    ///
275    /// [`AuthContext::principal`] reads the stamp back, and falls back to
276    /// re-deriving it from `user_id` when the stamp is absent (a context
277    /// built by an older code path). Both routes yield the same value for an
278    /// idp principal — see the `principal_and_user_id_agree_*` tests.
279    pub fn into_auth_context(self) -> AuthContext {
280        let Self {
281            principal,
282            session_id,
283            roles,
284            claims,
285        } = self;
286
287        let mut metadata: Map<String, Value> = match claims {
288            Value::Object(m) => m,
289            Value::Null => Map::new(),
290            // A non-object claims payload is preserved rather than dropped:
291            // discarding verified claims silently would be worse than an
292            // odd-shaped metadata bag.
293            other => {
294                let mut m = Map::new();
295                m.insert("claims".to_string(), other);
296                m
297            }
298        };
299        metadata.insert(
300            PRINCIPAL_CLAIM.to_string(),
301            Value::String(principal.to_string()),
302        );
303
304        AuthContext::new(
305            principal.as_legacy_user_id(),
306            session_id,
307            roles,
308            Value::Object(metadata),
309        )
310    }
311}
312
313/// One credential kind's verifier.
314///
315/// Implementations live wherever the verification material does — plexus-idp
316/// implements one over its own signing keys, a nostr gateway would implement
317/// one over secp256k1 — and are composed by an [`AuthenticatorChain`].
318///
319/// # Contract
320///
321/// - `accepts` must be cheap and side-effect free. It is a routing hint; a
322///   `true` from it does not oblige `authenticate` to succeed.
323/// - `authenticate` must return
324///   [`Unsupported`](AuthnRejection::Unsupported) if and only if `accepts`
325///   would have returned `false`. Any other error means the material was
326///   this authenticator's and was rejected.
327/// - `authenticate` must not return [`Authenticated`] without having
328///   verified the material — that is the whole contract of the type.
329#[async_trait]
330pub trait Authenticator: Send + Sync + 'static {
331    /// A stable, non-secret name for logs, audit records, and capability
332    /// advertisement.
333    fn name(&self) -> &str;
334
335    /// Does this authenticator handle this presentation?
336    fn accepts(&self, presentation: &Presentation) -> bool;
337
338    /// Verify the material and name the subject it proves.
339    async fn authenticate(
340        &self,
341        presentation: &Presentation,
342    ) -> Result<Authenticated, AuthnRejection>;
343}
344
345/// An ordered set of [`Authenticator`]s tried in turn.
346///
347/// The chain is what makes "idp is one authenticator among several"
348/// structural rather than aspirational: plexus-idp registers its bearer,
349/// cookie, and API-key authenticators into a chain, and a nostr gateway would
350/// push one more in without any of them knowing about each other.
351///
352/// # Ordering and short-circuiting
353///
354/// Authenticators are tried in insertion order. The first one whose
355/// `authenticate` returns anything other than
356/// [`Unsupported`](AuthnRejection::Unsupported) decides the outcome —
357/// success *or* failure. A malformed JWT therefore does not fall through to
358/// the API-key authenticator hoping it will be luckier.
359#[derive(Clone, Default)]
360pub struct AuthenticatorChain {
361    authenticators: Vec<Arc<dyn Authenticator>>,
362}
363
364impl std::fmt::Debug for AuthenticatorChain {
365    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
366        f.debug_struct("AuthenticatorChain")
367            .field("authenticators", &self.names())
368            .finish()
369    }
370}
371
372impl AuthenticatorChain {
373    /// An empty chain, which rejects everything.
374    pub fn new() -> Self {
375        Self::default()
376    }
377
378    /// Append an authenticator.
379    pub fn with(mut self, authenticator: Arc<dyn Authenticator>) -> Self {
380        self.authenticators.push(authenticator);
381        self
382    }
383
384    /// Append an authenticator, refusing one whose name the chain already
385    /// holds (IDENTITY-27): two providers of one name would mint one
386    /// namespace. The error is the repeated name.
387    pub fn try_with(self, authenticator: Arc<dyn Authenticator>) -> Result<Self, String> {
388        if self.names().contains(&authenticator.name()) {
389            return Err(authenticator.name().to_string());
390        }
391        Ok(self.with(authenticator))
392    }
393
394    /// The names of the registered authenticators, in order.
395    pub fn names(&self) -> Vec<&str> {
396        self.authenticators.iter().map(|a| a.name()).collect()
397    }
398
399    /// Is the chain empty?
400    pub fn is_empty(&self) -> bool {
401        self.authenticators.is_empty()
402    }
403
404    /// Try each authenticator in order.
405    ///
406    /// Returns the first non-`Unsupported` outcome. If every authenticator
407    /// declines, the last `Unsupported` is returned (or a synthetic one for
408    /// an empty chain), so the caller can tell "nobody handles this" from
409    /// "somebody handled it and said no".
410    pub async fn authenticate(
411        &self,
412        presentation: &Presentation,
413    ) -> Result<Authenticated, AuthnRejection> {
414        let mut last = AuthnRejection::unsupported("<empty chain>", presentation);
415        for authenticator in &self.authenticators {
416            if !authenticator.accepts(presentation) {
417                continue;
418            }
419            match authenticator.authenticate(presentation).await {
420                Ok(ok) => return Ok(ok),
421                Err(e) if e.is_unsupported() => last = e,
422                Err(e) => return Err(e),
423            }
424        }
425        Err(last)
426    }
427}
428
429/// Adapts a chain to the existing perimeter.
430///
431/// The cookie header a `SessionValidator` receives is offered to the chain as
432/// a [`Presentation::Cookie`]; if no authenticator claims it, it is retried as
433/// a [`Presentation::Bearer`], because plexus-idp's validator has always
434/// accepted a bare token in the cookie position and callers depend on that.
435#[async_trait]
436impl SessionValidator for AuthenticatorChain {
437    async fn validate(&self, cookie_value: &str) -> Option<AuthContext> {
438        let as_cookie = Presentation::Cookie {
439            header: cookie_value.to_string(),
440        };
441        match self.authenticate(&as_cookie).await {
442            Ok(ok) => return Some(ok.into_auth_context()),
443            Err(e) if !e.is_unsupported() => return None,
444            Err(_) => {}
445        }
446
447        let as_bearer = Presentation::Bearer {
448            token: cookie_value.trim().to_string(),
449        };
450        self.authenticate(&as_bearer)
451            .await
452            .ok()
453            .map(Authenticated::into_auth_context)
454    }
455}
456
457// ── Reference authenticators ───────────────────────────────────────────
458
459/// Verified content of a bearer token, as a token verifier reports it.
460///
461/// Deliberately smaller than a JWT claim set: an [`Authenticator`] needs the
462/// subject, the roles, and a claims bag, and nothing about this shape assumes
463/// JWT — a verifier backed by token introspection reports the same thing.
464#[derive(Debug, Clone)]
465pub struct VerifiedClaims {
466    /// The token's subject, as the issuer wrote it.
467    pub subject: String,
468    /// Roles asserted by the token, if any.
469    pub roles: Vec<String>,
470    /// Remaining verified claims (`org_id`, `username`, …).
471    pub claims: Value,
472}
473
474/// Verifies a bearer token's signature and time window.
475///
476/// This is the seam that lets [`BearerJwtAuthenticator`] live here while the
477/// actual key material lives elsewhere: plexus-idp implements this over its
478/// own `KeyStore` and `iss`/`aud` checks, so the bearer authenticator
479/// "delegates to today's idp validation" rather than reimplementing it.
480#[async_trait]
481pub trait TokenVerifier: Send + Sync + 'static {
482    /// The issuer whose principals this verifier mints. Fixes the namespace
483    /// of the resulting [`Principal`], so a verifier cannot accidentally
484    /// vouch for a subject in someone else's namespace.
485    fn issuer(&self) -> Issuer;
486
487    /// Verify signature, `iss`/`aud`, and expiry.
488    async fn verify(&self, token: &str) -> Result<VerifiedClaims, AuthnRejection>;
489}
490
491/// Bearer-token authenticator over an injected [`TokenVerifier`].
492pub struct BearerJwtAuthenticator<V: TokenVerifier> {
493    name: String,
494    verifier: V,
495}
496
497impl<V: TokenVerifier> BearerJwtAuthenticator<V> {
498    /// Wrap a verifier. `name` appears in logs and audit records.
499    pub fn new(name: impl Into<String>, verifier: V) -> Self {
500        Self {
501            name: name.into(),
502            verifier,
503        }
504    }
505}
506
507#[async_trait]
508impl<V: TokenVerifier> Authenticator for BearerJwtAuthenticator<V> {
509    fn name(&self) -> &str {
510        &self.name
511    }
512
513    fn accepts(&self, presentation: &Presentation) -> bool {
514        matches!(presentation, Presentation::Bearer { .. })
515    }
516
517    async fn authenticate(
518        &self,
519        presentation: &Presentation,
520    ) -> Result<Authenticated, AuthnRejection> {
521        let Presentation::Bearer { token } = presentation else {
522            return Err(AuthnRejection::unsupported(&self.name, presentation));
523        };
524
525        let verified = self.verifier.verify(token).await?;
526        // The verifier reports a raw subject; the issuer's grammar decides
527        // whether it is nameable. A token that verified but whose `sub` is
528        // not a legal subject for this issuer is malformed, not authentic.
529        let principal = Principal::new(self.verifier.issuer(), verified.subject.clone())
530            .map_err(|e| AuthnRejection::Malformed(e.to_string()))?;
531
532        Ok(Authenticated::new(
533            principal,
534            String::new(),
535            verified.roles,
536            verified.claims,
537        ))
538    }
539}
540
541/// Digests a raw API key into the locator its
542/// [`CredentialLink`] store is keyed by.
543///
544/// Injected rather than fixed so `plexus-auth-core` need not take a hash
545/// dependency, and so a deployment can change digest without changing this
546/// crate. plexus-idp passes its existing SHA-256 hex function, which is why
547/// the authenticator resolves keys that were stored before this build.
548pub type ApiKeyDigest = Arc<dyn Fn(&str) -> String + Send + Sync>;
549
550/// API-key authenticator backed by a [`CredentialLink`] store.
551///
552/// Resolution is *lookup*, never minting: a key that is not linked to a
553/// principal is [`UnknownCredential`](AuthnRejection::UnknownCredential).
554/// That is what makes an API key a credential *of* a principal rather than a
555/// second identity for the same human.
556pub struct ApiKeyAuthenticator {
557    name: String,
558    links: Arc<dyn CredentialLink>,
559    digest: ApiKeyDigest,
560}
561
562impl ApiKeyAuthenticator {
563    /// Build an authenticator that looks keys up, after digesting them, in
564    /// `links`.
565    pub fn new(name: impl Into<String>, links: Arc<dyn CredentialLink>, digest: ApiKeyDigest) -> Self {
566        Self {
567            name: name.into(),
568            links,
569            digest,
570        }
571    }
572
573    /// Convenience for stores that key on the raw value (tests, and
574    /// deployments that hash before calling).
575    pub fn plaintext(name: impl Into<String>, links: Arc<dyn CredentialLink>) -> Self {
576        Self::new(name, links, Arc::new(|k: &str| k.to_string()))
577    }
578}
579
580#[async_trait]
581impl Authenticator for ApiKeyAuthenticator {
582    fn name(&self) -> &str {
583        &self.name
584    }
585
586    fn accepts(&self, presentation: &Presentation) -> bool {
587        // API keys are commonly presented in the bearer position, so both
588        // carriers are accepted. The store lookup is what decides.
589        matches!(
590            presentation,
591            Presentation::ApiKey { .. } | Presentation::Bearer { .. }
592        )
593    }
594
595    async fn authenticate(
596        &self,
597        presentation: &Presentation,
598    ) -> Result<Authenticated, AuthnRejection> {
599        let raw = match presentation {
600            Presentation::ApiKey { key } => key,
601            Presentation::Bearer { token } => token,
602            _ => return Err(AuthnRejection::unsupported(&self.name, presentation)),
603        };
604        if raw.is_empty() {
605            return Err(AuthnRejection::Malformed("empty api key".into()));
606        }
607
608        let locator = (self.digest)(raw);
609        let link = self
610            .links
611            .resolve(CredentialClass::ApiKey, &locator)
612            .await
613            .map_err(|e| AuthnRejection::Backend(e.to_string()))?
614            .ok_or(AuthnRejection::UnknownCredential)?;
615
616        if link.is_revoked() {
617            return Err(AuthnRejection::Revoked);
618        }
619        if link.is_expired_at(chrono::Utc::now()) {
620            return Err(AuthnRejection::Expired);
621        }
622
623        Ok(Authenticated::new(
624            link.principal().clone(),
625            String::new(),
626            link.roles().to_vec(),
627            link.claims().clone(),
628        ))
629    }
630}
631
632/// Unwraps a cookie header and re-presents its token to an inner
633/// authenticator.
634///
635/// A cookie is a *carrier*, not a credential kind — the thing inside it is a
636/// bearer token or an API key. Modelling it as a decorator rather than a
637/// fourth verification algorithm keeps exactly one implementation of each
638/// actual proof, which is why this type contains no verification logic at
639/// all.
640pub struct CookieAuthenticator {
641    name: String,
642    cookie_name: String,
643    inner: Arc<dyn Authenticator>,
644    /// Accept a value with no `=` as a bare token, as plexus-idp always has.
645    allow_bare_token: bool,
646}
647
648impl CookieAuthenticator {
649    /// Extract `cookie_name` from the header and hand it to `inner`.
650    pub fn new(
651        name: impl Into<String>,
652        cookie_name: impl Into<String>,
653        inner: Arc<dyn Authenticator>,
654    ) -> Self {
655        Self {
656            name: name.into(),
657            cookie_name: cookie_name.into(),
658            inner,
659            allow_bare_token: true,
660        }
661    }
662
663    /// Require a real cookie pair; reject a bare token in the cookie
664    /// position.
665    pub fn strict(mut self) -> Self {
666        self.allow_bare_token = false;
667        self
668    }
669
670    /// Pull the configured cookie's value out of a `Cookie:` header.
671    fn extract<'a>(&self, header: &'a str) -> Option<&'a str> {
672        if !header.contains('=') {
673            return self.allow_bare_token.then(|| header.trim());
674        }
675        for pair in header.split(';') {
676            let pair = pair.trim();
677            if let Some(rest) = pair.strip_prefix(&self.cookie_name) {
678                if let Some(val) = rest.strip_prefix('=') {
679                    return Some(val.trim());
680                }
681            }
682        }
683        None
684    }
685}
686
687#[async_trait]
688impl Authenticator for CookieAuthenticator {
689    fn name(&self) -> &str {
690        &self.name
691    }
692
693    fn accepts(&self, presentation: &Presentation) -> bool {
694        matches!(presentation, Presentation::Cookie { .. })
695    }
696
697    async fn authenticate(
698        &self,
699        presentation: &Presentation,
700    ) -> Result<Authenticated, AuthnRejection> {
701        let Presentation::Cookie { header } = presentation else {
702            return Err(AuthnRejection::unsupported(&self.name, presentation));
703        };
704
705        let token = self.extract(header).ok_or_else(|| {
706            AuthnRejection::Malformed(format!("no `{}` cookie in header", self.cookie_name))
707        })?;
708        if token.is_empty() {
709            return Err(AuthnRejection::Malformed(format!(
710                "`{}` cookie is empty",
711                self.cookie_name
712            )));
713        }
714
715        let inner = Presentation::Bearer {
716            token: token.to_string(),
717        };
718        match self.inner.authenticate(&inner).await {
719            // Translate the inner authenticator's "not my kind" into this
720            // one's, so a chain sees a consistent story about the cookie.
721            Err(e) if e.is_unsupported() => {
722                Err(AuthnRejection::unsupported(&self.name, presentation))
723            }
724            other => other,
725        }
726    }
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732    use crate::identity::linking::{InMemoryCredentialLink, LinkedCredential};
733
734    const UUID: &str = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
735
736    struct FakeIdp;
737
738    #[async_trait]
739    impl TokenVerifier for FakeIdp {
740        fn issuer(&self) -> Issuer {
741            Issuer::Idp
742        }
743        async fn verify(&self, token: &str) -> Result<VerifiedClaims, AuthnRejection> {
744            match token {
745                "good" => Ok(VerifiedClaims {
746                    subject: UUID.to_string(),
747                    roles: vec!["user".into()],
748                    claims: serde_json::json!({"org_id": "acme"}),
749                }),
750                "stale" => Err(AuthnRejection::Expired),
751                "notauuid" => Ok(VerifiedClaims {
752                    subject: "alice".to_string(),
753                    roles: vec![],
754                    claims: Value::Null,
755                }),
756                _ => Err(AuthnRejection::SignatureInvalid),
757            }
758        }
759    }
760
761    fn bearer(t: &str) -> Presentation {
762        Presentation::Bearer {
763            token: t.to_string(),
764        }
765    }
766
767    #[tokio::test]
768    async fn bearer_authenticator_produces_a_verified_principal() {
769        let a = BearerJwtAuthenticator::new("idp-bearer", FakeIdp);
770        let ok = a.authenticate(&bearer("good")).await.unwrap();
771        assert_eq!(ok.principal().to_string(), format!("idp:{UUID}"));
772        assert_eq!(ok.roles(), ["user"]);
773    }
774
775    #[tokio::test]
776    async fn bearer_authenticator_rejects_with_typed_errors() {
777        let a = BearerJwtAuthenticator::new("idp-bearer", FakeIdp);
778        assert_eq!(
779            a.authenticate(&bearer("stale")).await.unwrap_err(),
780            AuthnRejection::Expired
781        );
782        assert_eq!(
783            a.authenticate(&bearer("forged")).await.unwrap_err(),
784            AuthnRejection::SignatureInvalid
785        );
786        // Verified, but the subject is not nameable in the idp namespace.
787        assert!(matches!(
788            a.authenticate(&bearer("notauuid")).await.unwrap_err(),
789            AuthnRejection::Malformed(_)
790        ));
791        // Wrong carrier entirely.
792        assert!(a
793            .authenticate(&Presentation::ApiKey { key: "x".into() })
794            .await
795            .unwrap_err()
796            .is_unsupported());
797    }
798
799    async fn links_with_key() -> Arc<InMemoryCredentialLink> {
800        let links = Arc::new(InMemoryCredentialLink::new());
801        let p: Principal = format!("idp:{UUID}").parse().unwrap();
802        links
803            .link(
804                LinkedCredential::new(CredentialClass::ApiKey, "digest-of-k1", p)
805                    .with_roles(vec!["service".into()]),
806            )
807            .await
808            .unwrap();
809        links
810    }
811
812    #[tokio::test]
813    async fn api_key_authenticator_resolves_and_rejects() {
814        let links = links_with_key().await;
815        let a = ApiKeyAuthenticator::new(
816            "apikey",
817            links.clone(),
818            Arc::new(|k: &str| format!("digest-of-{k}")),
819        );
820
821        let ok = a
822            .authenticate(&Presentation::ApiKey { key: "k1".into() })
823            .await
824            .unwrap();
825        assert_eq!(ok.principal().to_string(), format!("idp:{UUID}"));
826        assert_eq!(ok.roles(), ["service"]);
827
828        assert_eq!(
829            a.authenticate(&Presentation::ApiKey { key: "nope".into() })
830                .await
831                .unwrap_err(),
832            AuthnRejection::UnknownCredential
833        );
834        assert!(matches!(
835            a.authenticate(&Presentation::ApiKey { key: "".into() })
836                .await
837                .unwrap_err(),
838            AuthnRejection::Malformed(_)
839        ));
840    }
841
842    #[tokio::test]
843    async fn api_key_authenticator_honours_revocation_and_expiry() {
844        let links = Arc::new(InMemoryCredentialLink::new());
845        let p: Principal = format!("idp:{UUID}").parse().unwrap();
846        links
847            .link(LinkedCredential::new(CredentialClass::ApiKey, "dead", p.clone()).revoked())
848            .await
849            .unwrap();
850        links
851            .link(
852                LinkedCredential::new(CredentialClass::ApiKey, "old", p)
853                    .expiring_at(chrono::Utc::now() - chrono::Duration::hours(1)),
854            )
855            .await
856            .unwrap();
857
858        let a = ApiKeyAuthenticator::plaintext("apikey", links);
859        assert_eq!(
860            a.authenticate(&Presentation::ApiKey { key: "dead".into() })
861                .await
862                .unwrap_err(),
863            AuthnRejection::Revoked
864        );
865        assert_eq!(
866            a.authenticate(&Presentation::ApiKey { key: "old".into() })
867                .await
868                .unwrap_err(),
869            AuthnRejection::Expired
870        );
871    }
872
873    #[tokio::test]
874    async fn cookie_authenticator_unwraps_and_delegates() {
875        let inner = Arc::new(BearerJwtAuthenticator::new("idp-bearer", FakeIdp));
876        let a = CookieAuthenticator::new("idp-cookie", "access_token", inner);
877
878        let ok = a
879            .authenticate(&Presentation::Cookie {
880                header: "theme=dark; access_token=good; other=1".into(),
881            })
882            .await
883            .unwrap();
884        assert_eq!(ok.principal().to_string(), format!("idp:{UUID}"));
885
886        // Bare token in the cookie position, as plexus-idp has always allowed.
887        let ok = a
888            .authenticate(&Presentation::Cookie {
889                header: "good".into(),
890            })
891            .await
892            .unwrap();
893        assert_eq!(ok.principal().to_string(), format!("idp:{UUID}"));
894
895        // Missing cookie is malformed; a bad token inside surfaces the inner
896        // error unchanged.
897        assert!(matches!(
898            a.authenticate(&Presentation::Cookie {
899                header: "theme=dark".into()
900            })
901            .await
902            .unwrap_err(),
903            AuthnRejection::Malformed(_)
904        ));
905        assert_eq!(
906            a.authenticate(&Presentation::Cookie {
907                header: "access_token=stale".into()
908            })
909            .await
910            .unwrap_err(),
911            AuthnRejection::Expired
912        );
913    }
914
915    #[tokio::test]
916    async fn cookie_extraction_does_not_match_a_suffix_cookie() {
917        let inner = Arc::new(BearerJwtAuthenticator::new("idp-bearer", FakeIdp));
918        let a = CookieAuthenticator::new("idp-cookie", "access_token", inner);
919        // `xaccess_token` must not be mistaken for `access_token`.
920        let err = a
921            .authenticate(&Presentation::Cookie {
922                header: "xaccess_token=good".into(),
923            })
924            .await
925            .unwrap_err();
926        assert!(matches!(err, AuthnRejection::Malformed(_)), "{err:?}");
927    }
928
929    #[tokio::test]
930    async fn chain_short_circuits_on_a_real_failure() {
931        let links = links_with_key().await;
932        let chain = AuthenticatorChain::new()
933            .with(Arc::new(BearerJwtAuthenticator::new("idp-bearer", FakeIdp)))
934            .with(Arc::new(ApiKeyAuthenticator::plaintext("apikey", links)));
935
936        assert_eq!(chain.names(), ["idp-bearer", "apikey"]);
937
938        // The bearer authenticator claims and fails; the API-key
939        // authenticator must NOT get a second chance at an expired token.
940        assert_eq!(
941            chain.authenticate(&bearer("stale")).await.unwrap_err(),
942            AuthnRejection::Expired
943        );
944    }
945
946    #[tokio::test]
947    async fn empty_chain_reports_unsupported_not_success() {
948        let chain = AuthenticatorChain::new();
949        assert!(chain.is_empty());
950        assert!(chain
951            .authenticate(&bearer("good"))
952            .await
953            .unwrap_err()
954            .is_unsupported());
955        assert!(chain.validate("anything").await.is_none());
956    }
957
958    #[tokio::test]
959    async fn chain_is_a_session_validator() {
960        let chain = AuthenticatorChain::new().with(Arc::new(CookieAuthenticator::new(
961            "idp-cookie",
962            "access_token",
963            Arc::new(BearerJwtAuthenticator::new("idp-bearer", FakeIdp)),
964        )));
965
966        let ctx = chain.validate("access_token=good").await.unwrap();
967        assert_eq!(ctx.user_id, UUID);
968        assert_eq!(
969            ctx.principal().map(|p| p.to_string()),
970            Some(format!("idp:{UUID}"))
971        );
972        assert!(chain.validate("access_token=forged").await.is_none());
973    }
974}