1use jsonwebtoken::{
4 Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode, get_current_timestamp,
5};
6use serde::{Deserialize, Serialize};
7use std::time::Duration;
8
9pub const LEEWAY_SECS: u64 = 5;
11
12pub const SERVER_SUBJECT: &str = "server";
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "lowercase")]
19#[non_exhaustive]
20pub enum TokenKind {
21 Client,
23 Csrf,
25 Code,
27 Access,
29 Refresh,
31}
32
33#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Payload {
36 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub client_id: Option<String>,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub redirect_uris: Option<Vec<String>>,
42 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub client_name: Option<String>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub redirect_uri: Option<String>,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub code_challenge: Option<String>,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub scope: Option<String>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub resource: Option<String>,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub binding: Option<String>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub credential: Option<String>,
63 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub ver: Option<String>,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub auth_time: Option<u64>,
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct Claims {
77 pub iss: String,
79 pub aud: String,
81 pub sub: String,
83 pub typ: TokenKind,
85 pub jti: String,
87 pub iat: u64,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub exp: Option<u64>,
92 #[serde(flatten)]
94 pub payload: Payload,
95}
96
97#[derive(Debug, thiserror::Error)]
99#[non_exhaustive]
100pub enum JwtError {
101 #[error("invalid token")]
103 Invalid,
104 #[error("wrong token kind")]
106 WrongKind,
107}
108
109fn new_jti() -> Result<String, JwtError> {
111 use base64::Engine as _;
112 use ring::rand::SecureRandom as _;
113 let mut id = [0u8; 16];
114 ring::rand::SystemRandom::new()
115 .fill(&mut id)
116 .map_err(|_| JwtError::Invalid)?;
117 Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(id))
118}
119
120pub struct Jwt {
122 enc: EncodingKey,
123 dec: DecodingKey,
124 issuer: String,
125 audience: String,
126}
127
128impl Jwt {
129 pub fn new(secret: &[u8], issuer: impl Into<String>, audience: impl Into<String>) -> Self {
131 Self {
132 enc: EncodingKey::from_secret(secret),
133 dec: DecodingKey::from_secret(secret),
134 issuer: issuer.into(),
135 audience: audience.into(),
136 }
137 }
138
139 pub fn issue(
141 &self,
142 typ: TokenKind,
143 ttl: Option<Duration>,
144 payload: Payload,
145 ) -> Result<String, JwtError> {
146 self.issue_for(typ, ttl, payload, &self.audience)
147 }
148
149 pub fn issue_for(
153 &self,
154 typ: TokenKind,
155 ttl: Option<Duration>,
156 payload: Payload,
157 audience: &str,
158 ) -> Result<String, JwtError> {
159 self.issue_as(typ, ttl, payload, audience, SERVER_SUBJECT)
160 }
161
162 pub fn issue_as(
164 &self,
165 typ: TokenKind,
166 ttl: Option<Duration>,
167 payload: Payload,
168 audience: &str,
169 subject: &str,
170 ) -> Result<String, JwtError> {
171 let now = get_current_timestamp();
172 let claims = Claims {
173 iss: self.issuer.clone(),
174 aud: audience.to_string(),
175 sub: subject.to_string(),
176 typ,
177 jti: new_jti()?,
178 iat: now,
179 exp: ttl.map(|d| now + d.as_secs()),
180 payload,
181 };
182 encode(&Header::new(Algorithm::HS256), &claims, &self.enc).map_err(|_| JwtError::Invalid)
183 }
184
185 pub fn claims_issuer_here(&self, token: &str) -> bool {
188 use base64::Engine as _;
189 let mut parts = token.split('.');
190 let (Some(_), Some(body), Some(_), None) =
191 (parts.next(), parts.next(), parts.next(), parts.next())
192 else {
193 return false;
194 };
195 base64::engine::general_purpose::URL_SAFE_NO_PAD
196 .decode(body)
197 .ok()
198 .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
199 .and_then(|v| {
200 v.get("iss")
201 .and_then(|i| i.as_str())
202 .map(|i| i == self.issuer)
203 })
204 .unwrap_or(false)
205 }
206
207 pub fn verify(&self, token: &str, typ: TokenKind) -> Result<Claims, JwtError> {
209 self.verify_for(token, typ, &self.audience)
210 }
211
212 pub fn verify_for(
214 &self,
215 token: &str,
216 typ: TokenKind,
217 audience: &str,
218 ) -> Result<Claims, JwtError> {
219 let mut v = Validation::new(Algorithm::HS256);
220 v.set_audience(&[audience]);
221 v.set_issuer(&[&self.issuer]);
222 v.leeway = LEEWAY_SECS;
223 if typ == TokenKind::Client {
224 v.validate_exp = false;
225 v.set_required_spec_claims(&["iss", "aud", "sub"]);
226 } else {
227 v.set_required_spec_claims(&["exp", "iss", "aud", "sub"]);
228 }
229 let claims = decode::<Claims>(token, &self.dec, &v)
230 .map_err(|_| JwtError::Invalid)?
231 .claims;
232 if claims.typ != typ {
233 return Err(JwtError::WrongKind);
234 }
235 Ok(claims)
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242
243 const KEY: &[u8] = b"0123456789abcdef0123456789abcdef";
244
245 fn jwt() -> Jwt {
246 Jwt::new(
247 KEY,
248 "https://mail.example.com",
249 "https://mail.example.com/mcp",
250 )
251 }
252
253 #[test]
254 fn roundtrip_access_token() {
255 let j = jwt();
256 let payload = Payload {
257 client_id: Some("c1".into()),
258 scope: Some("mail".into()),
259 ..Default::default()
260 };
261 let t = j
262 .issue(
263 TokenKind::Access,
264 Some(Duration::from_secs(60)),
265 payload.clone(),
266 )
267 .unwrap();
268 let c = j.verify(&t, TokenKind::Access).unwrap();
269 assert_eq!(c.payload, payload);
270 assert_eq!(c.typ, TokenKind::Access);
271 assert!(c.exp.is_some());
272 }
273
274 #[test]
275 fn every_token_gets_a_fresh_random_id() {
276 let j = jwt();
277 let ids: std::collections::HashSet<String> = (0..100)
278 .map(|_| {
279 let t = j
280 .issue(TokenKind::Client, None, Payload::default())
281 .unwrap();
282 j.verify(&t, TokenKind::Client).unwrap().jti
283 })
284 .collect();
285 assert_eq!(ids.len(), 100);
286 assert!(ids.iter().all(|id| id.len() == 22), "{ids:?}");
287 }
288
289 #[test]
290 fn tokens_carry_their_subject_and_name_their_issuer() {
291 let j = jwt();
292 let t = j
293 .issue_as(
294 TokenKind::Access,
295 Some(Duration::from_secs(60)),
296 Payload::default(),
297 "https://mail.example.com/mcp",
298 "key:0123456789abcdef",
299 )
300 .unwrap();
301 assert_eq!(
302 j.verify(&t, TokenKind::Access).unwrap().sub,
303 "key:0123456789abcdef"
304 );
305 assert!(j.claims_issuer_here(&t));
306 let other = Jwt::new(KEY, "https://other.example.com", "x");
307 let t = other
308 .issue(
309 TokenKind::Access,
310 Some(Duration::from_secs(60)),
311 Payload::default(),
312 )
313 .unwrap();
314 assert!(!j.claims_issuer_here(&t));
315 for junk in ["a.b.c", "", "abc", "a.b.c.d", "eyJ.eyJ.x"] {
316 assert!(!j.claims_issuer_here(junk), "{junk}");
317 }
318 }
319
320 #[test]
321 fn wrong_kind_is_rejected() {
322 let j = jwt();
323 for kind in [TokenKind::Refresh, TokenKind::Code, TokenKind::Csrf] {
324 let t = j
325 .issue(kind, Some(Duration::from_secs(60)), Payload::default())
326 .unwrap();
327 assert!(matches!(
328 j.verify(&t, TokenKind::Access),
329 Err(JwtError::WrongKind)
330 ));
331 }
332 let client = j
333 .issue(TokenKind::Client, None, Payload::default())
334 .unwrap();
335 assert!(j.verify(&client, TokenKind::Access).is_err());
336 }
337
338 #[test]
339 fn client_tokens_have_no_expiry_and_verify() {
340 let j = jwt();
341 let t = j
342 .issue(
343 TokenKind::Client,
344 None,
345 Payload {
346 redirect_uris: Some(vec!["https://a/cb".into()]),
347 ..Default::default()
348 },
349 )
350 .unwrap();
351 let c = j.verify(&t, TokenKind::Client).unwrap();
352 assert_eq!(c.exp, None);
353 }
354
355 #[test]
356 fn non_client_tokens_require_expiry() {
357 let j = jwt();
358 let t = j
359 .issue(TokenKind::Access, None, Payload::default())
360 .unwrap();
361 assert!(j.verify(&t, TokenKind::Access).is_err());
362 }
363
364 #[test]
365 fn expired_token_is_rejected() {
366 let j = jwt();
367 let claims = Claims {
368 iss: "https://mail.example.com".into(),
369 aud: "https://mail.example.com/mcp".into(),
370 sub: SERVER_SUBJECT.into(),
371 typ: TokenKind::Access,
372 jti: "x".into(),
373 iat: get_current_timestamp() - 200,
374 exp: Some(get_current_timestamp() - 100),
375 payload: Payload::default(),
376 };
377 let t = encode(
378 &Header::new(Algorithm::HS256),
379 &claims,
380 &EncodingKey::from_secret(KEY),
381 )
382 .unwrap();
383 assert!(j.verify(&t, TokenKind::Access).is_err());
384 }
385
386 #[test]
387 fn other_audience_is_rejected() {
388 let other = Jwt::new(
389 KEY,
390 "https://mail.example.com",
391 "https://cal.example.com/mcp",
392 );
393 let t = other
394 .issue(
395 TokenKind::Access,
396 Some(Duration::from_secs(60)),
397 Payload::default(),
398 )
399 .unwrap();
400 assert!(jwt().verify(&t, TokenKind::Access).is_err());
401 }
402
403 #[test]
404 fn audience_bound_token_verifies_only_for_that_audience() {
405 let j = jwt();
406 let t = j
407 .issue_for(
408 TokenKind::Access,
409 Some(Duration::from_secs(60)),
410 Payload::default(),
411 "https://mail.example.com/mail",
412 )
413 .unwrap();
414 let c = j
415 .verify_for(&t, TokenKind::Access, "https://mail.example.com/mail")
416 .unwrap();
417 assert_eq!(c.aud, "https://mail.example.com/mail");
418 assert!(
419 j.verify_for(&t, TokenKind::Access, "https://mail.example.com/calendar")
420 .is_err()
421 );
422 assert!(j.verify(&t, TokenKind::Access).is_err());
423 }
424
425 #[test]
426 fn other_issuer_is_rejected() {
427 let other = Jwt::new(
428 KEY,
429 "https://other.example.com",
430 "https://mail.example.com/mcp",
431 );
432 let t = other
433 .issue(
434 TokenKind::Access,
435 Some(Duration::from_secs(60)),
436 Payload::default(),
437 )
438 .unwrap();
439 assert!(jwt().verify(&t, TokenKind::Access).is_err());
440 }
441
442 #[test]
443 fn other_key_is_rejected() {
444 let other = Jwt::new(
445 b"ffffffffffffffffffffffffffffffff",
446 "https://mail.example.com",
447 "https://mail.example.com/mcp",
448 );
449 let t = other
450 .issue(
451 TokenKind::Access,
452 Some(Duration::from_secs(60)),
453 Payload::default(),
454 )
455 .unwrap();
456 assert!(jwt().verify(&t, TokenKind::Access).is_err());
457 }
458
459 #[test]
460 fn token_without_aud_is_rejected() {
461 #[derive(Serialize)]
462 struct NoAud {
463 iss: String,
464 sub: String,
465 typ: TokenKind,
466 jti: String,
467 iat: u64,
468 exp: u64,
469 }
470 let t = encode(
471 &Header::new(Algorithm::HS256),
472 &NoAud {
473 iss: "https://mail.example.com".into(),
474 sub: SERVER_SUBJECT.into(),
475 typ: TokenKind::Access,
476 jti: "x".into(),
477 iat: get_current_timestamp(),
478 exp: get_current_timestamp() + 60,
479 },
480 &EncodingKey::from_secret(KEY),
481 )
482 .unwrap();
483 assert!(jwt().verify(&t, TokenKind::Access).is_err());
484 }
485}