Skip to main content

typesec_integrations/jwt/
authenticator.rs

1//! JWT authenticator that verifies tokens against a JWKS endpoint.
2
3use std::sync::{Arc, RwLock};
4use std::time::Instant;
5
6use jsonwebtoken::{
7    DecodingKey, TokenData, Validation, decode, decode_header,
8    jwk::{Jwk, JwkSet},
9};
10use typesec_core::typestate::{AgentError, Authenticator, Credentials};
11
12use crate::http::{HttpClient, ReqwestHttpClient};
13
14use super::claims::{JwtClaims, VerifiedSubject};
15use super::config::OidcConfig;
16
17/// JWT authenticator that verifies tokens against a JWKS endpoint.
18pub struct JwtAuthenticator {
19    config: OidcConfig,
20    http: Arc<dyn HttpClient>,
21    jwks: RwLock<Option<CachedJwks>>,
22}
23
24#[derive(Clone)]
25struct CachedJwks {
26    keys: JwkSet,
27    fetched_at: Instant,
28}
29
30impl JwtAuthenticator {
31    /// Create an authenticator using the default reqwest HTTP client.
32    pub fn new(config: OidcConfig) -> Self {
33        Self::with_http(config, Arc::new(ReqwestHttpClient::new()))
34    }
35
36    /// Create an authenticator with an injected HTTP client.
37    pub fn with_http(config: OidcConfig, http: Arc<dyn HttpClient>) -> Self {
38        Self {
39            config,
40            http,
41            jwks: RwLock::new(None),
42        }
43    }
44
45    /// Verify a bearer token and return its Typesec subject model.
46    pub fn verify(&self, token: &str) -> Result<VerifiedSubject, JwtAuthError> {
47        let data = self.decode_claims(token)?;
48        if !data.claims.aud.contains(&self.config.audience) {
49            return Err(JwtAuthError::InvalidAudience);
50        }
51        Ok(data.claims.into())
52    }
53
54    fn decode_claims(&self, token: &str) -> Result<TokenData<JwtClaims>, JwtAuthError> {
55        let header = decode_header(token)?;
56        let key = self.resolve_key(header.kid.as_deref())?;
57
58        let mut validation = Validation::new(header.alg);
59        validation.algorithms = self.config.algorithms.clone();
60        validation.set_issuer(&[self.config.issuer.as_str()]);
61        validation.set_audience(&[self.config.audience.as_str()]);
62
63        Ok(decode::<JwtClaims>(
64            token,
65            &DecodingKey::from_jwk(&key)?,
66            &validation,
67        )?)
68    }
69
70    /// Resolve the signing key for a token header.
71    ///
72    /// - With a `kid`: look it up in the cached JWKS; on a miss, re-fetch the
73    ///   JWKS once (the IdP may have rotated keys) before failing.
74    /// - Without a `kid`: only unambiguous key sets are accepted — if the JWKS
75    ///   holds more than one key, the token is rejected rather than verified
76    ///   against an arbitrary key.
77    fn resolve_key(&self, kid: Option<&str>) -> Result<Jwk, JwtAuthError> {
78        let jwks = self.jwks(false)?;
79        match kid {
80            Some(kid) => {
81                if let Some(key) = jwks.find(kid) {
82                    return Ok(key.clone());
83                }
84                // Unknown kid — refresh the JWKS once in case of key rotation.
85                let jwks = self.jwks(true)?;
86                jwks.find(kid).cloned().ok_or(JwtAuthError::MissingKey)
87            }
88            None => match jwks.keys.as_slice() {
89                [only] => Ok(only.clone()),
90                [] => Err(JwtAuthError::MissingKey),
91                _ => Err(JwtAuthError::MissingKid),
92            },
93        }
94    }
95
96    fn jwks(&self, force_refresh: bool) -> Result<JwkSet, JwtAuthError> {
97        if !force_refresh
98            && let Some(cached) = self.jwks.read().expect("jwks lock poisoned").as_ref()
99            && cached.fetched_at.elapsed() < self.config.jwks_ttl
100        {
101            return Ok(cached.keys.clone());
102        }
103
104        let value = self.http.get_json(&self.config.jwks_url, &[])?;
105        let keys: JwkSet = serde_json::from_value(value)?;
106        *self.jwks.write().expect("jwks lock poisoned") = Some(CachedJwks {
107            keys: keys.clone(),
108            fetched_at: Instant::now(),
109        });
110        Ok(keys)
111    }
112}
113
114impl Authenticator for JwtAuthenticator {
115    /// Verify the credential token as a JWT and return the *verified* subject.
116    ///
117    /// If the credentials claim a subject, it must match the token's `sub`
118    /// claim — a caller cannot authenticate as someone else's identity by
119    /// pairing a valid token with a different claimed subject.
120    fn verify_credentials(&self, credentials: &Credentials) -> Result<String, AgentError> {
121        let verified =
122            self.verify(credentials.token.expose())
123                .map_err(|e| AgentError::AuthFailed {
124                    reason: format!("jwt verification failed: {e}"),
125                })?;
126        if !credentials.subject.is_empty() && credentials.subject != verified.subject {
127            return Err(AgentError::AuthFailed {
128                reason: format!(
129                    "claimed subject '{}' does not match verified token subject '{}'",
130                    credentials.subject, verified.subject
131                ),
132            });
133        }
134        Ok(verified.subject)
135    }
136}
137
138/// Errors returned by [`JwtAuthenticator`].
139#[derive(Debug, thiserror::Error)]
140pub enum JwtAuthError {
141    /// Token validation failed.
142    #[error("jwt validation failed: {0}")]
143    Jwt(#[from] jsonwebtoken::errors::Error),
144    /// JWKS fetch failed.
145    #[error("jwks fetch failed: {0}")]
146    Http(#[from] Box<dyn std::error::Error + Send + Sync>),
147    /// JWKS JSON could not be parsed.
148    #[error("jwks parse failed: {0}")]
149    Json(#[from] serde_json::Error),
150    /// No matching signing key was found.
151    #[error("no matching signing key found in JWKS")]
152    MissingKey,
153    /// The token has no `kid` and the JWKS holds multiple keys.
154    #[error("token has no kid but JWKS is ambiguous (multiple keys)")]
155    MissingKid,
156    /// Token audience did not match the configured audience.
157    #[error("token audience did not match expected audience")]
158    InvalidAudience,
159}