tokenkit 1.0.1

Type-safe JWT encode/decode for Rust with configurable validation, secret rotation, key rotation, and revocation support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// Tests assert invariants directly; unwraps keep failures loud.
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::panic
)]

//! Config-knob behavior matrix: every public `JwtConfig` builder and JWKS
//! cache knob must observably change behavior. Deterministic: no sleeps,
//! no external network (JWKS tests run against a loopback mock).

use serde::{Deserialize, Serialize};
use tokenkit::claims::StandardClaims;
use tokenkit::service::{JwtAlgorithm, JwtConfig, JwtService};

#[derive(Debug, Serialize, Deserialize)]
struct TtlClaims {
    sub: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    exp: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    iss: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    aud: Option<String>,
}

/// Fresh (unstamped) claims: `encode_standard` / `encode_refresh_standard`
/// fill in `exp` from the configured TTL.
fn fresh_claims() -> StandardClaims {
    StandardClaims {
        sub: Some("user-1".to_string()),
        ..Default::default()
    }
}

fn now_secs() -> u64 {
    chrono::Utc::now().timestamp() as u64
}

fn mint_service(ttl_field: &str, ttl: i64) -> JwtService {
    let mut config = JwtConfig {
        algorithm: JwtAlgorithm::HS256,
        secret: format!("config-matrix-{ttl_field}-secret"),
        issuer: Some("config-matrix-issuer".to_string()),
        ..Default::default()
    };
    if ttl_field == "access" {
        config.access_token_ttl = ttl;
    } else {
        config.refresh_token_ttl = ttl;
    }
    JwtService::new(config)
}

/// `access_token_ttl` stamps `exp` ≈ now + access TTL on minted access
/// tokens (claims without an explicit `exp`).
#[test]
fn access_token_ttl_controls_minted_expiry() {
    let service = mint_service("access", 120);
    let token = service.encode_standard(fresh_claims()).unwrap();
    let decoded: TtlClaims = service.decode(&token).unwrap();
    let exp = decoded.exp.expect("encode_standard must stamp exp");
    let now = now_secs();
    assert!(
        (now + 115..=now + 120).contains(&exp),
        "exp {exp} must be ~now+120 (access ttl)"
    );
}

/// `refresh_token_ttl` is wired through `encode_refresh_standard`: it stamps
/// the refresh TTL, not the access TTL — the two knobs are independently
/// observable on the same service.
#[test]
fn refresh_token_ttl_controls_refresh_expiry_and_differs_from_access() {
    // Default refresh TTL is 7 days; access TTL is 1 hour.
    let config = JwtConfig {
        secret: "config-matrix-refresh-default-secret".to_string(),
        issuer: Some("config-matrix-issuer".to_string()),
        ..Default::default()
    };
    let service = JwtService::new(config);
    let claims = fresh_claims();

    let access = service.encode_standard(claims.clone()).unwrap();
    let refresh = service.encode_refresh_standard(claims).unwrap();

    let access_exp: u64 = service
        .decode::<TtlClaims>(&access)
        .unwrap()
        .exp
        .expect("access exp");
    let refresh_exp: u64 = service
        .decode::<TtlClaims>(&refresh)
        .unwrap()
        .exp
        .expect("refresh exp");

    let now = now_secs();
    assert!(
        (now + 3540..=now + 3600).contains(&access_exp),
        "access exp {access_exp} must be ~now+3600"
    );
    assert!(
        (now + 604_780..=now + 604_800).contains(&refresh_exp),
        "refresh exp {refresh_exp} must be ~now+604800"
    );
    assert!(
        refresh_exp - access_exp > 600_000,
        "refresh token must outlive the access token by days, not seconds"
    );

    // A custom refresh TTL is honored exactly.
    let service = mint_service("refresh", 90);
    let token = service
        .encode_refresh_standard(StandardClaims {
            sub: Some("user-2".to_string()),
            ..Default::default()
        })
        .unwrap();
    let decoded: TtlClaims = service.decode(&token).unwrap();
    let exp = decoded.exp.expect("refresh exp");
    let now = now_secs();
    assert!(
        (now + 85..=now + 90).contains(&exp),
        "exp {exp} must be ~now+90 (refresh ttl)"
    );
}

/// `with_audiences`: a token whose `aud` is in the accepted set validates;
/// the same token is rejected when the set does not contain it.
#[test]
fn with_audiences_accepts_listed_and_rejects_unlisted() {
    let claims = TtlClaims {
        sub: Some("user-1".to_string()),
        exp: Some(now_secs() + 3600),
        iss: Some("config-matrix-issuer".to_string()),
        aud: Some("aud-b".to_string()),
    };

    let accepting = JwtService::new(
        JwtConfig {
            secret: "config-matrix-audiences-secret".to_string(),
            issuer: Some("config-matrix-issuer".to_string()),
            ..Default::default()
        }
        .with_audiences(vec!["aud-a".to_string(), "aud-b".to_string()]),
    );
    let ok: TtlClaims = accepting
        .decode(&accepting.encode(&claims).unwrap())
        .unwrap();
    assert_eq!(ok.aud.as_deref(), Some("aud-b"));

    let rejecting = JwtService::new(
        JwtConfig {
            secret: "config-matrix-audiences-secret".to_string(),
            issuer: Some("config-matrix-issuer".to_string()),
            ..Default::default()
        }
        .with_audiences(vec!["aud-a".to_string()]),
    );
    assert!(
        rejecting
            .decode::<TtlClaims>(&rejecting.encode(&claims).unwrap())
            .is_err()
    );
}

// ---------------------------------------------------------------------------
// JWKS knobs (feature "jwks"): with_client, with_min_refresh_interval,
// with_ttl — behavior proven against a loopback mock that counts fetches.
// ---------------------------------------------------------------------------
#[cfg(feature = "jwks")]
mod jwks_config_tests {
    use std::io::{Read, Write};
    use std::net::TcpListener;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    use tokenkit::jwks::JwksCache;

    /// HMAC key: base64url(no pad) of "secret" is "c2VjcmV0". Test-only.
    const JWKS_BODY: &str = r#"{"keys":[{"kty":"oct","k":"c2VjcmV0","kid":"k1","alg":"HS256"}]}"#;

    struct MockJwks {
        url: String,
        fetches: Arc<AtomicUsize>,
        last_request: Arc<std::sync::Mutex<String>>,
    }

    /// Serve `max_requests` sequential JWKS responses on an ephemeral
    /// loopback port, recording the fetch count and last raw request.
    fn spawn_mock_jwks(max_requests: usize) -> MockJwks {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        let fetches = Arc::new(AtomicUsize::new(0));
        let last_request = Arc::new(std::sync::Mutex::new(String::new()));

        let f = Arc::clone(&fetches);
        let lr = Arc::clone(&last_request);
        std::thread::spawn(move || {
            for stream in listener.incoming().take(max_requests) {
                let Ok(mut stream) = stream else { break };
                let mut buf = [0u8; 4096];
                let n = stream.read(&mut buf).unwrap_or(0);
                if let Ok(req) = std::str::from_utf8(&buf[..n]) {
                    *lr.lock().unwrap() = req.to_ascii_lowercase();
                }
                f.fetch_add(1, Ordering::SeqCst);
                let resp = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
                     Content-Length: {}\r\nConnection: close\r\n\r\n{}",
                    JWKS_BODY.len(),
                    JWKS_BODY
                );
                let _ = stream.write_all(resp.as_bytes());
                let _ = stream.flush();
            }
        });

        MockJwks {
            url: format!("http://127.0.0.1:{port}/jwks.json"),
            fetches,
            last_request,
        }
    }

    fn hs256_token(kid: &str) -> String {
        let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256);
        header.kid = Some(kid.to_string());
        jsonwebtoken::encode(
            &header,
            &serde_json::json!({"sub": "u1", "exp": chrono::Utc::now().timestamp() as u64 + 3600}),
            &jsonwebtoken::EncodingKey::from_secret(b"secret"),
        )
        .unwrap()
    }

    fn validation() -> jsonwebtoken::Validation {
        let mut v = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::HS256);
        v.required_spec_claims.clear();
        v
    }

    fn runtime() -> tokio::runtime::Runtime {
        tokio::runtime::Runtime::new().unwrap()
    }

    /// `with_client` must route JWKS fetches through the provided client.
    /// The custom client stamps a probe header; the mock observes it on the
    /// wire — the default client would never send it.
    #[test]
    fn with_client_routes_fetches_through_provided_client() {
        let mock = spawn_mock_jwks(4);
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            "x-probe",
            reqwest::header::HeaderValue::from_static("config-matrix"),
        );
        let client = reqwest::Client::builder()
            .default_headers(headers)
            .build()
            .unwrap();

        let cache = JwksCache::new(mock.url.clone())
            .with_client(client)
            .with_min_refresh_interval(Duration::ZERO);

        let rt = runtime();
        rt.block_on(async {
            let claims: serde_json::Value = cache
                .decode(&hs256_token("k1"), &validation())
                .await
                .unwrap();
            assert_eq!(claims["sub"], "u1");
        });

        assert!(
            mock.fetches.load(Ordering::SeqCst) >= 1,
            "a fetch must have happened"
        );
        let req = mock.last_request.lock().unwrap();
        assert!(
            req.contains("x-probe: config-matrix"),
            "fetch must carry the custom client's probe header, got: {req}"
        );
    }

    /// `with_min_refresh_interval` (default 10s): within the window after a
    /// fetch, on-miss refreshes are SKIPPED (no second fetch). With the
    /// interval at ZERO the very same miss DOES re-fetch — the knob
    /// observably changes refresh behavior.
    #[test]
    fn min_refresh_interval_skips_on_miss_refreshes_within_window() {
        // Default interval: second (unknown-kid) lookup must not re-fetch.
        let mock = spawn_mock_jwks(4);
        let cache = JwksCache::new(mock.url.clone()); // default 10s interval
        let rt = runtime();
        rt.block_on(async {
            let claims: serde_json::Value = cache
                .decode(&hs256_token("k1"), &validation())
                .await
                .unwrap();
            assert_eq!(claims["sub"], "u1");
            assert_eq!(mock.fetches.load(Ordering::SeqCst), 1);

            // Unknown kid, but still inside the min-refresh window: no new
            // fetch — the error must come from the post-skip lookup.
            let err = cache
                .decoding_key(Some("k2"))
                .await
                .expect_err("unknown kid must fail");
            assert!(matches!(err, tokenkit::error::JwtError::Jwks(_)), "{err:?}");
        });
        assert_eq!(
            mock.fetches.load(Ordering::SeqCst),
            1,
            "refresh within the min interval must be skipped"
        );

        // Same miss with a ZERO interval: the refresh must actually happen.
        let mock = spawn_mock_jwks(4);
        let cache = JwksCache::new(mock.url.clone()).with_min_refresh_interval(Duration::ZERO);
        rt.block_on(async {
            let claims: serde_json::Value = cache
                .decode(&hs256_token("k1"), &validation())
                .await
                .unwrap();
            assert_eq!(claims["sub"], "u1");
            let err = cache
                .decoding_key(Some("k2"))
                .await
                .expect_err("unknown kid must fail");
            assert!(matches!(err, tokenkit::error::JwtError::Jwks(_)), "{err:?}");
        });
        assert_eq!(
            mock.fetches.load(Ordering::SeqCst),
            2,
            "ZERO min interval must allow the on-miss refresh"
        );
    }

    /// `with_ttl(ZERO)`: every lookup is stale, so even a cached kid
    /// triggers a re-fetch (rate-limit disabled) — versus the default TTL,
    /// where a second decode of the same kid never fetches.
    #[test]
    fn zero_ttl_refetches_even_cached_kids() {
        let mock = spawn_mock_jwks(4);
        let cache = JwksCache::new(mock.url.clone())
            .with_ttl(Duration::ZERO)
            .with_min_refresh_interval(Duration::ZERO);
        let rt = runtime();
        rt.block_on(async {
            for _ in 0..2 {
                let claims: serde_json::Value = cache
                    .decode(&hs256_token("k1"), &validation())
                    .await
                    .unwrap();
                assert_eq!(claims["sub"], "u1");
            }
        });
        assert_eq!(
            mock.fetches.load(Ordering::SeqCst),
            2,
            "zero TTL must force a refresh on every lookup"
        );
    }
}

// ---------------------------------------------------------------------------
// Revocation knob (feature "revocation"): `with_revocation` must observably
// gate `decode_standard` — a revoked jti is rejected, a live jti passes.
// Previously untested: the fail-closed Redis path had coverage, the happy/
// revoked in-memory paths did not.
// ---------------------------------------------------------------------------
#[cfg(feature = "revocation")]
mod revocation_config_tests {
    use std::collections::HashSet;
    use std::sync::{Arc, Mutex};

    use tokenkit::claims::StandardClaims;
    use tokenkit::error::JwtError;
    use tokenkit::revocation::TokenRevocationStore;
    use tokenkit::service::{JwtAlgorithm, JwtConfig, JwtService};

    /// Minimal shared revocation store so the test can revoke through one
    /// handle while the service holds another.
    #[derive(Default)]
    struct SharedStore {
        revoked: Mutex<HashSet<String>>,
    }

    impl SharedStore {
        fn revoke(&self, jti: &str) {
            self.revoked.lock().unwrap().insert(jti.to_string());
        }
    }

    #[async_trait::async_trait]
    impl TokenRevocationStore for SharedStore {
        async fn revoke(&self, jti: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
            SharedStore::revoke(self, jti);
            Ok(())
        }

        async fn is_revoked(
            &self,
            jti: &str,
        ) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
            Ok(self.revoked.lock().unwrap().contains(jti))
        }
    }

    fn service_with_revocation() -> (Arc<JwtService>, Arc<SharedStore>) {
        let store = Arc::new(SharedStore::default());
        let config = JwtConfig {
            algorithm: JwtAlgorithm::HS256,
            secret: "config-matrix-revocation-secret".to_string(),
            issuer: Some("config-matrix-issuer".to_string()),
            ..Default::default()
        };
        let service = Arc::new(
            JwtService::new(config).with_revocation(Box::new(SharedHandle(Arc::clone(&store)))),
        );
        (service, store)
    }

    /// `Box<dyn TokenRevocationStore>` adapter over the shared handle.
    struct SharedHandle(Arc<SharedStore>);

    #[async_trait::async_trait]
    impl TokenRevocationStore for SharedHandle {
        async fn revoke(&self, jti: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
            self.0.revoke(jti);
            Ok(())
        }

        async fn is_revoked(
            &self,
            jti: &str,
        ) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
            self.0.is_revoked(jti).await
        }
    }

    fn claims_with_jti(jti: Option<&str>) -> StandardClaims {
        use chrono::{Duration, Utc};
        StandardClaims {
            sub: Some("user-1".to_string()),
            iss: Some("config-matrix-issuer".to_string()),
            exp: Some(Utc::now() + Duration::seconds(3600)),
            jti: jti.map(str::to_string),
            ..Default::default()
        }
    }

    /// `with_revocation`: decoding a token whose jti was revoked must fail
    /// with `JwtError::Revoked`; the same service accepts a token whose jti
    /// is not in the store.
    #[test]
    fn with_revocation_rejects_revoked_jti_and_accepts_live_jti() {
        let runtime = tokio::runtime::Runtime::new().unwrap();
        let (service, store) = service_with_revocation();

        let revoked_token = service
            .encode(&claims_with_jti(Some("revoked-jti")))
            .unwrap();
        let live_token = service.encode(&claims_with_jti(Some("live-jti"))).unwrap();

        runtime.block_on(async move {
            // Before revocation both decode.
            service.decode_standard(&live_token).await.unwrap();
            service.decode_standard(&revoked_token).await.unwrap();

            store.revoke("revoked-jti");

            // After revocation: revoked jti fails closed, live jti still passes.
            let err = service
                .decode_standard(&revoked_token)
                .await
                .expect_err("revoked jti must be rejected");
            assert!(matches!(err, JwtError::Revoked), "{err:?}");
            service.decode_standard(&live_token).await.unwrap();
        });
    }

    /// Refresh tokens ride the same revocation path: a revoked refresh
    /// token cannot be decoded (and therefore cannot mint new access tokens).
    #[test]
    fn revoked_refresh_token_is_rejected_via_decode_standard() {
        let runtime = tokio::runtime::Runtime::new().unwrap();
        let (service, store) = service_with_revocation();

        let refresh = service
            .encode(&claims_with_jti(Some("refresh-jti")))
            .unwrap();

        runtime.block_on(async move {
            service.decode_standard(&refresh).await.unwrap();
            store.revoke("refresh-jti");
            let err = service
                .decode_standard(&refresh)
                .await
                .expect_err("revoked");
            assert!(matches!(err, JwtError::Revoked), "{err:?}");
        });
    }

    /// A store attached but a token WITHOUT a jti: the revocation check is
    /// skipped (there is no identifier to look up). Documents the contract:
    /// revocation applies only to tokens carrying a jti — `encode_standard`
    /// and `encode_refresh_standard` always stamp one.
    #[test]
    fn token_without_jti_bypasses_the_store_by_contract() {
        let runtime = tokio::runtime::Runtime::new().unwrap();
        let (service, _store) = service_with_revocation();

        let no_jti = claims_with_jti(None);
        let token = service.encode(&no_jti).unwrap();

        runtime.block_on(async move {
            let claims = service.decode_standard(&token).await.unwrap();
            assert_eq!(claims.jti, None);
        });
    }
}