Skip to main content

plexus_auth_core/
capabilities.rs

1//! Capability advertisement primitives — what a backend tells a client about
2//! its authentication surface, served at `_info`.
3//!
4//! Per AUTHZ-S01-output §2: a backend extends its `_info` response with an
5//! optional `auth_capabilities` field carrying a [`BackendAuthCapabilities`].
6//! Clients (synapse CLI, gamma, generated SDKs, agents) read it to decide
7//! which authentication flow to drive.
8//!
9//! These types are *not* sealed — the cryptographic anchor is `AuthContext` /
10//! `VerifiedUser` in this same crate. Capability-advertisement types carry
11//! contract metadata; they belong here with the auth primitives so the
12//! dependency graph and the orphan-rule defense extend uniformly per AUTHZ-0
13//! §"Crate-level isolation amplifies the seal".
14//!
15//! Each newtype follows the strong-typing skill: `Debug, Clone, PartialEq, Eq,
16//! Hash, Serialize, Deserialize`; `#[serde(transparent)]` for single-field
17//! wrappers; validation at the wire boundary via a `try_new` constructor;
18//! `as_str()` accessor; `Display` for tracing.
19
20use schemars::JsonSchema;
21use serde::{Deserialize, Serialize};
22use std::fmt;
23use url::Url;
24
25// ---------------------------------------------------------------------------
26// Error types
27// ---------------------------------------------------------------------------
28
29/// Why a `MethodPath::try_new` rejected its input.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum MethodPathError {
32    /// Empty input.
33    Empty,
34    /// Path does not match `^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$`.
35    InvalidFormat(String),
36}
37
38impl fmt::Display for MethodPathError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            Self::Empty => write!(f, "method path is empty"),
42            Self::InvalidFormat(s) => write!(
43                f,
44                "method path {:?} does not match `^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$`",
45                s
46            ),
47        }
48    }
49}
50
51impl std::error::Error for MethodPathError {}
52
53/// Why an `IssuerUrl::try_new` rejected its input.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum IssuerUrlError {
56    /// Scheme is not `https`, and host is not localhost on `http`.
57    InsecureScheme(String),
58}
59
60impl fmt::Display for IssuerUrlError {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match self {
63            Self::InsecureScheme(u) => write!(
64                f,
65                "issuer URL {:?} must be https:// (or http://localhost)",
66                u
67            ),
68        }
69    }
70}
71
72impl std::error::Error for IssuerUrlError {}
73
74/// Why a `CookieName::try_new` rejected its input.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub enum CookieNameError {
77    /// Empty.
78    Empty,
79    /// Contains a byte outside RFC 6265's `cookie-name = token` set.
80    InvalidToken(String),
81}
82
83impl fmt::Display for CookieNameError {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        match self {
86            Self::Empty => write!(f, "cookie name is empty"),
87            Self::InvalidToken(s) => write!(
88                f,
89                "cookie name {:?} contains characters outside RFC 6265 token set",
90                s
91            ),
92        }
93    }
94}
95
96impl std::error::Error for CookieNameError {}
97
98/// Why a `HeaderName::try_new` rejected its input.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum HeaderNameError {
101    /// Empty.
102    Empty,
103    /// Contains a byte outside RFC 7230's `field-name = token` set.
104    InvalidToken(String),
105}
106
107impl fmt::Display for HeaderNameError {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        match self {
110            Self::Empty => write!(f, "header name is empty"),
111            Self::InvalidToken(s) => write!(
112                f,
113                "header name {:?} contains characters outside RFC 7230 token set",
114                s
115            ),
116        }
117    }
118}
119
120impl std::error::Error for HeaderNameError {}
121
122/// Why a `ClientId::try_new` rejected its input.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub enum ClientIdError {
125    /// Empty.
126    Empty,
127}
128
129impl fmt::Display for ClientIdError {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        match self {
132            Self::Empty => write!(f, "client_id is empty"),
133        }
134    }
135}
136
137impl std::error::Error for ClientIdError {}
138
139/// Why a `BackendAuthCapabilities::new` rejected its input.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub enum BackendAuthCapabilitiesError {
142    /// `default` index is out of range for `mechanisms`.
143    DefaultOutOfRange { default: usize, len: usize },
144}
145
146impl fmt::Display for BackendAuthCapabilitiesError {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        match self {
149            Self::DefaultOutOfRange { default, len } => write!(
150                f,
151                "default index {} is out of range for mechanisms (len = {})",
152                default, len
153            ),
154        }
155    }
156}
157
158impl std::error::Error for BackendAuthCapabilitiesError {}
159
160// ---------------------------------------------------------------------------
161// MethodPath
162// ---------------------------------------------------------------------------
163
164/// A dotted method path like `auth.login` or `cone.send_message`.
165///
166/// Wire form: bare string. Validation: must match
167/// `^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$`. At least two segments are required
168/// (the activation namespace plus the method name).
169///
170/// Wildcards are NOT allowed — wildcards belong to `Scope` (AUTHZ-CORE-4).
171///
172/// Per AUTHZ-S01-output §1.
173#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
174#[serde(transparent)]
175pub struct MethodPath(String);
176
177impl MethodPath {
178    /// Construct a `MethodPath`, validating the dotted-path grammar.
179    pub fn try_new(s: impl Into<String>) -> Result<Self, MethodPathError> {
180        let s = s.into();
181        if s.is_empty() {
182            return Err(MethodPathError::Empty);
183        }
184        if !is_valid_method_path(&s) {
185            return Err(MethodPathError::InvalidFormat(s));
186        }
187        Ok(Self(s))
188    }
189
190    /// Borrow the inner string.
191    pub fn as_str(&self) -> &str {
192        &self.0
193    }
194
195    /// The first segment — the activation namespace (e.g., `"auth"` in
196    /// `"auth.login"`).
197    pub fn activation(&self) -> &str {
198        self.0.split('.').next().expect("validated: at least one segment")
199    }
200
201    /// The last segment — the method name (e.g., `"login"` in
202    /// `"auth.login"`).
203    pub fn method(&self) -> &str {
204        self.0.rsplit('.').next().expect("validated: at least one segment")
205    }
206}
207
208impl fmt::Display for MethodPath {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        f.write_str(&self.0)
211    }
212}
213
214fn is_valid_method_path(s: &str) -> bool {
215    // Grammar: `^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$`
216    // Implemented without `regex` to avoid pulling that dep into auth-core.
217    let mut segments = s.split('.');
218    let first = match segments.next() {
219        Some(seg) => seg,
220        None => return false,
221    };
222    if !is_valid_path_segment(first) {
223        return false;
224    }
225    let mut has_second_segment = false;
226    for seg in segments {
227        has_second_segment = true;
228        if !is_valid_path_segment(seg) {
229            return false;
230        }
231    }
232    has_second_segment
233}
234
235/// Shared segment grammar `[a-z][a-z0-9_]*` — used by `MethodPath` here and
236/// by the `Scope` / `RoleName` grammars in `crate::scope_registry`
237/// (AUTHZ-CORE-4).
238pub(crate) fn is_valid_path_segment(seg: &str) -> bool {
239    let mut chars = seg.chars();
240    let first = match chars.next() {
241        Some(c) => c,
242        None => return false, // empty segment
243    };
244    if !first.is_ascii_lowercase() {
245        return false;
246    }
247    for c in chars {
248        if !(c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {
249            return false;
250        }
251    }
252    true
253}
254
255// ---------------------------------------------------------------------------
256// IssuerUrl
257// ---------------------------------------------------------------------------
258
259/// An OIDC-style issuer URL.
260///
261/// Constructor validates `https://` URLs and `http://localhost[:port]/` URLs
262/// (loopback exception for development). All other schemes / hosts are
263/// rejected.
264///
265/// Per AUTHZ-S01-output §1.
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
267#[serde(transparent)]
268pub struct IssuerUrl(#[schemars(with = "String")] Url);
269
270impl IssuerUrl {
271    /// Construct an `IssuerUrl`. Accepts `https://...` and `http://localhost...`.
272    pub fn try_new(u: Url) -> Result<Self, IssuerUrlError> {
273        let scheme = u.scheme();
274        let is_https = scheme == "https";
275        let is_localhost_http = scheme == "http"
276            && u
277                .host_str()
278                .map(|h| h == "localhost" || h == "127.0.0.1" || h == "[::1]")
279                .unwrap_or(false);
280        if !(is_https || is_localhost_http) {
281            return Err(IssuerUrlError::InsecureScheme(u.to_string()));
282        }
283        Ok(Self(u))
284    }
285
286    /// Borrow the inner URL.
287    pub fn as_url(&self) -> &Url {
288        &self.0
289    }
290}
291
292impl fmt::Display for IssuerUrl {
293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294        f.write_str(self.0.as_str())
295    }
296}
297
298impl std::hash::Hash for IssuerUrl {
299    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
300        self.0.as_str().hash(state);
301    }
302}
303
304// ---------------------------------------------------------------------------
305// ClientId
306// ---------------------------------------------------------------------------
307
308/// OIDC `client_id` opaque identifier.
309///
310/// Treated as bytes; only non-empty is enforced. Per AUTHZ-S01-output §1.
311#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
312#[serde(transparent)]
313pub struct ClientId(String);
314
315impl ClientId {
316    /// Construct a `ClientId`. Rejects only the empty string.
317    pub fn try_new(s: impl Into<String>) -> Result<Self, ClientIdError> {
318        let s = s.into();
319        if s.is_empty() {
320            return Err(ClientIdError::Empty);
321        }
322        Ok(Self(s))
323    }
324
325    /// Borrow the inner string.
326    pub fn as_str(&self) -> &str {
327        &self.0
328    }
329}
330
331impl fmt::Display for ClientId {
332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333        f.write_str(&self.0)
334    }
335}
336
337// ---------------------------------------------------------------------------
338// CookieName
339// ---------------------------------------------------------------------------
340
341/// A cookie name (e.g. `"plexus_session"`). RFC 6265 token-set validation.
342///
343/// Per AUTHZ-S01-output §1. RFC 6265 defines `cookie-name = token` and `token`
344/// from RFC 7230 §3.2.6: any VCHAR except CTLs, separators, and the
345/// delimiters listed in RFC 7230.
346#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
347#[serde(transparent)]
348pub struct CookieName(String);
349
350impl CookieName {
351    /// Construct a `CookieName`, validating against RFC 6265 / 7230 `token`.
352    pub fn try_new(s: impl Into<String>) -> Result<Self, CookieNameError> {
353        let s = s.into();
354        if s.is_empty() {
355            return Err(CookieNameError::Empty);
356        }
357        if !s.bytes().all(is_rfc7230_token_byte) {
358            return Err(CookieNameError::InvalidToken(s));
359        }
360        Ok(Self(s))
361    }
362
363    /// Borrow the inner string.
364    pub fn as_str(&self) -> &str {
365        &self.0
366    }
367}
368
369impl fmt::Display for CookieName {
370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371        f.write_str(&self.0)
372    }
373}
374
375/// RFC 7230 §3.2.6 token character set.
376///
377/// `token = 1*tchar`,
378/// `tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^"
379///           / "_" / "`" / "|" / "~" / DIGIT / ALPHA`
380fn is_rfc7230_token_byte(b: u8) -> bool {
381    matches!(
382        b,
383        b'!' | b'#'
384            | b'$'
385            | b'%'
386            | b'&'
387            | b'\''
388            | b'*'
389            | b'+'
390            | b'-'
391            | b'.'
392            | b'^'
393            | b'_'
394            | b'`'
395            | b'|'
396            | b'~'
397            | b'0'..=b'9'
398            | b'A'..=b'Z'
399            | b'a'..=b'z'
400    )
401}
402
403// ---------------------------------------------------------------------------
404// HeaderName
405// ---------------------------------------------------------------------------
406
407/// An HTTP header name (e.g. `"Authorization"`).
408///
409/// Stored normalized to lowercase so equality matches the case-insensitive
410/// HTTP convention. RFC 7230 §3.2 token-set validation applied to the input
411/// before normalization. Per AUTHZ-S01-output §1.
412#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
413#[serde(transparent)]
414pub struct HeaderName(String);
415
416impl HeaderName {
417    /// Construct a `HeaderName`. The input is lowercased on construction;
418    /// invalid token characters are rejected.
419    pub fn try_new(s: impl Into<String>) -> Result<Self, HeaderNameError> {
420        let s = s.into();
421        if s.is_empty() {
422            return Err(HeaderNameError::Empty);
423        }
424        if !s.bytes().all(is_rfc7230_token_byte) {
425            return Err(HeaderNameError::InvalidToken(s));
426        }
427        Ok(Self(s.to_ascii_lowercase()))
428    }
429
430    /// Borrow the inner (normalized, lowercase) string.
431    pub fn as_str(&self) -> &str {
432        &self.0
433    }
434}
435
436impl fmt::Display for HeaderName {
437    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438        f.write_str(&self.0)
439    }
440}
441
442// ---------------------------------------------------------------------------
443// AuthMechanism
444// ---------------------------------------------------------------------------
445
446/// Tagged union of supported auth mechanisms a backend advertises.
447///
448/// Wire form: discriminated on `kind`, snake_case (`"bearer"`, `"cookie"`,
449/// `"oidc"`, `"anonymous"`). See AUTHZ-S01-output §2 for canonical JSON
450/// examples.
451#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
452#[serde(tag = "kind", rename_all = "snake_case")]
453pub enum AuthMechanism {
454    /// Static bearer token (today's substrate `--api-key` shape). Not
455    /// user-bound; the token authorizes the bearer.
456    Bearer {
457        /// Header carrying the token, e.g. `Authorization`.
458        header: HeaderName,
459    },
460
461    /// Cookie session, with a backend-defined `login` method that issues
462    /// `Set-Cookie`.
463    Cookie {
464        /// Name of the session cookie.
465        cookie: CookieName,
466        /// Method the client calls to issue/establish the cookie.
467        login: MethodPath,
468        /// Optional method to renew the cookie.
469        #[serde(skip_serializing_if = "Option::is_none", default)]
470        refresh: Option<MethodPath>,
471        /// Optional method to invalidate the cookie.
472        #[serde(skip_serializing_if = "Option::is_none", default)]
473        logout: Option<MethodPath>,
474    },
475
476    /// OIDC mechanism (designed-for; may not be implemented in initial epic).
477    Oidc {
478        /// Issuer URL of the IdP.
479        issuer: IssuerUrl,
480        /// `client_id` registered with the IdP for this backend.
481        client_id: ClientId,
482        /// Optional `auth.exchange`-style method the backend exposes to swap
483        /// an ID token for a backend session cookie.
484        #[serde(skip_serializing_if = "Option::is_none", default)]
485        exchange: Option<MethodPath>,
486        /// Scopes the backend will request from the IdP. Bare-string scopes
487        /// per the OIDC convention (e.g. `"openid"`, `"profile"`, `"email"`);
488        /// AUTHZ scoping vocabulary is a separate concern (AUTHZ-CORE-4).
489        request_scopes: Vec<String>,
490    },
491
492    /// Anonymous — the backend accepts unauthenticated callers for some
493    /// methods.
494    ///
495    /// Advertising `Anonymous` is **not** permission to bypass scoping:
496    /// per-method `#[plexus::method(public)]` markers gate which methods
497    /// anonymous callers may invoke (AUTHZ-CORE-1 / AUTHZ-CORE-2). The
498    /// advertisement says "anonymous is one of the accepted shapes"; the
499    /// authorization layer says "this specific method is callable that way."
500    Anonymous,
501}
502
503impl AuthMechanism {
504    /// The [`AttachmentSite`] this mechanism implies for credential
505    /// placement on subsequent calls — the CA-1 derivation rule (trak facet
506    /// `ccc924ad-0e78-4d4b-b71f-0018d249d0bf`).
507    ///
508    /// Mapping table:
509    ///
510    /// | Mechanism   | Implied site                            |
511    /// |-------------|-----------------------------------------|
512    /// | `Bearer`    | `Header { name: <advertised header> }`  |
513    /// | `Cookie`    | `Cookie { name: <advertised cookie> }`  |
514    /// | `Oidc`      | `Header { name: "authorization" }`      |
515    /// | `Anonymous` | `None` (nothing to attach)              |
516    ///
517    /// `Oidc` maps to the bearer convention (`Authorization: Bearer <jwt>`)
518    /// because the OIDC validator accepts the ID/access token there; an
519    /// OIDC backend whose exchanged session rides a cookie should advertise
520    /// a `Cookie` mechanism alongside (and mark it `default`) to steer the
521    /// derivation.
522    pub fn implied_attachment_site(&self) -> Option<crate::credential::AttachmentSite> {
523        use crate::credential::AttachmentSite;
524        match self {
525            AuthMechanism::Bearer { header } => Some(AttachmentSite::Header {
526                name: header.clone(),
527            }),
528            AuthMechanism::Cookie { cookie, .. } => Some(AttachmentSite::Cookie {
529                name: cookie.clone(),
530            }),
531            AuthMechanism::Oidc { .. } => Some(AttachmentSite::Header {
532                name: HeaderName::try_new("authorization")
533                    .expect("static header name is valid"),
534            }),
535            AuthMechanism::Anonymous => None,
536        }
537    }
538}
539
540// ---------------------------------------------------------------------------
541// BackendAuthCapabilities
542// ---------------------------------------------------------------------------
543
544/// What the backend advertises at `_info`'s `auth_capabilities` field.
545///
546/// Per AUTHZ-S01-output §2. Backwards-compatible addition: clients that don't
547/// know the field continue to ignore it.
548#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
549pub struct BackendAuthCapabilities {
550    /// Mechanisms the backend supports. May be empty (no auth wired) but
551    /// conventionally contains at least one entry; the framework default
552    /// emits `[Anonymous]` when no backend has called
553    /// `DynamicHub::with_auth_capabilities`.
554    pub mechanisms: Vec<AuthMechanism>,
555
556    /// Index into `mechanisms` for the "primary" mechanism a generic client
557    /// should try first. `None` means "no opinion; client chooses."
558    #[serde(skip_serializing_if = "Option::is_none", default)]
559    pub default: Option<usize>,
560}
561
562impl BackendAuthCapabilities {
563    /// Construct a `BackendAuthCapabilities`, validating that `default` (if
564    /// present) is in range.
565    pub fn new(
566        mechanisms: Vec<AuthMechanism>,
567        default: Option<usize>,
568    ) -> Result<Self, BackendAuthCapabilitiesError> {
569        if let Some(idx) = default {
570            if idx >= mechanisms.len() {
571                return Err(BackendAuthCapabilitiesError::DefaultOutOfRange {
572                    default: idx,
573                    len: mechanisms.len(),
574                });
575            }
576        }
577        Ok(Self {
578            mechanisms,
579            default,
580        })
581    }
582
583    /// The default value emitted by `_info` for backends that have not called
584    /// `DynamicHub::with_auth_capabilities`: a single `Anonymous` mechanism,
585    /// no preferred default.
586    ///
587    /// This preserves today's substrate behavior (anyone can call) while
588    /// signaling "no auth wired" to capability-aware clients.
589    pub fn anonymous_default() -> Self {
590        Self {
591            mechanisms: vec![AuthMechanism::Anonymous],
592            default: None,
593        }
594    }
595
596    /// The [`AttachmentSite`] this capability advertisement implies — used
597    /// by the framework to fill `RequiredCredential.site_hint` at
598    /// schema-assembly time (CA-1, trak facet
599    /// `ccc924ad-0e78-4d4b-b71f-0018d249d0bf`).
600    ///
601    /// Selection order:
602    ///
603    /// 1. The `default`-indexed mechanism, when set and it implies a site.
604    /// 2. Otherwise the first mechanism (advertisement order) that implies
605    ///    a site.
606    /// 3. Otherwise `None` (anonymous-only / empty advertisements imply no
607    ///    attach site — schemas stay byte-identical to pre-CA-1).
608    ///
609    /// [`AttachmentSite`]: crate::credential::AttachmentSite
610    pub fn implied_attachment_site(&self) -> Option<crate::credential::AttachmentSite> {
611        if let Some(site) = self
612            .default
613            .and_then(|idx| self.mechanisms.get(idx))
614            .and_then(AuthMechanism::implied_attachment_site)
615        {
616            return Some(site);
617        }
618        self.mechanisms
619            .iter()
620            .find_map(AuthMechanism::implied_attachment_site)
621    }
622}
623
624// ---------------------------------------------------------------------------
625// Tests
626// ---------------------------------------------------------------------------
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631    use serde_json::json;
632
633    // -- MethodPath -----------------------------------------------------------
634
635    #[test]
636    fn method_path_accepts_two_segments() {
637        let m = MethodPath::try_new("auth.login").expect("valid");
638        assert_eq!(m.as_str(), "auth.login");
639        assert_eq!(m.activation(), "auth");
640        assert_eq!(m.method(), "login");
641    }
642
643    #[test]
644    fn method_path_accepts_three_segments() {
645        let m = MethodPath::try_new("cone.threads.list").expect("valid");
646        assert_eq!(m.activation(), "cone");
647        assert_eq!(m.method(), "list");
648    }
649
650    #[test]
651    fn method_path_accepts_underscored_segments() {
652        MethodPath::try_new("cone.send_message").expect("underscores ok");
653        MethodPath::try_new("a_b.c_d_e").expect("multiple underscores ok");
654    }
655
656    #[test]
657    fn method_path_rejects_single_segment() {
658        assert!(matches!(
659            MethodPath::try_new("login"),
660            Err(MethodPathError::InvalidFormat(_))
661        ));
662    }
663
664    #[test]
665    fn method_path_rejects_uppercase() {
666        assert!(matches!(
667            MethodPath::try_new("Auth.login"),
668            Err(MethodPathError::InvalidFormat(_))
669        ));
670        assert!(matches!(
671            MethodPath::try_new("auth.Login"),
672            Err(MethodPathError::InvalidFormat(_))
673        ));
674    }
675
676    #[test]
677    fn method_path_rejects_leading_digit() {
678        assert!(matches!(
679            MethodPath::try_new("1auth.login"),
680            Err(MethodPathError::InvalidFormat(_))
681        ));
682        assert!(matches!(
683            MethodPath::try_new("auth.2login"),
684            Err(MethodPathError::InvalidFormat(_))
685        ));
686    }
687
688    #[test]
689    fn method_path_rejects_trailing_dot() {
690        assert!(matches!(
691            MethodPath::try_new("auth."),
692            Err(MethodPathError::InvalidFormat(_))
693        ));
694    }
695
696    #[test]
697    fn method_path_rejects_leading_dot() {
698        assert!(matches!(
699            MethodPath::try_new(".login"),
700            Err(MethodPathError::InvalidFormat(_))
701        ));
702    }
703
704    #[test]
705    fn method_path_rejects_wildcard() {
706        // Wildcards belong to Scope, not MethodPath.
707        assert!(matches!(
708            MethodPath::try_new("auth.*"),
709            Err(MethodPathError::InvalidFormat(_))
710        ));
711        assert!(matches!(
712            MethodPath::try_new("*"),
713            Err(MethodPathError::InvalidFormat(_))
714        ));
715    }
716
717    #[test]
718    fn method_path_rejects_empty() {
719        assert_eq!(MethodPath::try_new(""), Err(MethodPathError::Empty));
720    }
721
722    #[test]
723    fn method_path_rejects_double_dot() {
724        assert!(matches!(
725            MethodPath::try_new("auth..login"),
726            Err(MethodPathError::InvalidFormat(_))
727        ));
728    }
729
730    #[test]
731    fn method_path_serde_roundtrip() {
732        let m = MethodPath::try_new("auth.login").unwrap();
733        let s = serde_json::to_string(&m).unwrap();
734        assert_eq!(s, "\"auth.login\"");
735        let back: MethodPath = serde_json::from_str(&s).unwrap();
736        assert_eq!(back, m);
737    }
738
739    // -- IssuerUrl ------------------------------------------------------------
740
741    #[test]
742    fn issuer_url_accepts_https() {
743        let u: Url = "https://accounts.example.com/".parse().unwrap();
744        let i = IssuerUrl::try_new(u.clone()).expect("https ok");
745        assert_eq!(i.as_url(), &u);
746    }
747
748    #[test]
749    fn issuer_url_accepts_localhost_http() {
750        let u: Url = "http://localhost:8080/".parse().unwrap();
751        IssuerUrl::try_new(u).expect("http://localhost ok");
752        let u2: Url = "http://127.0.0.1:8080/".parse().unwrap();
753        IssuerUrl::try_new(u2).expect("http://127.0.0.1 ok");
754        let u3: Url = "http://[::1]:8080/".parse().unwrap();
755        IssuerUrl::try_new(u3).expect("http://[::1] ok");
756    }
757
758    #[test]
759    fn issuer_url_rejects_non_localhost_http() {
760        let u: Url = "http://accounts.example.com/".parse().unwrap();
761        assert!(matches!(
762            IssuerUrl::try_new(u),
763            Err(IssuerUrlError::InsecureScheme(_))
764        ));
765    }
766
767    #[test]
768    fn issuer_url_rejects_other_schemes() {
769        let u: Url = "ftp://example.com/".parse().unwrap();
770        assert!(matches!(
771            IssuerUrl::try_new(u),
772            Err(IssuerUrlError::InsecureScheme(_))
773        ));
774    }
775
776    #[test]
777    fn issuer_url_serde_roundtrip() {
778        let u: Url = "https://accounts.example.com/".parse().unwrap();
779        let i = IssuerUrl::try_new(u).unwrap();
780        let s = serde_json::to_string(&i).unwrap();
781        assert_eq!(s, "\"https://accounts.example.com/\"");
782        let back: IssuerUrl = serde_json::from_str(&s).unwrap();
783        assert_eq!(back, i);
784    }
785
786    // -- ClientId -------------------------------------------------------------
787
788    #[test]
789    fn client_id_accepts_non_empty() {
790        let c = ClientId::try_new("plexus-substrate").unwrap();
791        assert_eq!(c.as_str(), "plexus-substrate");
792    }
793
794    #[test]
795    fn client_id_rejects_empty() {
796        assert_eq!(ClientId::try_new(""), Err(ClientIdError::Empty));
797    }
798
799    // -- CookieName -----------------------------------------------------------
800
801    #[test]
802    fn cookie_name_accepts_valid_token() {
803        CookieName::try_new("plexus_session").unwrap();
804        CookieName::try_new("Session-Id").unwrap();
805        CookieName::try_new("a.b.c").unwrap();
806    }
807
808    #[test]
809    fn cookie_name_rejects_separator_chars() {
810        // RFC 7230 separators that must be rejected: ( ) , / : ; < = > ? @ [ \ ] { } " whitespace
811        for ch in [' ', '(', ')', ',', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '{', '}', '"'] {
812            let name = format!("a{}b", ch);
813            assert!(
814                matches!(
815                    CookieName::try_new(name.clone()),
816                    Err(CookieNameError::InvalidToken(_))
817                ),
818                "expected reject for {:?}",
819                name
820            );
821        }
822    }
823
824    #[test]
825    fn cookie_name_rejects_empty() {
826        assert_eq!(CookieName::try_new(""), Err(CookieNameError::Empty));
827    }
828
829    // -- HeaderName -----------------------------------------------------------
830
831    #[test]
832    fn header_name_normalizes_to_lowercase() {
833        let h = HeaderName::try_new("Authorization").unwrap();
834        assert_eq!(h.as_str(), "authorization");
835
836        // Different cases compare equal because both normalize.
837        let h2 = HeaderName::try_new("AUTHORIZATION").unwrap();
838        let h3 = HeaderName::try_new("authorization").unwrap();
839        assert_eq!(h, h2);
840        assert_eq!(h, h3);
841    }
842
843    #[test]
844    fn header_name_rejects_invalid_chars() {
845        assert!(matches!(
846            HeaderName::try_new("X Header"),
847            Err(HeaderNameError::InvalidToken(_))
848        ));
849        assert!(matches!(
850            HeaderName::try_new("X:Header"),
851            Err(HeaderNameError::InvalidToken(_))
852        ));
853    }
854
855    #[test]
856    fn header_name_rejects_empty() {
857        assert_eq!(HeaderName::try_new(""), Err(HeaderNameError::Empty));
858    }
859
860    // -- AuthMechanism serialization ------------------------------------------
861
862    #[test]
863    fn auth_mechanism_bearer_round_trip() {
864        let m = AuthMechanism::Bearer {
865            header: HeaderName::try_new("authorization").unwrap(),
866        };
867        let v = serde_json::to_value(&m).unwrap();
868        assert_eq!(
869            v,
870            json!({
871                "kind": "bearer",
872                "header": "authorization"
873            })
874        );
875        let back: AuthMechanism = serde_json::from_value(v).unwrap();
876        assert_eq!(back, m);
877    }
878
879    #[test]
880    fn auth_mechanism_cookie_round_trip_minimal() {
881        // refresh / logout omitted — exercise the skip_serializing_if path.
882        let m = AuthMechanism::Cookie {
883            cookie: CookieName::try_new("plexus_session").unwrap(),
884            login: MethodPath::try_new("auth.login").unwrap(),
885            refresh: None,
886            logout: None,
887        };
888        let v = serde_json::to_value(&m).unwrap();
889        assert_eq!(
890            v,
891            json!({
892                "kind": "cookie",
893                "cookie": "plexus_session",
894                "login": "auth.login"
895            }),
896            "refresh / logout should be omitted when None"
897        );
898        let back: AuthMechanism = serde_json::from_value(v).unwrap();
899        assert_eq!(back, m);
900    }
901
902    #[test]
903    fn auth_mechanism_cookie_round_trip_full() {
904        let m = AuthMechanism::Cookie {
905            cookie: CookieName::try_new("plexus_session").unwrap(),
906            login: MethodPath::try_new("auth.login").unwrap(),
907            refresh: Some(MethodPath::try_new("auth.refresh").unwrap()),
908            logout: Some(MethodPath::try_new("auth.logout").unwrap()),
909        };
910        let v = serde_json::to_value(&m).unwrap();
911        assert_eq!(
912            v,
913            json!({
914                "kind": "cookie",
915                "cookie": "plexus_session",
916                "login": "auth.login",
917                "refresh": "auth.refresh",
918                "logout": "auth.logout"
919            })
920        );
921        let back: AuthMechanism = serde_json::from_value(v).unwrap();
922        assert_eq!(back, m);
923    }
924
925    #[test]
926    fn auth_mechanism_oidc_round_trip() {
927        let m = AuthMechanism::Oidc {
928            issuer: IssuerUrl::try_new("https://accounts.example.com/".parse().unwrap()).unwrap(),
929            client_id: ClientId::try_new("plexus-substrate").unwrap(),
930            exchange: Some(MethodPath::try_new("auth.exchange").unwrap()),
931            request_scopes: vec!["openid".into(), "profile".into(), "email".into()],
932        };
933        let v = serde_json::to_value(&m).unwrap();
934        assert_eq!(
935            v,
936            json!({
937                "kind": "oidc",
938                "issuer": "https://accounts.example.com/",
939                "client_id": "plexus-substrate",
940                "exchange": "auth.exchange",
941                "request_scopes": ["openid", "profile", "email"]
942            })
943        );
944        let back: AuthMechanism = serde_json::from_value(v).unwrap();
945        assert_eq!(back, m);
946    }
947
948    #[test]
949    fn auth_mechanism_anonymous_round_trip() {
950        let m = AuthMechanism::Anonymous;
951        let v = serde_json::to_value(&m).unwrap();
952        assert_eq!(v, json!({ "kind": "anonymous" }));
953        let back: AuthMechanism = serde_json::from_value(v).unwrap();
954        assert_eq!(back, m);
955    }
956
957    // -- BackendAuthCapabilities ---------------------------------------------
958
959    #[test]
960    fn backend_auth_capabilities_constructs_with_valid_default() {
961        let caps = BackendAuthCapabilities::new(
962            vec![
963                AuthMechanism::Bearer {
964                    header: HeaderName::try_new("authorization").unwrap(),
965                },
966                AuthMechanism::Cookie {
967                    cookie: CookieName::try_new("plexus_session").unwrap(),
968                    login: MethodPath::try_new("auth.login").unwrap(),
969                    refresh: None,
970                    logout: None,
971                },
972            ],
973            Some(1),
974        )
975        .unwrap();
976        assert_eq!(caps.default, Some(1));
977        assert_eq!(caps.mechanisms.len(), 2);
978    }
979
980    #[test]
981    fn backend_auth_capabilities_rejects_out_of_range_default() {
982        let res = BackendAuthCapabilities::new(
983            vec![AuthMechanism::Anonymous],
984            Some(5),
985        );
986        assert_eq!(
987            res,
988            Err(BackendAuthCapabilitiesError::DefaultOutOfRange {
989                default: 5,
990                len: 1,
991            })
992        );
993    }
994
995    #[test]
996    fn backend_auth_capabilities_rejects_default_for_empty_mechanisms() {
997        let res = BackendAuthCapabilities::new(vec![], Some(0));
998        assert_eq!(
999            res,
1000            Err(BackendAuthCapabilitiesError::DefaultOutOfRange {
1001                default: 0,
1002                len: 0,
1003            })
1004        );
1005    }
1006
1007    #[test]
1008    fn backend_auth_capabilities_anonymous_default() {
1009        let caps = BackendAuthCapabilities::anonymous_default();
1010        assert_eq!(caps.mechanisms, vec![AuthMechanism::Anonymous]);
1011        assert_eq!(caps.default, None);
1012
1013        // Wire format: default is omitted when None.
1014        let v = serde_json::to_value(&caps).unwrap();
1015        assert_eq!(
1016            v,
1017            json!({
1018                "mechanisms": [{ "kind": "anonymous" }]
1019            }),
1020            "default should be omitted when None"
1021        );
1022    }
1023
1024    #[test]
1025    fn backend_auth_capabilities_full_wire_form_matches_spec() {
1026        // The canonical example from AUTHZ-S01-output §2 (verbatim).
1027        let caps = BackendAuthCapabilities::new(
1028            vec![
1029                AuthMechanism::Bearer {
1030                    header: HeaderName::try_new("authorization").unwrap(),
1031                },
1032                AuthMechanism::Cookie {
1033                    cookie: CookieName::try_new("plexus_session").unwrap(),
1034                    login: MethodPath::try_new("auth.login").unwrap(),
1035                    refresh: Some(MethodPath::try_new("auth.refresh").unwrap()),
1036                    logout: Some(MethodPath::try_new("auth.logout").unwrap()),
1037                },
1038                AuthMechanism::Oidc {
1039                    issuer: IssuerUrl::try_new(
1040                        "https://accounts.example.com/".parse().unwrap(),
1041                    )
1042                    .unwrap(),
1043                    client_id: ClientId::try_new("plexus-substrate").unwrap(),
1044                    exchange: Some(MethodPath::try_new("auth.exchange").unwrap()),
1045                    request_scopes: vec!["openid".into(), "profile".into(), "email".into()],
1046                },
1047            ],
1048            Some(1),
1049        )
1050        .unwrap();
1051
1052        let v = serde_json::to_value(&caps).unwrap();
1053        assert_eq!(
1054            v,
1055            json!({
1056                "mechanisms": [
1057                    { "kind": "bearer", "header": "authorization" },
1058                    {
1059                        "kind": "cookie",
1060                        "cookie": "plexus_session",
1061                        "login": "auth.login",
1062                        "refresh": "auth.refresh",
1063                        "logout": "auth.logout"
1064                    },
1065                    {
1066                        "kind": "oidc",
1067                        "issuer": "https://accounts.example.com/",
1068                        "client_id": "plexus-substrate",
1069                        "exchange": "auth.exchange",
1070                        "request_scopes": ["openid", "profile", "email"]
1071                    }
1072                ],
1073                "default": 1
1074            })
1075        );
1076
1077        // Round-trip back.
1078        let back: BackendAuthCapabilities = serde_json::from_value(v).unwrap();
1079        assert_eq!(back, caps);
1080    }
1081
1082    // -- implied_attachment_site (CA-1) ---------------------------------------
1083
1084    use crate::credential::AttachmentSite;
1085
1086    fn bearer() -> AuthMechanism {
1087        AuthMechanism::Bearer {
1088            header: HeaderName::try_new("authorization").unwrap(),
1089        }
1090    }
1091
1092    fn cookie() -> AuthMechanism {
1093        AuthMechanism::Cookie {
1094            cookie: CookieName::try_new("plexus_session").unwrap(),
1095            login: MethodPath::try_new("auth.login").unwrap(),
1096            refresh: None,
1097            logout: None,
1098        }
1099    }
1100
1101    fn oidc() -> AuthMechanism {
1102        AuthMechanism::Oidc {
1103            issuer: IssuerUrl::try_new("https://accounts.example.com/".parse().unwrap())
1104                .unwrap(),
1105            client_id: ClientId::try_new("plexus-substrate").unwrap(),
1106            exchange: None,
1107            request_scopes: vec!["openid".into()],
1108        }
1109    }
1110
1111    #[test]
1112    fn mechanism_implied_site_mapping_table() {
1113        assert_eq!(
1114            bearer().implied_attachment_site(),
1115            Some(AttachmentSite::Header {
1116                name: HeaderName::try_new("authorization").unwrap()
1117            })
1118        );
1119        assert_eq!(
1120            cookie().implied_attachment_site(),
1121            Some(AttachmentSite::Cookie {
1122                name: CookieName::try_new("plexus_session").unwrap()
1123            })
1124        );
1125        // OIDC maps to the bearer convention.
1126        assert_eq!(
1127            oidc().implied_attachment_site(),
1128            Some(AttachmentSite::Header {
1129                name: HeaderName::try_new("authorization").unwrap()
1130            })
1131        );
1132        assert_eq!(AuthMechanism::Anonymous.implied_attachment_site(), None);
1133    }
1134
1135    #[test]
1136    fn capabilities_implied_site_prefers_default_index() {
1137        // bearer first, cookie second, default = cookie → cookie wins.
1138        let caps = BackendAuthCapabilities::new(vec![bearer(), cookie()], Some(1)).unwrap();
1139        assert_eq!(
1140            caps.implied_attachment_site(),
1141            Some(AttachmentSite::Cookie {
1142                name: CookieName::try_new("plexus_session").unwrap()
1143            })
1144        );
1145    }
1146
1147    #[test]
1148    fn capabilities_implied_site_falls_back_to_first_siteful_mechanism() {
1149        // No default: first mechanism with a site wins (anonymous skipped).
1150        let caps =
1151            BackendAuthCapabilities::new(vec![AuthMechanism::Anonymous, cookie(), bearer()], None)
1152                .unwrap();
1153        assert_eq!(
1154            caps.implied_attachment_site(),
1155            Some(AttachmentSite::Cookie {
1156                name: CookieName::try_new("plexus_session").unwrap()
1157            })
1158        );
1159
1160        // default points at Anonymous (no site) → fall back to first siteful.
1161        let caps =
1162            BackendAuthCapabilities::new(vec![AuthMechanism::Anonymous, bearer()], Some(0))
1163                .unwrap();
1164        assert_eq!(
1165            caps.implied_attachment_site(),
1166            Some(AttachmentSite::Header {
1167                name: HeaderName::try_new("authorization").unwrap()
1168            })
1169        );
1170    }
1171
1172    #[test]
1173    fn capabilities_implied_site_none_for_anonymous_only_and_empty() {
1174        let anon = BackendAuthCapabilities::anonymous_default();
1175        assert_eq!(anon.implied_attachment_site(), None);
1176
1177        let empty = BackendAuthCapabilities::new(vec![], None).unwrap();
1178        assert_eq!(empty.implied_attachment_site(), None);
1179    }
1180}