Skip to main content

seiva_identity/
jwt.rs

1//! An [`Authenticator`] that verifies an OIDC/JWT bearer against a JWKS.
2//!
3//! It verifies with the audited [`jsonwebtoken`] crate (on `ring`): the signing
4//! algorithm is an allowlist of **RS256 and ES256 only** — never a shared-secret
5//! `HS*`, never `alg: none` — and `iss`, `aud`, `exp` and `nbf` are all checked.
6//! A token that fails any step yields no [`Principal`] (ADR 0006).
7//!
8//! Key material is **injected**, not fetched here: the authenticator holds the
9//! [`JwkSet`] by value, so this stays network-free and
10//! deterministically testable. Fetching/rotating the JWKS from the issuer's
11//! `jwks_uri` (and the issuer allowlist that guards against SSRF) belongs to the
12//! wiring layer, not here.
13
14use jsonwebtoken::jwk::JwkSet;
15use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
16use serde_json::Value;
17
18use crate::{AuthError, Authenticator, Principal};
19
20/// The default claim carrying the caller's tenant.
21pub const DEFAULT_TENANT_CLAIM: &str = "tenant";
22/// The default claim carrying the caller's permissions (a JSON array of strings).
23/// When absent, a space-delimited `scope` claim is used instead.
24pub const DEFAULT_PERMISSION_CLAIM: &str = "permissions";
25
26/// The signing algorithms Seiva will verify — asymmetric only. A token header
27/// naming anything else (a shared-secret `HS*`, or `none`) is refused before the
28/// signature is checked, closing the algorithm-confusion hole.
29const ALLOWED_ALGORITHMS: [Algorithm; 2] = [Algorithm::RS256, Algorithm::ES256];
30
31/// Verifies an OIDC/JWT bearer against an injected JWKS and maps its claims to a
32/// [`Principal`].
33///
34/// Build it from the keys and the expected issuer/audience, then (optionally)
35/// point it at the claims that carry the tenant and permissions:
36///
37/// ```no_run
38/// use jsonwebtoken::jwk::JwkSet;
39/// use seiva_identity::JwtAuthenticator;
40///
41/// # fn demo(jwks: JwkSet) {
42/// let auth = JwtAuthenticator::new(jwks, "https://id.example.com/", "seiva-api")
43///     .with_tenant_claim("org_id");
44/// # let _ = auth;
45/// # }
46/// ```
47pub struct JwtAuthenticator {
48    jwks: JwkSet,
49    validation: Validation,
50    tenant_claim: String,
51    permission_claim: String,
52}
53
54impl JwtAuthenticator {
55    /// A verifier for tokens minted by `issuer` for `audience`, trusting the keys
56    /// in `jwks`. Algorithms are fixed to RS256 and ES256; `exp` and `nbf` are
57    /// validated.
58    #[must_use]
59    pub fn new(jwks: JwkSet, issuer: impl Into<String>, audience: impl Into<String>) -> Self {
60        let mut validation = Validation::new(Algorithm::RS256);
61        // A placeholder; the real algorithm is pinned per request to the (allowlisted)
62        // one named in the token header — jsonwebtoken refuses a `from_jwk` key against
63        // a multi-family algorithm list, so the single-alg pin both works and is tighter.
64        validation.algorithms = ALLOWED_ALGORITHMS.to_vec();
65        validation.set_issuer(&[issuer.into()]);
66        validation.set_audience(&[audience.into()]);
67        validation.validate_nbf = true;
68        Self {
69            jwks,
70            validation,
71            tenant_claim: DEFAULT_TENANT_CLAIM.to_string(),
72            permission_claim: DEFAULT_PERMISSION_CLAIM.to_string(),
73        }
74    }
75
76    /// Builds a verifier from the JWKS as a JSON string (the body of a
77    /// `jwks_uri`, or a file a deployment ships), so a caller need not depend on
78    /// `jsonwebtoken` to parse the key set.
79    ///
80    /// # Errors
81    ///
82    /// Returns the [`serde_json::Error`] if `jwks_json` is not a valid JWKS.
83    pub fn from_jwks_json(
84        jwks_json: &str,
85        issuer: impl Into<String>,
86        audience: impl Into<String>,
87    ) -> Result<Self, serde_json::Error> {
88        let jwks: JwkSet = serde_json::from_str(jwks_json)?;
89        Ok(Self::new(jwks, issuer, audience))
90    }
91
92    /// Read the tenant from a different claim (default [`DEFAULT_TENANT_CLAIM`]).
93    #[must_use]
94    pub fn with_tenant_claim(mut self, claim: impl Into<String>) -> Self {
95        self.tenant_claim = claim.into();
96        self
97    }
98
99    /// Read the permissions from a different claim (default
100    /// [`DEFAULT_PERMISSION_CLAIM`]); a space-delimited `scope` is the fallback.
101    #[must_use]
102    pub fn with_permission_claim(mut self, claim: impl Into<String>) -> Self {
103        self.permission_claim = claim.into();
104        self
105    }
106
107    fn permissions_from(&self, claims: &Value) -> std::collections::BTreeSet<String> {
108        if let Some(array) = claims.get(&self.permission_claim).and_then(Value::as_array) {
109            return array
110                .iter()
111                .filter_map(Value::as_str)
112                .map(str::to_string)
113                .collect();
114        }
115        // OIDC convention: a space-delimited `scope` string.
116        if let Some(scope) = claims.get("scope").and_then(Value::as_str) {
117            return scope.split_whitespace().map(str::to_string).collect();
118        }
119        std::collections::BTreeSet::new()
120    }
121}
122
123impl Authenticator for JwtAuthenticator {
124    fn authenticate(&self, bearer: &str) -> Result<Principal, AuthError> {
125        if bearer.is_empty() {
126            return Err(AuthError::MissingCredentials);
127        }
128        // The header names the key (`kid`) and the algorithm; both are checked
129        // against the allowlist and the JWKS before the signature is trusted.
130        let header = decode_header(bearer).map_err(|_| AuthError::InvalidToken)?;
131        if !ALLOWED_ALGORITHMS.contains(&header.alg) {
132            return Err(AuthError::InvalidToken);
133        }
134        let kid = header.kid.ok_or(AuthError::InvalidToken)?;
135        let jwk = self.jwks.find(&kid).ok_or(AuthError::InvalidToken)?;
136        let key = DecodingKey::from_jwk(jwk).map_err(|_| AuthError::InvalidToken)?;
137
138        // Pin verification to the single (allowlisted) algorithm the header names.
139        // A mismatch between it and the JWK's key family (RS/ES confusion) makes
140        // `decode` fail here, so the pin is a tightening, not a trust of the header.
141        let mut validation = self.validation.clone();
142        validation.algorithms = vec![header.alg];
143        let data =
144            decode::<Value>(bearer, &key, &validation).map_err(|_| AuthError::InvalidToken)?;
145        let claims = data.claims;
146
147        let subject = claims
148            .get("sub")
149            .and_then(Value::as_str)
150            .ok_or(AuthError::InvalidToken)?
151            .to_string();
152        let tenant = claims
153            .get(&self.tenant_claim)
154            .and_then(Value::as_str)
155            .map(str::to_string);
156        let permissions = self.permissions_from(&claims);
157
158        Ok(Principal {
159            subject,
160            tenant,
161            permissions,
162        })
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    use jsonwebtoken::{encode, get_current_timestamp, EncodingKey, Header};
170    use serde_json::json;
171
172    const PRIVATE_KEY_PEM: &[u8] = include_bytes!("../tests/fixtures/private_key.pem");
173    const JWKS_JSON: &str = include_str!("../tests/fixtures/jwks.json");
174
175    const ISSUER: &str = "https://id.example.com/";
176    const AUDIENCE: &str = "seiva-api";
177
178    fn jwks() -> JwkSet {
179        serde_json::from_str(JWKS_JSON).expect("the fixture JWKS parses")
180    }
181
182    fn authenticator() -> JwtAuthenticator {
183        JwtAuthenticator::new(jwks(), ISSUER, AUDIENCE)
184    }
185
186    /// Signs `claims` with the fixture RSA key under the matching `kid`.
187    fn sign(alg: Algorithm, kid: Option<&str>, claims: &Value) -> String {
188        let mut header = Header::new(alg);
189        header.kid = kid.map(str::to_string);
190        let key = EncodingKey::from_rsa_pem(PRIVATE_KEY_PEM).expect("fixture key loads");
191        encode(&header, claims, &key).expect("signing succeeds")
192    }
193
194    fn valid_claims() -> Value {
195        json!({
196            "sub": "alice",
197            "iss": ISSUER,
198            "aud": AUDIENCE,
199            "exp": get_current_timestamp() + 3600,
200            "tenant": "acme",
201            "permissions": ["notes.read", "notes.create"],
202        })
203    }
204
205    #[test]
206    fn a_valid_token_maps_claims_to_a_principal() {
207        let token = sign(Algorithm::RS256, Some("test-key-1"), &valid_claims());
208        let p = authenticator().authenticate(&token).expect("valid token");
209        assert_eq!(p.subject, "alice");
210        assert_eq!(p.tenant.as_deref(), Some("acme"));
211        assert!(p.has("notes.read") && p.has("notes.create"));
212    }
213
214    #[test]
215    fn a_tampered_signature_is_rejected() {
216        let token = sign(Algorithm::RS256, Some("test-key-1"), &valid_claims());
217        // Flip the last character of the signature segment.
218        let mut bytes = token.into_bytes();
219        let last = bytes.last_mut().unwrap();
220        *last = if *last == b'A' { b'B' } else { b'A' };
221        let tampered = String::from_utf8(bytes).unwrap();
222        assert_eq!(
223            authenticator().authenticate(&tampered),
224            Err(AuthError::InvalidToken)
225        );
226    }
227
228    #[test]
229    fn the_wrong_audience_is_rejected() {
230        let mut claims = valid_claims();
231        claims["aud"] = json!("someone-else");
232        let token = sign(Algorithm::RS256, Some("test-key-1"), &claims);
233        assert_eq!(
234            authenticator().authenticate(&token),
235            Err(AuthError::InvalidToken)
236        );
237    }
238
239    #[test]
240    fn the_wrong_issuer_is_rejected() {
241        let mut claims = valid_claims();
242        claims["iss"] = json!("https://evil.example/");
243        let token = sign(Algorithm::RS256, Some("test-key-1"), &claims);
244        assert_eq!(
245            authenticator().authenticate(&token),
246            Err(AuthError::InvalidToken)
247        );
248    }
249
250    #[test]
251    fn an_expired_token_is_rejected() {
252        let mut claims = valid_claims();
253        // Well past the default 60s leeway, so it is unambiguously expired.
254        claims["exp"] = json!(get_current_timestamp() - 3600);
255        let token = sign(Algorithm::RS256, Some("test-key-1"), &claims);
256        assert_eq!(
257            authenticator().authenticate(&token),
258            Err(AuthError::InvalidToken)
259        );
260    }
261
262    #[test]
263    fn an_unknown_key_id_is_rejected() {
264        let token = sign(Algorithm::RS256, Some("some-other-kid"), &valid_claims());
265        assert_eq!(
266            authenticator().authenticate(&token),
267            Err(AuthError::InvalidToken)
268        );
269    }
270
271    #[test]
272    fn a_disallowed_algorithm_is_rejected() {
273        // An HS256 token (shared-secret) must be refused: the allowlist is
274        // RS256/ES256, so algorithm confusion never reaches signature checking.
275        let mut header = Header::new(Algorithm::HS256);
276        header.kid = Some("test-key-1".to_string());
277        let token = encode(
278            &header,
279            &valid_claims(),
280            &EncodingKey::from_secret(b"attacker-chosen-secret"),
281        )
282        .unwrap();
283        assert_eq!(
284            authenticator().authenticate(&token),
285            Err(AuthError::InvalidToken)
286        );
287    }
288
289    #[test]
290    fn an_empty_bearer_is_missing_credentials() {
291        assert_eq!(
292            authenticator().authenticate(""),
293            Err(AuthError::MissingCredentials)
294        );
295    }
296
297    #[test]
298    fn permissions_fall_back_to_the_scope_claim() {
299        let mut claims = valid_claims();
300        claims.as_object_mut().unwrap().remove("permissions");
301        claims["scope"] = json!("notes.read notes.delete");
302        let token = sign(Algorithm::RS256, Some("test-key-1"), &claims);
303        let p = authenticator().authenticate(&token).expect("valid");
304        assert!(p.has("notes.read") && p.has("notes.delete"));
305    }
306}