Skip to main content

fastauth_plugin_jwt/
verify.rs

1//! Verifying fastauth JWTs against a JWKS, for resource servers that don't run fastauth.
2//!
3//! Fetch `{base_url}{base_path}/jwks` (`http://localhost:3000/api/auth/jwks`), build a
4//! [`JwksVerifier`] from it, and check each request's token with it. When
5//! [`VerifyError::UnknownKey`] comes back, the auth server has rotated to a key you haven't
6//! seen: fetch the JWKS again and retry once.
7
8use jsonwebtoken::errors::ErrorKind;
9use jsonwebtoken::jwk::{AlgorithmParameters, EllipticCurve, Jwk, JwkSet, KeyAlgorithm};
10use jsonwebtoken::{Algorithm, DecodingKey, Validation};
11use serde::de::DeserializeOwned;
12
13/// Checks a token's signature against a JWKS, then its `exp`, `nbf`, `iss` and `aud`.
14/// Tokens need `exp`, `sub`, `iss` and `aud`, which every token fastauth signs has.
15///
16/// ```
17/// use fastauth_plugin_jwt::verify::JwksVerifier;
18///
19/// # let jwks = r#"{"keys":[]}"#;
20/// // `jwks` is the body of GET /api/auth/jwks.
21/// let verifier = JwksVerifier::from_json(jwks, "https://acme.dk", "https://acme.dk")?;
22/// # Ok::<(), serde_json::Error>(())
23/// ```
24#[derive(Clone, Debug)]
25pub struct JwksVerifier {
26    jwks: JwkSet,
27    issuer: String,
28    audience: String,
29    leeway: u64,
30}
31
32/// Why a token didn't verify.
33#[derive(Debug)]
34pub enum VerifyError {
35    /// The token's `kid` isn't in the JWKS (or it has none). If the kid is new, the server
36    /// rotated keys: fetch the JWKS again.
37    UnknownKey(Option<String>),
38    /// A bad signature, an expired token, the wrong issuer or audience, or not a JWT.
39    Invalid(jsonwebtoken::errors::Error),
40}
41
42impl std::fmt::Display for VerifyError {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        match self {
45            VerifyError::UnknownKey(Some(kid)) => write!(f, "no key with kid {kid} in the JWKS"),
46            VerifyError::UnknownKey(None) => f.write_str("the token has no kid"),
47            VerifyError::Invalid(err) => write!(f, "invalid token: {err}"),
48        }
49    }
50}
51
52impl std::error::Error for VerifyError {
53    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
54        match self {
55            VerifyError::Invalid(err) => Some(err),
56            VerifyError::UnknownKey(_) => None,
57        }
58    }
59}
60
61impl JwksVerifier {
62    /// `issuer` and `audience` are what the auth server signs with: its base URL
63    /// (`https://acme.dk`) unless `Jwt::issuer` or `Jwt::audience` set something else.
64    pub fn new(jwks: JwkSet, issuer: impl Into<String>, audience: impl Into<String>) -> Self {
65        Self {
66            jwks,
67            issuer: issuer.into(),
68            audience: audience.into(),
69            leeway: 0,
70        }
71    }
72
73    /// From the JSON body of `/jwks`.
74    pub fn from_json(
75        jwks: &str,
76        issuer: impl Into<String>,
77        audience: impl Into<String>,
78    ) -> Result<Self, serde_json::Error> {
79        Ok(Self::new(serde_json::from_str(jwks)?, issuer, audience))
80    }
81
82    /// Seconds of clock skew allowed on `exp` and `nbf` (default 0, like Better Auth).
83    pub fn leeway(mut self, seconds: u64) -> Self {
84        self.leeway = seconds;
85        self
86    }
87
88    pub fn jwks(&self) -> &JwkSet {
89        &self.jwks
90    }
91
92    /// The token's claims, once everything checks out. `T` can be
93    /// `serde_json::Map<String, serde_json::Value>` or your own claims struct.
94    pub fn verify<T: DeserializeOwned>(&self, token: &str) -> Result<T, VerifyError> {
95        let header = jsonwebtoken::decode_header(token).map_err(VerifyError::Invalid)?;
96        let jwk = header
97            .kid
98            .as_deref()
99            .and_then(|kid| self.jwks.find(kid))
100            .ok_or_else(|| VerifyError::UnknownKey(header.kid.clone()))?;
101        let alg = algorithm(jwk)
102            .ok_or_else(|| VerifyError::Invalid(ErrorKind::InvalidAlgorithm.into()))?;
103        let key = DecodingKey::from_jwk(jwk).map_err(VerifyError::Invalid)?;
104        let mut validation = Validation::new(alg);
105        validation.leeway = self.leeway;
106        validation.set_issuer(&[&self.issuer]);
107        validation.set_audience(&[&self.audience]);
108        validation.set_required_spec_claims(&["exp", "sub", "iss", "aud"]);
109        jsonwebtoken::decode::<T>(token, &key, &validation)
110            .map(|data| data.claims)
111            .map_err(VerifyError::Invalid)
112    }
113}
114
115/// The algorithm a key signs with: its `alg`, else the one its key type implies.
116fn algorithm(jwk: &Jwk) -> Option<Algorithm> {
117    match (jwk.common.key_algorithm, &jwk.algorithm) {
118        (Some(KeyAlgorithm::EdDSA), AlgorithmParameters::OctetKeyPair(_)) => Some(Algorithm::EdDSA),
119        (Some(KeyAlgorithm::ES256), AlgorithmParameters::EllipticCurve(_)) => {
120            Some(Algorithm::ES256)
121        }
122        (Some(KeyAlgorithm::RS256), AlgorithmParameters::RSA(_)) => Some(Algorithm::RS256),
123        (Some(_), _) => None,
124        (None, AlgorithmParameters::OctetKeyPair(p)) if p.curve == EllipticCurve::Ed25519 => {
125            Some(Algorithm::EdDSA)
126        }
127        (None, AlgorithmParameters::EllipticCurve(p)) if p.curve == EllipticCurve::P256 => {
128            Some(Algorithm::ES256)
129        }
130        (None, AlgorithmParameters::RSA(_)) => Some(Algorithm::RS256),
131        (None, _) => None,
132    }
133}