common-access-token 0.2.7

Implementation of the Common Access Token (CAT) specification
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
//! Tests for Common Access Token

use crate::{
    cat_keys, catm, catr, catreplay, catu, cattprint,
    claims::RegisteredClaims,
    constants::{uri_components, FingerprintType},
    header::{Algorithm, CborValue, KeyId},
    token::{Token, TokenBuilder, VerificationOptions},
    utils::current_timestamp,
};
use ct_codecs::{Base64UrlSafeNoPadding, Decoder, Hex};

use std::collections::BTreeMap;

#[test]
fn test_token_creation_and_verification() {
    let key = b"test-key-for-hmac-sha256-algorithm";

    // Create a token
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("test-key-1"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_subject("subject")
                .with_audience("audience")
                .with_expiration(current_timestamp() + 3600) // 1 hour from now
                .with_not_before(current_timestamp())
                .with_issued_at(current_timestamp())
                .with_cti(b"token-id-1234".to_vec()),
        )
        .custom_string(100, "custom-string-value")
        .custom_binary(101, b"custom-binary-value".to_vec())
        .custom_int(102, 12345)
        .sign(key)
        .expect("Failed to sign token");

    // Encode to bytes
    let token_bytes = token.to_bytes().expect("Failed to encode token");

    // Decode from bytes
    let decoded_token = Token::from_bytes(&token_bytes).expect("Failed to decode token");

    // Verify signature
    decoded_token
        .verify(key)
        .expect("Failed to verify signature");

    // Verify claims
    let options = VerificationOptions::new()
        .verify_exp(true)
        .verify_nbf(true)
        .expected_issuer("issuer")
        .expected_audience("audience");

    decoded_token
        .verify_claims(&options)
        .expect("Failed to verify claims");

    // Check that we can access the claims
    assert_eq!(
        decoded_token.claims.registered.iss,
        Some("issuer".to_string())
    );
    assert_eq!(
        decoded_token.claims.registered.sub,
        Some("subject".to_string())
    );
    assert_eq!(
        decoded_token.claims.registered.aud,
        Some("audience".to_string())
    );

    // Check that custom claims exist
    assert!(
        decoded_token.claims.custom.contains_key(&100),
        "Custom string claim not found"
    );
    assert!(
        decoded_token.claims.custom.contains_key(&101),
        "Custom binary claim not found"
    );
    assert!(
        decoded_token.claims.custom.contains_key(&102),
        "Custom int claim not found"
    );
}

#[test]
fn test_token_with_binary_kid() {
    let key = b"test-key-for-hmac-sha256-algorithm";
    let binary_kid = vec![0x01, 0x02, 0x03, 0x04, 0x05];

    // Create a token with binary key ID
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::binary(binary_kid.clone()))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_expiration(current_timestamp() + 3600),
        )
        .sign(key)
        .expect("Failed to sign token");

    // Encode to bytes
    let token_bytes = token.to_bytes().expect("Failed to encode token");

    // Decode from bytes
    let decoded_token = Token::from_bytes(&token_bytes).expect("Failed to decode token");

    // Check that the key ID was preserved
    if let Some(KeyId::Binary(kid)) = decoded_token.header.key_id() {
        assert_eq!(kid, binary_kid);
    } else {
        panic!("Binary key ID not found or has wrong type");
    }
}

#[test]
fn test_expired_token() {
    let key = b"test-key-for-hmac-sha256-algorithm";

    // Create an expired token
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_expiration(current_timestamp() - 3600), // 1 hour ago
        )
        .sign(key)
        .expect("Failed to sign token");

    // Verify claims should fail with Expired error
    let options = VerificationOptions::new().verify_exp(true);
    let result = token.verify_claims(&options);
    assert!(result.is_err());
    match result {
        Err(crate::Error::Expired) => {} // Expected
        _ => panic!("Expected Expired error"),
    }
}

#[test]
fn test_not_yet_valid_token() {
    let key = b"test-key-for-hmac-sha256-algorithm";

    // Create a token that's not yet valid
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_not_before(current_timestamp() + 3600), // 1 hour from now
        )
        .sign(key)
        .expect("Failed to sign token");

    // Verify claims should fail with NotYetValid error
    let options = VerificationOptions::new().verify_nbf(true);
    let result = token.verify_claims(&options);
    assert!(result.is_err());
    match result {
        Err(crate::Error::NotYetValid) => {} // Expected
        _ => panic!("Expected NotYetValid error"),
    }
}

#[test]
fn test_invalid_signature() {
    let key = b"test-key-for-hmac-sha256-algorithm";
    let wrong_key = b"wrong-key-for-verification";

    // Create a token
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(RegisteredClaims::new().with_issuer("issuer"))
        .sign(key)
        .expect("Failed to sign token");

    // Verify with wrong key should fail
    let result = token.verify(wrong_key);
    assert!(result.is_err());
    match result {
        Err(crate::Error::SignatureVerification) => {} // Expected
        _ => panic!("Expected SignatureVerification error"),
    }
}

#[test]
fn test_nested_map_claims() {
    let key = b"test-key-for-hmac-sha256-algorithm";

    // Create a nested map for testing
    let mut nested_map = BTreeMap::new();
    nested_map.insert(1, CborValue::Text("nested-text".to_string()));
    nested_map.insert(2, CborValue::Integer(42));
    nested_map.insert(3, CborValue::Bytes(vec![1, 2, 3, 4]));

    // Create a token with a nested map claim
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(RegisteredClaims::new().with_issuer("issuer"))
        .custom_map(200, nested_map)
        .sign(key)
        .expect("Failed to sign token");

    // Encode to bytes
    let token_bytes = token.to_bytes().expect("Failed to encode token");

    // Decode from bytes
    let decoded_token = Token::from_bytes(&token_bytes).expect("Failed to decode token");

    // Verify the nested map claim exists
    assert!(
        decoded_token.claims.custom.contains_key(&200),
        "Nested map claim not found"
    );

    // Verify the nested map claim has the correct type
    if let Some(CborValue::Map(map)) = decoded_token.claims.custom.get(&200) {
        assert_eq!(map.len(), 3, "Nested map should have 3 entries");

        // Check nested map values
        if let Some(CborValue::Text(text)) = map.get(&1) {
            assert_eq!(text, "nested-text");
        } else {
            panic!("Expected text value in nested map");
        }

        if let Some(CborValue::Integer(num)) = map.get(&2) {
            assert_eq!(*num, 42);
        } else {
            panic!("Expected integer value in nested map");
        }

        if let Some(CborValue::Bytes(bytes)) = map.get(&3) {
            assert_eq!(bytes, &[1, 2, 3, 4]);
        } else {
            panic!("Expected bytes value in nested map");
        }
    } else {
        panic!("Expected Map value for nested map claim");
    }
}

#[test]
fn test_specific_token_verification() {
    // The token string provided
    let token_str = "2D3RhEOhAQWhBExTeW1tZXRyaWMyNTZYmKQBZ2Nkbm5hbWUCeCxBNXMyRnptNUI5UG5EVEVmS3VybGxMdnJUelJLSWl4ZERsMWI0TEZzZlB3PQQaaIqzLBkBOKIFoQJ4Ji9lMDU5Lzc4MTEvMTY0MC80N2UxLTk5MzAtMmE0MzQxZWE4YjEwBqEBeCUvMWJkMWUyNmUtMzQwNy00ODA1LWI4MDYtMTMyMTZiMzRkNGJmWCBxCao7OrEJkkIQ8DcTNUFB-bMV4vUcVohXksntwc42_w";

    // Convert the token string to bytes
    let token_bytes =
        Base64UrlSafeNoPadding::decode_to_vec(token_str, None).expect("Failed to decode base64");

    // Convert the hex key to bytes
    let key_hex = "746573744b6579"; // "testKey" in hex
    let key = Hex::decode_to_vec(key_hex, None).expect("Failed to decode hex key");

    // Decode the token
    let token = Token::from_bytes(&token_bytes).expect("Failed to decode token");

    // Verify the signature
    token.verify(&key).expect("Failed to verify signature");

    // Check registered claims
    assert_eq!(token.claims.registered.iss, Some("cdnname".to_string()));
    assert_eq!(
        token.claims.registered.sub,
        Some("A5s2Fzm5B9PnDTEfKurllLvrTzRKIixdDl1b4LFsfPw=".to_string())
    );
    assert!(token.claims.registered.exp.is_some());

    // Check custom claims - specifically the nested maps at key 312
    if let Some(CborValue::Map(map_312)) = token.claims.custom.get(&312) {
        // Check path in map 5
        if let Some(CborValue::Map(map_5)) = map_312.get(&5) {
            if let Some(CborValue::Text(path)) = map_5.get(&2) {
                assert_eq!(path, "/e059/7811/1640/47e1-9930-2a4341ea8b10");
            } else {
                panic!("Expected path in map 5 not found or has wrong type");
            }
        } else {
            panic!("Expected map at key 5 not found or has wrong type");
        }

        // Check path in map 6
        if let Some(CborValue::Map(map_6)) = map_312.get(&6) {
            if let Some(CborValue::Text(path)) = map_6.get(&1) {
                assert_eq!(path, "/1bd1e26e-3407-4805-b806-13216b34d4bf");
            } else {
                panic!("Expected path in map 6 not found or has wrong type");
            }
        } else {
            panic!("Expected map at key 6 not found or has wrong type");
        }
    } else {
        panic!("Expected map at key 312 not found or has wrong type");
    }
}

#[test]
fn test_catu_validation() {
    let key = b"test-key-for-hmac-sha256-algorithm";

    // Create a token with CATU claim
    let mut catu_components = BTreeMap::new();

    // Restrict to https scheme
    catu_components.insert(uri_components::SCHEME, catu::exact_match("https"));

    // Restrict to example.com host
    catu_components.insert(uri_components::HOST, catu::suffix_match(".example.com"));

    // Restrict to paths starting with /api
    catu_components.insert(uri_components::PATH, catu::prefix_match("/api"));

    // Create a token with CATU claim
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_expiration(current_timestamp() + 3600),
        )
        .custom_cbor(cat_keys::CATU, catu::create(catu_components))
        .sign(key)
        .expect("Failed to sign token");

    // Test valid URI
    let options = VerificationOptions::new()
        .verify_catu(true)
        .uri("https://api.example.com/api/users");

    assert!(token.verify_claims(&options).is_ok());

    // Test invalid scheme
    let invalid_scheme_options = VerificationOptions::new()
        .verify_catu(true)
        .uri("http://api.example.com/api/users");

    assert!(token.verify_claims(&invalid_scheme_options).is_err());

    // Test invalid host
    let invalid_host_options = VerificationOptions::new()
        .verify_catu(true)
        .uri("https://api.other-domain.com/api/users");

    assert!(token.verify_claims(&invalid_host_options).is_err());

    // Test invalid path
    let invalid_path_options = VerificationOptions::new()
        .verify_catu(true)
        .uri("https://api.example.com/users");

    assert!(token.verify_claims(&invalid_path_options).is_err());
}

#[test]
fn test_catm_validation() {
    let key = b"test-key-for-hmac-sha256-algorithm";

    // Create a token with CATM claim (allow GET and POST only)
    let allowed_methods = vec!["GET", "POST"];

    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_expiration(current_timestamp() + 3600),
        )
        .custom_array(cat_keys::CATM, catm::create(allowed_methods))
        .sign(key)
        .expect("Failed to sign token");

    // Test allowed method (GET)
    let get_options = VerificationOptions::new()
        .verify_catm(true)
        .http_method("GET");

    assert!(token.verify_claims(&get_options).is_ok());

    // Test allowed method (POST)
    let post_options = VerificationOptions::new()
        .verify_catm(true)
        .http_method("POST");

    assert!(token.verify_claims(&post_options).is_ok());

    // Test allowed method with different case
    let get_lowercase_options = VerificationOptions::new()
        .verify_catm(true)
        .http_method("get");

    assert!(token.verify_claims(&get_lowercase_options).is_ok());

    // Test disallowed method
    let put_options = VerificationOptions::new()
        .verify_catm(true)
        .http_method("PUT");

    assert!(token.verify_claims(&put_options).is_err());
}

#[test]
fn test_catreplay_validation() {
    let key = b"test-key-for-hmac-sha256-algorithm";

    // Create a token with CATREPLAY claim (replay prohibited)
    let token_prohibited = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_expiration(current_timestamp() + 3600),
        )
        .custom_cbor(cat_keys::CATREPLAY, catreplay::prohibited())
        .sign(key)
        .expect("Failed to sign token");

    // Test token not seen before (should pass)
    let options_not_seen = VerificationOptions::new()
        .verify_catreplay(true)
        .token_seen_before(false);

    assert!(token_prohibited.verify_claims(&options_not_seen).is_ok());

    // Test token seen before (should fail with replay prohibited)
    let options_seen = VerificationOptions::new()
        .verify_catreplay(true)
        .token_seen_before(true);

    assert!(token_prohibited.verify_claims(&options_seen).is_err());

    // Create a token with CATREPLAY claim (replay permitted)
    let token_permitted = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_expiration(current_timestamp() + 3600),
        )
        .custom_cbor(cat_keys::CATREPLAY, catreplay::permitted())
        .sign(key)
        .expect("Failed to sign token");

    // Test token seen before (should pass with replay permitted)
    assert!(token_permitted.verify_claims(&options_seen).is_ok());
}

#[test]
fn test_catr_token() {
    let key = b"test-key-for-hmac-sha256-algorithm";
    let now = current_timestamp();

    // Create a token with automatic renewal CATR claim
    let renewal_params = catr::automatic_renewal(3600, Some((now + 3000) as i64));

    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_expiration(now + 3600),
        )
        .custom_cbor(cat_keys::CATR, catr::create(renewal_params))
        .sign(key)
        .expect("Failed to sign token");

    // Verify token is valid
    let options = VerificationOptions::new()
        .verify_exp(true)
        .expected_issuer("issuer");

    assert!(token.verify_claims(&options).is_ok());

    // Extract and verify the CATR claim
    if let Some(CborValue::Map(catr_map)) = token.claims.custom.get(&cat_keys::CATR) {
        use crate::constants::renewal_params;

        // Check renewal type
        if let Some(CborValue::Integer(renewal_type)) = catr_map.get(&renewal_params::TYPE) {
            assert_eq!(*renewal_type, 0); // Automatic renewal
        } else {
            panic!("Missing or invalid renewal type");
        }

        // Check expiration extension
        if let Some(CborValue::Integer(exp_add)) = catr_map.get(&renewal_params::EXPADD) {
            assert_eq!(*exp_add, 3600);
        } else {
            panic!("Missing or invalid expiration extension");
        }

        // Check deadline
        if let Some(CborValue::Integer(deadline)) = catr_map.get(&renewal_params::DEADLINE) {
            assert_eq!(*deadline, now as i64 + 3000);
        } else {
            panic!("Missing or invalid deadline");
        }
    } else {
        panic!("Missing or invalid CATR claim");
    }
}

#[test]
fn test_complex_uri_match() {
    let key = b"test-key-for-hmac-sha256-algorithm";

    // Create a complex CATU claim with regex and hash matching
    let mut catu_components = BTreeMap::new();

    // Regex pattern for path (matches /users/<uuid>)
    let user_id_pattern = r"^/users/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
    catu_components.insert(
        uri_components::PATH,
        catu::regex_match(user_id_pattern, vec![]),
    );

    // Create a token with complex CATU claim
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_expiration(current_timestamp() + 3600),
        )
        .custom_cbor(cat_keys::CATU, catu::create(catu_components))
        .sign(key)
        .expect("Failed to sign token");

    // Test matching URI with valid UUID
    let options_valid = VerificationOptions::new()
        .verify_catu(true)
        .uri("https://api.example.com/users/550e8400-e29b-41d4-a716-446655440000");

    assert!(token.verify_claims(&options_valid).is_ok());

    // Test non-matching URI
    let options_invalid = VerificationOptions::new()
        .verify_catu(true)
        .uri("https://api.example.com/users/invalid-id");

    assert!(token.verify_claims(&options_invalid).is_err());
}

#[test]
fn test_mac0_token_verification_with_original_bytes() {
    // Test token from the issue - this is a COSE_Mac0 token with tags 61 and 17
    let token_b64 = "2D3RhEOhAQWhBEd0ZXN0S2lkWOCnAWpwcmltZXZpZGVvAngkNWI4ZWQ2YjItZmNhNC00ZWQ1LTkxNWYtNThjZTFiMGYzMDRiB1gkZjI0ZmIxMDctNDA0MS00MTkxLThkMDktOWMzMzZkNWVjNzAyBRpofDGABBpoirIAGQE4ogahAXgkNGFkZGQ5ZTctZTUzMS00NzIxLTlhNjctYjJlNzQ1OTIyMmJiBaECeCYvZTA1OS83ODExLzE2NDAvNDdlMS05OTMwLTJhNDM0MWVhOGIxMBkBQ6MAAgEZA4QEdVgtUFYtQ0ROLUFjY2Vzcy1Ub2tlblggdBNqM-3RwdEOuIZ2UoF-jDq3z7DvNcjUWSISjCiugR4";

    // Decode the token
    let token_bytes =
        Base64UrlSafeNoPadding::decode_to_vec(token_b64, None).expect("Failed to decode base64");

    // Parse the token
    let token = Token::from_bytes(&token_bytes).expect("Failed to parse token");

    // Verify the token with the correct key
    let key = b"testSecret";
    assert!(
        token.verify(key).is_ok(),
        "Token verification should succeed with testSecret"
    );

    // Verify the token fails with wrong key
    let wrong_key = b"wrongKey";
    assert!(
        token.verify(wrong_key).is_err(),
        "Token verification should fail with wrong key"
    );

    // Verify claims (without expiration check as token might be expired)
    let options = VerificationOptions::new()
        .verify_exp(false)
        .verify_nbf(false);
    assert!(
        token.verify_claims(&options).is_ok(),
        "Claims verification should succeed"
    );

    // Check token properties
    assert_eq!(token.header.algorithm(), Some(Algorithm::HmacSha256));
    assert_eq!(
        token.header.key_id(),
        Some(KeyId::Binary(b"testKid".to_vec()))
    );

    // Check some claims
    assert_eq!(token.claims.registered.iss, Some("primevideo".to_string()));
    assert_eq!(
        token.claims.registered.sub,
        Some("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b".to_string())
    );
}

#[test]
fn test_created_token_format() {
    // Test that tokens created by this library have the correct format
    let key = b"testSecret";

    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(1752100813),
        )
        .sign(key)
        .expect("Failed to sign token");

    // Encode to bytes
    let token_bytes = token.to_bytes().expect("Failed to encode token");

    // Check that it has the correct CBOR tags for HMAC tokens
    assert_eq!(
        token_bytes[0], 0xd8,
        "First byte should be CBOR tag indicator"
    );
    assert_eq!(token_bytes[1], 0x3d, "Should have tag 61 (CWT)");
    assert_eq!(token_bytes[2], 0xd1, "Should have tag 17 (COSE_Mac0)");
    assert_eq!(
        token_bytes[3], 0x84,
        "Should be followed by 4-element array"
    );

    // Verify the token can be decoded and verified
    let decoded = Token::from_bytes(&token_bytes).expect("Failed to decode token");
    decoded.verify(key).expect("Failed to verify token");
}

#[test]
fn test_create_verify_token_with_catu_filename(){
    let key = b"testSecret";
    let expiration = current_timestamp() + 3600;
    // Create a token with CATU filename restriction

    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(expiration),
        )
        .custom_cbor(312, catu::create({
            let mut components = BTreeMap::new();
            components.insert(
                uri_components::FILENAME,
                catu::suffix_match("video_3.mp4"),
            );
            components
        }))
        .sign(key)
        .expect("Failed to sign token");

    // Encode to bytes
    let token_bytes = token.to_bytes().expect("Failed to encode token");

    // Verify the token can be decoded and verified
    let decoded_token = Token::from_bytes(&token_bytes).expect("Failed to decode token");
    decoded_token.verify(key).expect("Failed to verify token");

    // Verify including checking catu with a valid URI
    let options = VerificationOptions::new()
        .verify_exp(true)
        .require_exp(true)
        .verify_catu(true)
        .uri("https://example.com/us-east/title-1234/video_3.mp4");

    token.verify_claims(&options).expect("Failed to verify token claims");
}

#[test]
fn test_create_verify_token_with_catu_parentpath(){
    let key = b"testSecret";
    let expiration = current_timestamp() + 3600;
    // Create a token with CATU filename restriction

    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(expiration),
        )
        .custom_cbor(312, catu::create({
            let mut components = BTreeMap::new();
            components.insert(
                uri_components::PARENT_PATH,
                catu::suffix_match("/us-east/title-1234"),
            );
            components
        }))
        .sign(key)
        .expect("Failed to sign token");

    // Encode to bytes
    let token_bytes = token.to_bytes().expect("Failed to encode token");

    // Verify the token can be decoded and verified
    let decoded_token = Token::from_bytes(&token_bytes).expect("Failed to decode token");
    decoded_token.verify(key).expect("Failed to verify token");

    // Verify including checking catu with a valid URI
    let options = VerificationOptions::new()
        .verify_exp(true)
        .require_exp(true)
        .verify_catu(true)
        .uri("https://example.com/us-east/title-1234/video_3.mp4");

    token.verify_claims(&options).expect("Failed to verify token claims");
}

#[test]
fn test_create_verify_token_with_catu_stem(){
    let key = b"testSecret";
    let expiration = current_timestamp() + 3600;
    // Create a token with CATU filename restriction

    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(expiration),
        )
        .custom_cbor(312, catu::create({
            let mut components = BTreeMap::new();
            components.insert(
                uri_components::STEM,
                catu::suffix_match("video_3"),
            );
            components
        }))
        .sign(key)
        .expect("Failed to sign token");

    // Encode to bytes
    let token_bytes = token.to_bytes().expect("Failed to encode token");

    // Verify the token can be decoded and verified
    let decoded_token = Token::from_bytes(&token_bytes).expect("Failed to decode token");
    decoded_token.verify(key).expect("Failed to verify token");

    // Verify including checking catu with a valid URI
    let options = VerificationOptions::new()
        .verify_exp(true)
        .require_exp(true)
        .verify_catu(true)
        .uri("https://example.com/us-east/title-1234/video_3.mp4");

    token.verify_claims(&options).expect("Failed to verify token claims");
}

#[test]
fn test_catu_filename_mismatch() {
    let key = b"testSecret";
    let expiration = current_timestamp() + 3600;

    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(expiration),
        )
        .custom_cbor(312, catu::create({
            let mut components = BTreeMap::new();
            components.insert(
                uri_components::FILENAME,
                catu::suffix_match("video_3.mp4"),
            );
            components
        }))
        .sign(key)
        .expect("Failed to sign token");

    // Verify with a mismatched filename should fail
    let options = VerificationOptions::new()
        .verify_exp(true)
        .require_exp(true)
        .verify_catu(true)
        .uri("https://example.com/us-east/title-1234/video_5.mp4");

    assert!(token.verify_claims(&options).is_err(), "Should fail with mismatched filename");
}

#[test]
fn test_catu_parentpath_mismatch() {
    let key = b"testSecret";
    let expiration = current_timestamp() + 3600;

    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(expiration),
        )
        .custom_cbor(312, catu::create({
            let mut components = BTreeMap::new();
            components.insert(
                uri_components::PARENT_PATH,
                catu::suffix_match("/us-east/title-1234"),
            );
            components
        }))
        .sign(key)
        .expect("Failed to sign token");

    // Verify with a mismatched parent path should fail
    let options = VerificationOptions::new()
        .verify_exp(true)
        .require_exp(true)
        .verify_catu(true)
        .uri("https://example.com/us-west/title-5678/video_3.mp4");

    assert!(token.verify_claims(&options).is_err(), "Should fail with mismatched parent path");
}

#[test]
fn test_catu_stem_mismatch() {
    let key = b"testSecret";
    let expiration = current_timestamp() + 3600;

    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(expiration),
        )
        .custom_cbor(312, catu::create({
            let mut components = BTreeMap::new();
            components.insert(
                uri_components::STEM,
                catu::suffix_match("video_3"),
            );
            components
        }))
        .sign(key)
        .expect("Failed to sign token");

    // Verify with a mismatched stem should fail
    let options = VerificationOptions::new()
        .verify_exp(true)
        .require_exp(true)
        .verify_catu(true)
        .uri("https://example.com/us-east/title-1234/audio_1.mp4");

    assert!(token.verify_claims(&options).is_err(), "Should fail with mismatched stem");
}

#[test]
fn test_catu_filename_edge_cases() {
    let key = b"testSecret";
    let expiration = current_timestamp() + 3600;

    // Test with filename without extension
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(expiration),
        )
        .custom_cbor(312, catu::create({
            let mut components = BTreeMap::new();
            components.insert(
                uri_components::FILENAME,
                catu::suffix_match("README"),
            );
            components
        }))
        .sign(key)
        .expect("Failed to sign token");

    let options = VerificationOptions::new()
        .verify_exp(true)
        .require_exp(true)
        .verify_catu(true)
        .uri("https://example.com/docs/README");

    token.verify_claims(&options).expect("Should handle filename without extension");
}

#[test]
fn test_catu_stem_edge_cases() {
    let key = b"testSecret";
    let expiration = current_timestamp() + 3600;

    // Test stem with file that has no extension
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(expiration),
        )
        .custom_cbor(312, catu::create({
            let mut components = BTreeMap::new();
            components.insert(
                uri_components::STEM,
                catu::suffix_match("Makefile"),
            );
            components
        }))
        .sign(key)
        .expect("Failed to sign token");

    let options = VerificationOptions::new()
        .verify_exp(true)
        .require_exp(true)
        .verify_catu(true)
        .uri("https://example.com/project/Makefile");

    token.verify_claims(&options).expect("Should handle stem without extension");
}

#[test]
fn test_catu_parentpath_root() {
    let key = b"testSecret";
    let expiration = current_timestamp() + 3600;

    // Test parent path with file at root
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(expiration),
        )
        .custom_cbor(312, catu::create({
            let mut components = BTreeMap::new();
            components.insert(
                uri_components::PARENT_PATH,
                catu::suffix_match(""),
            );
            components
        }))
        .sign(key)
        .expect("Failed to sign token");

    let options = VerificationOptions::new()
        .verify_exp(true)
        .require_exp(true)
        .verify_catu(true)
        .uri("https://example.com/file.txt");

    token.verify_claims(&options).expect("Should handle root-level files with empty parent path");
}

#[test]
fn test_catu_filename_with_multiple_dots() {
    let key = b"testSecret";
    let expiration = current_timestamp() + 3600;

    // Test filename with multiple dots (e.g., archive.tar.gz)
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(expiration),
        )
        .custom_cbor(312, catu::create({
            let mut components = BTreeMap::new();
            components.insert(
                uri_components::FILENAME,
                catu::suffix_match("archive.tar.gz"),
            );
            components
        }))
        .sign(key)
        .expect("Failed to sign token");

    let options = VerificationOptions::new()
        .verify_exp(true)
        .require_exp(true)
        .verify_catu(true)
        .uri("https://example.com/downloads/archive.tar.gz");

    token.verify_claims(&options).expect("Should handle filenames with multiple dots");
}

#[test]
fn test_catu_stem_with_multiple_dots() {
    let key = b"testSecret";
    let expiration = current_timestamp() + 3600;

    // Test stem extraction from filename with multiple dots
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .protected_key_id(KeyId::string("testKid"))
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("fastly")
                .with_subject("5b8ed6b2-fca4-4ed5-915f-58ce1b0f304b")
                .with_expiration(expiration),
        )
        .custom_cbor(312, catu::create({
            let mut components = BTreeMap::new();
            components.insert(
                uri_components::STEM,
                catu::suffix_match("archive.tar"),
            );
            components
        }))
        .sign(key)
        .expect("Failed to sign token");

    let options = VerificationOptions::new()
        .verify_exp(true)
        .require_exp(true)
        .verify_catu(true)
        .uri("https://example.com/downloads/archive.tar.gz");

    token.verify_claims(&options).expect("Should handle stem from filenames with multiple dots");
}

#[test]
fn test_cattprint_token() {
    let key = b"test-key-for-hmac-sha256-algorithm";
    let test_fingerprint_type = FingerprintType::JA4;
    let test_fingerprint_value = "t13d1516h2_8daaf6152771_b186095e22b6";

    // Create a token with CATTPRINT claim
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_expiration(current_timestamp() + 3600),
        )
        .custom_cbor(cat_keys::CATTPRINT, cattprint::create(test_fingerprint_type, test_fingerprint_value))
        .sign(key)
        .expect("Failed to sign token");

    // Extract and verify the CATTPRINT claim
    if let Some(CborValue::Map(cattprint_map)) = token.claims.custom.get(&cat_keys::CATTPRINT) {
        use crate::constants::{tprint_params};

        // Check fingerprint type
        if let Some(CborValue::Integer(fingerprint_type)) = cattprint_map.get(&tprint_params::FINGERPRINT_TYPE) {
            assert_eq!(*fingerprint_type, test_fingerprint_type as i64);
        } else {
            panic!("Missing or invalid fingerprint type");
        }

        // Check fingerprint value
        if let Some(CborValue::Text(fingerprint_value)) = cattprint_map.get(&tprint_params::FINGERPRINT_VALUE) {
            assert_eq!(*fingerprint_value, test_fingerprint_value);
        } else {
            panic!("Missing or invalid fingerprint value");
        }
    } else {
        panic!("Missing or invalid CATTPRINT claim");
    }

    // Test valid TLS Fingerprint
    let options = VerificationOptions::new()
        .verify_cattprint(true)
        .fingerprint_type(test_fingerprint_type)
        .fingerprint_value(test_fingerprint_value);

    assert!(token.verify_claims(&options).is_ok());
}

#[test]
fn test_cattprint_token_fingerprint_type_not_match() {
    let key = b"test-key-for-hmac-sha256-algorithm";
    let test_fingerprint_type = FingerprintType::JA4;
    let test_fingerprint_value = "t13d1516h2_8daaf6152771_b186095e22b6";

    // Create a token with CATTPRINT claim
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_expiration(current_timestamp() + 3600),
        )
        .custom_cbor(cat_keys::CATTPRINT, cattprint::create(test_fingerprint_type, test_fingerprint_value))
        .sign(key)
        .expect("Failed to sign token");

    // Extract and verify the CATTPRINT claim
    if let Some(CborValue::Map(cattprint_map)) = token.claims.custom.get(&cat_keys::CATTPRINT) {
        use crate::constants::{tprint_params};

        // Check fingerprint type
        if let Some(CborValue::Integer(fingerprint_type)) = cattprint_map.get(&tprint_params::FINGERPRINT_TYPE) {
            assert_eq!(*fingerprint_type, test_fingerprint_type as i64);
        } else {
            panic!("Missing or invalid fingerprint type");
        }

        // Check fingerprint value
        if let Some(CborValue::Text(fingerprint_value)) = cattprint_map.get(&tprint_params::FINGERPRINT_VALUE) {
            assert_eq!(*fingerprint_value, test_fingerprint_value);
        } else {
            panic!("Missing or invalid fingerprint value");
        }
    } else {
        panic!("Missing or invalid CATTPRINT claim");
    }

    // Test valid TLS Fingerprint
    let options = VerificationOptions::new()
        .verify_cattprint(true)
        .fingerprint_type(FingerprintType::JA3)
        .fingerprint_value(test_fingerprint_value);

    let result = token.verify_claims(&options);
    assert!(result.is_err(), "Expected error due to fingerprint type mismatch");
    match result {
        Err(crate::Error::InvalidTLSFingerprintClaim(msg)) => {
            assert_eq!(
                msg,
                "TLS Fingerprint Type 'JA4' does not match required value 'JA3'",
                "Error message does not match expected value"
            );
        } // Expected
        _ => panic!("Expected InvalidTLSFingerprintClaim error"),
    }
}

#[test]
fn test_cattprint_token_fingerprint_value_not_match() {
    let key = b"test-key-for-hmac-sha256-algorithm";
    let test_fingerprint_type = FingerprintType::JA4;
    let test_fingerprint_value = "t13d1516h2_8daaf6152771_b186095e22b6";

    // Create a token with CATTPRINT claim
    let token = TokenBuilder::new()
        .algorithm(Algorithm::HmacSha256)
        .registered_claims(
            RegisteredClaims::new()
                .with_issuer("issuer")
                .with_expiration(current_timestamp() + 3600),
        )
        .custom_cbor(cat_keys::CATTPRINT, cattprint::create(test_fingerprint_type, test_fingerprint_value))
        .sign(key)
        .expect("Failed to sign token");

    // Extract and verify the CATTPRINT claim
    if let Some(CborValue::Map(cattprint_map)) = token.claims.custom.get(&cat_keys::CATTPRINT) {
        use crate::constants::{tprint_params};

        // Check fingerprint type
        if let Some(CborValue::Integer(fingerprint_type)) = cattprint_map.get(&tprint_params::FINGERPRINT_TYPE) {
            assert_eq!(*fingerprint_type, test_fingerprint_type as i64);
        } else {
            panic!("Missing or invalid fingerprint type");
        }

        // Check fingerprint value
        if let Some(CborValue::Text(fingerprint_value)) = cattprint_map.get(&tprint_params::FINGERPRINT_VALUE) {
            assert_eq!(*fingerprint_value, test_fingerprint_value);
        } else {
            panic!("Missing or invalid fingerprint value");
        }
    } else {
        panic!("Missing or invalid CATTPRINT claim");
    }

    // Test valid TLS Fingerprint
    let test_fingerprint_value_not_match = "t65a1516h2_8daaf6152771_b186095e22d3";
    let options = VerificationOptions::new()
        .verify_cattprint(true)
        .fingerprint_type(test_fingerprint_type)
        .fingerprint_value(test_fingerprint_value_not_match);

    let result = token.verify_claims(&options);
    assert!(result.is_err(), "Expected error due to fingerprint type mismatch");
    match result {
        Err(crate::Error::InvalidTLSFingerprintClaim(msg)) => {
            assert_eq!(
                msg,
                "TLS Fingerprint Value 't13d1516h2_8daaf6152771_b186095e22b6' does not match required value 't65a1516h2_8daaf6152771_b186095e22d3'",
                "Error message does not match expected value"
            );
        } // Expected
        _ => panic!("Expected InvalidTLSFingerprintClaim error"),
    }
}