Skip to main content

mcp_server_core/
jwt.rs

1//! The server's own tokens: HS256 JWTs signed with `OAUTH_SIGNING_KEY`.
2
3use jsonwebtoken::{
4    Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode, get_current_timestamp,
5};
6use serde::{Deserialize, Serialize};
7use std::time::Duration;
8
9/// Seconds a token is still accepted after its `exp`, for clock skew.
10pub const LEEWAY_SECS: u64 = 5;
11
12/// The subject of tokens the authorization server issues to itself or to clients (client ids and
13/// CSRF tokens), which belong to no person.
14pub const SERVER_SUBJECT: &str = "server";
15
16/// What a token is for, in its `typ` claim; a token of one kind is never accepted as another.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "lowercase")]
19#[non_exhaustive]
20pub enum TokenKind {
21    /// A registered client: the `client_id` itself. Does not expire.
22    Client,
23    /// Binds a sign-in form to its authorization request.
24    Csrf,
25    /// An authorization code, used once.
26    Code,
27    /// An access token for one service.
28    Access,
29    /// A refresh token.
30    Refresh,
31}
32
33/// The claims that depend on the token's kind.
34#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Payload {
36    /// The client a code, access or refresh token was issued to.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub client_id: Option<String>,
39    /// A client's registered redirect URIs.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub redirect_uris: Option<Vec<String>>,
42    /// A client's self-reported name.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub client_name: Option<String>,
45    /// The redirect URI a code was issued for.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub redirect_uri: Option<String>,
48    /// A code's PKCE challenge.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub code_challenge: Option<String>,
51    /// The service granted.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub scope: Option<String>,
54    /// The resource URL granted.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub resource: Option<String>,
57    /// A CSRF token's hash of its authorization request.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub binding: Option<String>,
60    /// The person's credential, sealed by `credential::Sealer` (code, access and refresh tokens).
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub credential: Option<String>,
63    /// The sign-in version (code, access and refresh tokens): it changes when the way people sign
64    /// in changes, such as a new owner's password, which ends every earlier grant. See
65    /// [`AuthState::sign_in_version`](crate::oauth::AuthState::sign_in_version).
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub ver: Option<String>,
68    /// When the person signed in, Unix seconds (code, access and refresh tokens). Kept through
69    /// refreshes, so a grant ends a fixed time after sign-in however often it is refreshed.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub auth_time: Option<u64>,
72}
73
74/// A token's claims. The bearer guard adds an access token's claims to the request extensions.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct Claims {
77    /// Issuer: `PUBLIC_URL`.
78    pub iss: String,
79    /// Audience: a service's resource URL for access tokens, `PUBLIC_URL` otherwise.
80    pub aud: String,
81    /// Subject: who signed in (code, access and refresh tokens), or [`SERVER_SUBJECT`].
82    pub sub: String,
83    /// The token's kind.
84    pub typ: TokenKind,
85    /// Unique id.
86    pub jti: String,
87    /// Issued at, Unix seconds.
88    pub iat: u64,
89    /// Expiry, Unix seconds; client tokens have none.
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub exp: Option<u64>,
92    /// The kind-specific claims.
93    #[serde(flatten)]
94    pub payload: Payload,
95}
96
97/// Why a token was refused.
98#[derive(Debug, thiserror::Error)]
99#[non_exhaustive]
100pub enum JwtError {
101    /// Malformed, badly signed, expired, or for another issuer or audience.
102    #[error("invalid token")]
103    Invalid,
104    /// Valid, but of another [`TokenKind`].
105    #[error("wrong token kind")]
106    WrongKind,
107}
108
109/// A random token id: 128 bits, base64url.
110fn 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
120/// Issues and verifies the server's tokens.
121pub struct Jwt {
122    enc: EncodingKey,
123    dec: DecodingKey,
124    issuer: String,
125    audience: String,
126}
127
128impl Jwt {
129    /// Signs with `secret`, as `issuer`, for the default `audience`.
130    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    /// Issues a token for the default audience (the authorization server itself).
140    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    /// Issues a token whose `aud` is `audience`, with [`SERVER_SUBJECT`] as its subject. Access
150    /// tokens for people come from [`issue_as`](Self::issue_as) with their subject, and need the
151    /// grant's `ver` and `auth_time` in `payload` to be accepted.
152    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    /// Issues a token for `audience` whose subject is `subject`: who signed in.
163    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    /// Whether `token` looks like one this server issued: a JWT whose (unverified) `iss` is this
186    /// server. Such a token is never treated as anything else, even when it fails verification.
187    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    /// Verifies a token issued for the default audience.
208    pub fn verify(&self, token: &str, typ: TokenKind) -> Result<Claims, JwtError> {
209        self.verify_for(token, typ, &self.audience)
210    }
211
212    /// Verifies a token and requires its `aud` to be exactly `audience`.
213    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}