jwt-verify 0.1.0

JWT verification library for AWS Cognito tokens and any OIDC-compatible IDP
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
use base64::Engine;
use jwt_verify::{CognitoJwtVerifier, JwtError, JwtVerifier, VerifierConfig};
use std::time::{SystemTime, UNIX_EPOCH};

// Helper function to create a test token
fn create_test_token(header: &str, payload: &str, signature: &str) -> String {
    format!("{}.{}.{}", header, payload, signature)
}

// Helper function to create a base64 encoded string
fn base64_encode(data: &str) -> String {
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(data)
}

// Helper function to get current timestamp
fn current_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

// Helper function to create a test ID token
fn create_test_id_token(issuer: &str, kid: &str, exp_offset: i64) -> String {
    let now = current_timestamp();
    let exp = now + exp_offset as u64;

    let header = base64_encode(&format!(r#"{{"alg":"RS256","kid":"{}","typ":"JWT"}}"#, kid));
    let payload = base64_encode(&format!(
        r#"{{
        "sub": "test-user-id",
        "iss": "{}",
        "client_id": "test-client-id",
        "token_use": "id",
        "auth_time": {},
        "exp": {},
        "iat": {},
        "jti": "test-jwt-id",
        "email": "test@example.com",
        "email_verified": true,
        "cognito:username": "testuser",
        "aud": "test-client-id"
    }}"#,
        issuer,
        now - 300,
        exp,
        now
    ));

    // For testing purposes, we use a dummy signature
    let signature = "test-signature";

    create_test_token(&header, &payload, signature)
}

// Helper function to create a tampered token with modified payload
fn create_tampered_token(issuer: &str, kid: &str, tamper_type: &str) -> String {
    let now = current_timestamp();
    let exp = now + 3600;

    let header = base64_encode(&format!(r#"{{"alg":"RS256","kid":"{}","typ":"JWT"}}"#, kid));
    
    // Create different tampered payloads based on the tamper type
    let payload = match tamper_type {
        "modified_sub" => base64_encode(&format!(
            r#"{{
            "sub": "hacker-user-id",
            "iss": "{}",
            "client_id": "test-client-id",
            "token_use": "id",
            "auth_time": {},
            "exp": {},
            "iat": {},
            "jti": "test-jwt-id",
            "email": "test@example.com"
        }}"#,
            issuer,
            now - 300,
            exp,
            now
        )),
        "elevated_permissions" => base64_encode(&format!(
            r#"{{
            "sub": "test-user-id",
            "iss": "{}",
            "client_id": "test-client-id",
            "token_use": "id",
            "auth_time": {},
            "exp": {},
            "iat": {},
            "jti": "test-jwt-id",
            "email": "test@example.com",
            "cognito:groups": ["admin", "superuser"]
        }}"#,
            issuer,
            now - 300,
            exp,
            now
        )),
        "modified_iat" => base64_encode(&format!(
            r#"{{
            "sub": "test-user-id",
            "iss": "{}",
            "client_id": "test-client-id",
            "token_use": "id",
            "auth_time": {},
            "exp": {},
            "iat": {},
            "jti": "test-jwt-id",
            "email": "test@example.com"
        }}"#,
            issuer,
            now - 300,
            exp,
            now - 86400 // Set issued at to 24 hours ago
        )),
        _ => base64_encode(&format!(
            r#"{{
            "sub": "test-user-id",
            "iss": "{}",
            "client_id": "test-client-id",
            "token_use": "id",
            "auth_time": {},
            "exp": {},
            "iat": {},
            "jti": "test-jwt-id",
            "email": "test@example.com"
        }}"#,
            issuer,
            now - 300,
            exp,
            now
        )),
    };

    // Original signature from a valid token
    let signature = "test-signature";

    create_test_token(&header, &payload, signature)
}

// Helper function to create a token with none algorithm (algorithm stripping attack)
fn create_none_algorithm_token(issuer: &str) -> String {
    let now = current_timestamp();
    let exp = now + 3600;

    // Use "none" algorithm in header
    let header = base64_encode(r#"{"alg":"none","typ":"JWT"}"#);
    
    let payload = base64_encode(&format!(
        r#"{{
        "sub": "test-user-id",
        "iss": "{}",
        "client_id": "test-client-id",
        "token_use": "id",
        "auth_time": {},
        "exp": {},
        "iat": {},
        "jti": "test-jwt-id",
        "email": "test@example.com",
        "cognito:groups": ["admin"]
    }}"#,
        issuer,
        now - 300,
        exp,
        now
    ));

    // Empty signature for "none" algorithm
    let signature = "";

    create_test_token(&header, &payload, signature)
}

// Helper function to create a token with invalid signature
fn create_invalid_signature_token(issuer: &str, kid: &str) -> String {
    let now = current_timestamp();
    let exp = now + 3600;

    let header = base64_encode(&format!(r#"{{"alg":"RS256","kid":"{}","typ":"JWT"}}"#, kid));
    let payload = base64_encode(&format!(
        r#"{{
        "sub": "test-user-id",
        "iss": "{}",
        "client_id": "test-client-id",
        "token_use": "id",
        "auth_time": {},
        "exp": {},
        "iat": {},
        "jti": "test-jwt-id",
        "email": "test@example.com"
    }}"#,
        issuer,
        now - 300,
        exp,
        now
    ));

    // Invalid signature
    let signature = "invalid-signature";

    create_test_token(&header, &payload, signature)
}

// Helper function to create an expired token
fn create_expired_token(issuer: &str, kid: &str, expired_seconds_ago: u64) -> String {
    let now = current_timestamp();
    let exp = now - expired_seconds_ago; // Token expired in the past

    let header = base64_encode(&format!(r#"{{"alg":"RS256","kid":"{}","typ":"JWT"}}"#, kid));
    let payload = base64_encode(&format!(
        r#"{{
        "sub": "test-user-id",
        "iss": "{}",
        "client_id": "test-client-id",
        "token_use": "id",
        "auth_time": {},
        "exp": {},
        "iat": {},
        "jti": "test-jwt-id",
        "email": "test@example.com"
    }}"#,
        issuer,
        now - expired_seconds_ago - 3600, // Auth time is before expiration
        exp,
        now - expired_seconds_ago - 3600  // Issued at is before expiration
    ));

    // For testing purposes, we use a dummy signature
    let signature = "test-signature";

    create_test_token(&header, &payload, signature)
}

// Helper function to create a token with wrong issuer
fn create_wrong_issuer_token(kid: &str) -> String {
    let now = current_timestamp();
    let exp = now + 3600;

    let header = base64_encode(&format!(r#"{{"alg":"RS256","kid":"{}","typ":"JWT"}}"#, kid));
    let payload = base64_encode(&format!(
        r#"{{
        "sub": "test-user-id",
        "iss": "https://wrong-issuer.com",
        "client_id": "test-client-id",
        "token_use": "id",
        "auth_time": {},
        "exp": {},
        "iat": {},
        "jti": "test-jwt-id",
        "email": "test@example.com"
    }}"#,
        now - 300,
        exp,
        now
    ));

    // For testing purposes, we use a dummy signature
    let signature = "test-signature";

    create_test_token(&header, &payload, signature)
}

// Helper function to create a token with future issued at time (clock manipulation attack)
fn create_future_iat_token(issuer: &str, kid: &str, seconds_in_future: u64) -> String {
    let now = current_timestamp();
    let future_time = now + seconds_in_future;
    let exp = future_time + 3600;

    let header = base64_encode(&format!(r#"{{"alg":"RS256","kid":"{}","typ":"JWT"}}"#, kid));
    let payload = base64_encode(&format!(
        r#"{{
        "sub": "test-user-id",
        "iss": "{}",
        "client_id": "test-client-id",
        "token_use": "id",
        "auth_time": {},
        "exp": {},
        "iat": {},
        "jti": "test-jwt-id",
        "email": "test@example.com"
    }}"#,
        issuer,
        future_time,
        exp,
        future_time
    ));

    // For testing purposes, we use a dummy signature
    let signature = "test-signature";

    create_test_token(&header, &payload, signature)
}

#[tokio::test]
async fn test_tampered_tokens() {
    // Create a verifier config
    let config = VerifierConfig::new(
        "us-east-1",
        "us-east-1_example",
        &["test-client-id".to_string()],
        None,
    )
    .unwrap();

    // Create a verifier
    let verifier = CognitoJwtVerifier::new(vec![config]).unwrap();

    // Create issuer
    let issuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example";
    
    // Test with tampered subject
    let tampered_sub_token = create_tampered_token(issuer, "test-key-1", "modified_sub");
    let result = verifier.verify_id_token(&tampered_sub_token).await;
    assert!(result.is_err());
    
    // Test with elevated permissions
    let elevated_perms_token = create_tampered_token(issuer, "test-key-1", "elevated_permissions");
    let result = verifier.verify_id_token(&elevated_perms_token).await;
    assert!(result.is_err());
    
    // Test with modified issued-at time
    let modified_iat_token = create_tampered_token(issuer, "test-key-1", "modified_iat");
    let result = verifier.verify_id_token(&modified_iat_token).await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_none_algorithm_attack() {
    // Create a verifier config
    let config = VerifierConfig::new(
        "us-east-1",
        "us-east-1_example",
        &["test-client-id".to_string()],
        None,
    )
    .unwrap();

    // Create a verifier
    let verifier = CognitoJwtVerifier::new(vec![config]).unwrap();

    // Create issuer
    let issuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example";
    
    // Test with none algorithm
    let none_alg_token = create_none_algorithm_token(issuer);
    let result = verifier.verify_id_token(&none_alg_token).await;
    assert!(result.is_err());
    
    // The error should be related to invalid algorithm or parsing
    match result.unwrap_err() {
        JwtError::InvalidClaim { claim, .. } => {
            assert_eq!(claim, "alg");
        },
        JwtError::ParseError { .. } => {
            // This is also acceptable
        },
        err => panic!("Expected InvalidClaim or ParseError, got: {:?}", err),
    }
}

#[tokio::test]
async fn test_invalid_signature() {
    // Create a verifier config
    let config = VerifierConfig::new(
        "us-east-1",
        "us-east-1_example",
        &["test-client-id".to_string()],
        None,
    )
    .unwrap();

    // Create a verifier
    let verifier = CognitoJwtVerifier::new(vec![config]).unwrap();

    // Create issuer
    let issuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example";
    
    // Test with invalid signature
    let invalid_sig_token = create_invalid_signature_token(issuer, "test-key-1");
    let result = verifier.verify_id_token(&invalid_sig_token).await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_expired_tokens() {
    // Create a verifier config
    let config = VerifierConfig::new(
        "us-east-1",
        "us-east-1_example",
        &["test-client-id".to_string()],
        None,
    )
    .unwrap();

    // Create a verifier
    let verifier = CognitoJwtVerifier::new(vec![config]).unwrap();

    // Create issuer
    let issuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example";
    
    // Test with token expired 1 hour ago
    let expired_token = create_expired_token(issuer, "test-key-1", 3600);
    let result = verifier.verify_id_token(&expired_token).await;
    assert!(result.is_err());
    
    // Test with token expired just now (1 second ago)
    let just_expired_token = create_expired_token(issuer, "test-key-1", 1);
    let result = verifier.verify_id_token(&just_expired_token).await;
    assert!(result.is_err());
    
    // Test with token expired long ago (1 year)
    let long_expired_token = create_expired_token(issuer, "test-key-1", 31536000); // 365 days
    let result = verifier.verify_id_token(&long_expired_token).await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_wrong_issuer() {
    // Create a verifier config
    let config = VerifierConfig::new(
        "us-east-1",
        "us-east-1_example",
        &["test-client-id".to_string()],
        None,
    )
    .unwrap();

    // Create a verifier
    let verifier = CognitoJwtVerifier::new(vec![config]).unwrap();
    
    // Test with wrong issuer
    let wrong_issuer_token = create_wrong_issuer_token("test-key-1");
    let result = verifier.verify_id_token(&wrong_issuer_token).await;
    assert!(result.is_err());
    
    // The error should be related to configuration (issuer not found)
    match result.unwrap_err() {
        JwtError::ConfigurationError { parameter, .. } => {
            assert_eq!(parameter, Some("issuer".to_string()));
        },
        err => panic!("Expected ConfigurationError, got: {:?}", err),
    }
}

#[tokio::test]
async fn test_future_issued_at() {
    // Create a verifier config
    let config = VerifierConfig::new(
        "us-east-1",
        "us-east-1_example",
        &["test-client-id".to_string()],
        None,
    )
    .unwrap();

    // Create a verifier
    let verifier = CognitoJwtVerifier::new(vec![config]).unwrap();

    // Create issuer
    let issuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example";
    
    // Test with token issued 1 hour in the future (clock manipulation attack)
    let future_token = create_future_iat_token(issuer, "test-key-1", 3600);
    let result = verifier.verify_id_token(&future_token).await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_cross_pool_token_rejection() {
    // Create verifier configs for two different user pools
    let config1 = VerifierConfig::new(
        "us-east-1",
        "us-east-1_pool1",
        &["client-id-1".to_string()],
        None,
    )
    .unwrap();
    
    let config2 = VerifierConfig::new(
        "us-west-2",
        "us-west-2_pool2",
        &["client-id-2".to_string()],
        None,
    )
    .unwrap();

    // Create a verifier with both pools
    let verifier = CognitoJwtVerifier::new(vec![config1, config2]).unwrap();

    // Create issuers for both pools
    let issuer1 = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_pool1";
    let issuer2 = "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_pool2";
    
    // Create tokens for both pools
    let token1 = create_test_id_token(issuer1, "test-key-1", 3600);
    let token2 = create_test_id_token(issuer2, "test-key-1", 3600);
    
    // Try to verify token1 with pool2's issuer (should fail)
    let modified_token1 = token1.replace(issuer1, issuer2);
    let result = verifier.verify_id_token(&modified_token1).await;
    assert!(result.is_err());
    
    // Try to verify token2 with pool1's issuer (should fail)
    let modified_token2 = token2.replace(issuer2, issuer1);
    let result = verifier.verify_id_token(&modified_token2).await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_token_replay_detection() {
    // This test is more conceptual since we don't have a real implementation of replay detection
    // In a real system, you would check if the token has been used before
    
    // Create a verifier config
    let config = VerifierConfig::new(
        "us-east-1",
        "us-east-1_example",
        &["test-client-id".to_string()],
        None,
    )
    .unwrap();

    // Create a verifier
    let verifier = CognitoJwtVerifier::new(vec![config]).unwrap();

    // Create issuer
    let issuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example";
    
    // Create a token
    let token = create_test_id_token(issuer, "test-key-1", 3600);
    
    // First verification should fail due to signature/key issues, but not due to replay
    let result1 = verifier.verify_id_token(&token).await;
    assert!(result1.is_err());
    
    // Second verification should also fail for the same reason
    let result2 = verifier.verify_id_token(&token).await;
    assert!(result2.is_err());
    
    // In a real implementation with replay detection, the second verification would fail
    // with a specific error indicating that the token has been used before
}