Skip to main content

plexus_auth_core/oidc/
config.rs

1//! Validator configuration: trusted issuer + expected audience (UT-1).
2
3use crate::capabilities::IssuerUrl;
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use std::fmt;
7
8/// Why an `Audience::try_new` rejected its input.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum AudienceError {
11    /// Empty, longer than 256 bytes, or contains non-printable bytes.
12    InvalidShape(String),
13}
14
15impl fmt::Display for AudienceError {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        match self {
18            Self::InvalidShape(s) => {
19                write!(f, "invalid audience {s:?}: must be non-empty printable ASCII, ≤ 256 bytes")
20            }
21        }
22    }
23}
24
25impl std::error::Error for AudienceError {}
26
27/// An OAuth2 / OIDC audience (`aud`) value.
28///
29/// Per UT-S01 D1, the audience is **per-backend** (Auth0 "API identifier"
30/// convention, e.g. `plexus:trak`) so a token minted for one backend
31/// cannot be replayed against another. A deployment that wants one shared
32/// audience configures it explicitly — that is an opt-down, not the
33/// default.
34///
35/// Validated newtype in the style of the capability-advertisement types
36/// (`ClientId`, `CookieName`, ...): public `try_new`, transparent serde,
37/// `JsonSchema` for IR/codegen integration.
38#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
39#[serde(transparent)]
40pub struct Audience(String);
41
42impl Audience {
43    /// Construct an `Audience`. Rules: non-empty, ≤ 256 bytes, printable
44    /// ASCII (no control bytes, no DEL) — the same shape rules as tenant
45    /// identifiers, for the same reason (safe in logs, binds, filenames).
46    pub fn try_new(s: impl Into<String>) -> Result<Self, AudienceError> {
47        let s = s.into();
48        let ok = !s.is_empty() && s.len() <= 256 && !s.bytes().any(|b| b < 0x20 || b == 0x7f);
49        if !ok {
50            return Err(AudienceError::InvalidShape(s));
51        }
52        Ok(Self(s))
53    }
54
55    /// Borrow the inner value as `&str`.
56    pub fn as_str(&self) -> &str {
57        &self.0
58    }
59}
60
61impl fmt::Display for Audience {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        f.write_str(self.as_str())
64    }
65}
66
67/// The claim a provider names a token's audience in (IDENTITY-30).
68#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
69#[serde(rename_all = "snake_case")]
70pub enum AudienceClaim {
71    /// `aud`, as OIDC and Auth0 mint it: the audience is one of its values.
72    #[default]
73    Aud,
74    /// `client_id`, as WorkOS mints its access tokens, which carry no
75    /// `aud`: the audience is the client the token was issued to, and must
76    /// equal it.
77    ClientId,
78}
79
80/// Configuration for an [`OidcValidator`](crate::oidc::OidcValidator).
81///
82/// Names the single trusted issuer and the audience this backend expects
83/// in every token. Multi-issuer federation is deliberately out of scope
84/// (UT-S01 open question 3 — a product decision); the validator type
85/// composes trivially into a set if that lands.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
87pub struct OidcConfig {
88    issuer: IssuerUrl,
89    audience: Audience,
90    /// Where the audience is read from; `aud` unless the provider says
91    /// otherwise.
92    #[serde(default)]
93    audience_claim: AudienceClaim,
94}
95
96impl OidcConfig {
97    /// Build a config from a validated issuer and audience.
98    pub fn new(issuer: IssuerUrl, audience: Audience) -> Self {
99        Self { issuer, audience, audience_claim: AudienceClaim::Aud }
100    }
101
102    /// The same config, reading the audience from `claim`.
103    pub fn with_audience_claim(mut self, claim: AudienceClaim) -> Self {
104        self.audience_claim = claim;
105        self
106    }
107
108    /// The claim the audience is read from.
109    pub fn audience_claim(&self) -> AudienceClaim {
110        self.audience_claim
111    }
112
113    /// The trusted issuer URL.
114    pub fn issuer(&self) -> &IssuerUrl {
115        &self.issuer
116    }
117
118    /// The audience this backend expects in `aud`.
119    pub fn audience(&self) -> &Audience {
120        &self.audience
121    }
122
123    /// The OIDC Discovery URL for the configured issuer:
124    /// `{issuer}/.well-known/openid-configuration` (issuer trailing slash
125    /// normalized away first, per OIDC Discovery §4).
126    pub fn discovery_url(&self) -> url::Url {
127        let base = self.issuer.as_url().as_str().trim_end_matches('/').to_string();
128        url::Url::parse(&format!("{base}/.well-known/openid-configuration"))
129            .expect("issuer URL + well-known suffix is always a valid URL")
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    fn issuer(s: &str) -> IssuerUrl {
138        IssuerUrl::try_new(s.parse().unwrap()).unwrap()
139    }
140
141    #[test]
142    fn audience_accepts_api_identifier_shapes() {
143        Audience::try_new("plexus:trak").unwrap();
144        Audience::try_new("https://api.example.com").unwrap();
145        Audience::try_new("my-api").unwrap();
146    }
147
148    #[test]
149    fn audience_rejects_bad_shapes() {
150        assert!(Audience::try_new("").is_err());
151        assert!(Audience::try_new("a".repeat(257)).is_err());
152        assert!(Audience::try_new("evil\0aud").is_err());
153    }
154
155    #[test]
156    fn discovery_url_normalizes_trailing_slash() {
157        // `Url` normalizes a host-only URL to a trailing slash; the
158        // discovery path must not end up with a double slash.
159        let c = OidcConfig::new(
160            issuer("https://idp.example.com"),
161            Audience::try_new("plexus:trak").unwrap(),
162        );
163        assert_eq!(
164            c.discovery_url().as_str(),
165            "https://idp.example.com/.well-known/openid-configuration"
166        );
167
168        let c2 = OidcConfig::new(
169            issuer("https://idp.example.com/tenant/"),
170            Audience::try_new("plexus:trak").unwrap(),
171        );
172        assert_eq!(
173            c2.discovery_url().as_str(),
174            "https://idp.example.com/tenant/.well-known/openid-configuration"
175        );
176    }
177
178    #[test]
179    fn config_round_trips_serde() {
180        let c = OidcConfig::new(
181            issuer("https://idp.example.com"),
182            Audience::try_new("plexus:trak").unwrap(),
183        );
184        let s = serde_json::to_string(&c).unwrap();
185        let back: OidcConfig = serde_json::from_str(&s).unwrap();
186        assert_eq!(back, c);
187    }
188
189    #[test]
190    fn the_audience_claim_is_aud_unless_said() {
191        let c = OidcConfig::new(issuer("https://idp.example.com"), Audience::try_new("plexus:trak").unwrap());
192        assert_eq!(c.audience_claim(), AudienceClaim::Aud);
193        // a config serialized before IDENTITY-30 reads as `aud`
194        let old: OidcConfig =
195            serde_json::from_str(r#"{"issuer":"https://idp.example.com/","audience":"plexus:trak"}"#).unwrap();
196        assert_eq!(old, c);
197        let w = c.with_audience_claim(AudienceClaim::ClientId);
198        let back: OidcConfig = serde_json::from_str(&serde_json::to_string(&w).unwrap()).unwrap();
199        assert_eq!(back.audience_claim(), AudienceClaim::ClientId);
200    }
201}