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