1use jsonwebtoken::jwk::JwkSet;
15use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
16use serde_json::Value;
17
18use crate::{AuthError, Authenticator, Principal};
19
20pub const DEFAULT_TENANT_CLAIM: &str = "tenant";
22pub const DEFAULT_PERMISSION_CLAIM: &str = "permissions";
25
26const ALLOWED_ALGORITHMS: [Algorithm; 2] = [Algorithm::RS256, Algorithm::ES256];
30
31pub struct JwtAuthenticator {
48 jwks: JwkSet,
49 validation: Validation,
50 tenant_claim: String,
51 permission_claim: String,
52}
53
54impl JwtAuthenticator {
55 #[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 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 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 #[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 #[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 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 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 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 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 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 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 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}