polyjose 0.2.0

Pure-Rust JOSE: JWA, JWK, JWS, JWE and JWT per the RFCs, with no OpenSSL
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
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
//! 0004 T09: nested JWTs, a signed JWT encrypted as a compact JWE
//! (RFC 7519 §5.2, §7.1 step 5, §7.2 step 8, §11.2; RFC 8725 §3.3, §3.11;
//! ADR 0027 §7, §9), through the public API only (ADR 0008 layer 2).
//!
//! - Decrypt-then-verify across the JWE key management modes, with an
//!   ES256 or EdDSA inner JWS, and RSA-OAEP-256 around an RS256 or EdDSA
//!   inner JWS with the RFC 7515 A.2 RSA private key (ADR 0067).
//! - Both layers validated with the caller's keys and algorithms
//!   (RFC 8725 §3.3).
//! - The shape and typing rules (ADR 0027 §6–§7): outer `cty`, depth 1,
//!   separate entry points, explicit typing on the inner JWS.
//! - Replicated claims (RFC 7519 §5.3) and the ADR 0027 §9 precedence.
//! - The outer typing read from the JWE Protected Header only, and the
//!   compact-only shape (ADR 0050 §3, ADR 0049 §2).
//! - No part of the decrypted inner token in `Debug` or errors
//!   (ADR 0049 §4).
//!
//! Time comes only from `FixedClock`; no test reads the wall clock
//! (pipeline rule 8). PBES2 tokens use a small `p2c`, inside the default
//! decrypt budget (ADR 0023, ADR 0050 §2). The RSA private key is the
//! RFC 7515 A.2 fixture under `tests/data/keys/rfc/` (ADR 0067).

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] // test code: a panic is a failed assertion

mod common;

use polyjose::Error;
use polyjose::header::Header;
use polyjose::jwa::{ContentEncAlg, KeyMgmtAlg, SigningAlg};
use polyjose::jwe::{DecryptPolicy, Encryptor, JsonForm, Recipient};
use polyjose::jwk::{EcCurve, Jwk, OkpCurve};
use polyjose::jws::{ProtectedHeader, SignOptions, sign_compact};
use polyjose::jwt::{
    self, Audience, Claims, FixedClock, IssueOptions, Keys, NumericDate, Policy, VerifiedNestedJwt,
};
use polyjose::keys::{KeySpec, generate};
use polyjose::util::{b64url_decode, b64url_encode};

use ContentEncAlg as E;
use KeyMgmtAlg as A;

// ---------------------------------------------------------------------------
// Test data. Every private key here is published test data or generated
// per run.
// ---------------------------------------------------------------------------

/// RFC 7515 Appendix A.3.1: the P-256 key (the inner ES256 signer).
const P256: &str = r#"{"kty":"EC","crv":"P-256","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0","d":"jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI"}"#;
/// RFC 7520 §5.8.1: the A128KW key-encryption key.
const KEK: &str = r#"{"kty":"oct","k":"GZy6sIZ6wl9NJOKB-jnmVQ"}"#;
/// RFC 7520 §5.3.1: the PBES2 password.
const PASSWORD: &[u8] = b"entrap_o\xe2\x80\x93peter_long\xe2\x80\x93credit_tun";
/// RFC 7515 Appendix A.2.1's 2048-bit RSA key, public members only.
const RSA_PUBLIC: &str = r#"{"kty":"RSA","n":"ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ","e":"AQAB"}"#;

/// The inner tokens' `exp` and the fixed time, one minute before it.
const EXP: i64 = 1_300_819_380;
const NOW: i64 = EXP - 60;
/// Past `exp` plus the 60 s default leeway (ADR 0027 §3).
const LATE: i64 = EXP + 60;

const ISSUER: &str = "https://issuer.example";
const AUDIENCE: &str = "https://api.example";

const SIGNING: [SigningAlg; 2] = [SigningAlg::ES256, SigningAlg::EdDSA];

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn jwk(json: &str) -> Jwk {
    Jwk::from_json(json.as_bytes()).unwrap()
}

fn header(json: &str) -> Header {
    Header::from_json(json.as_bytes()).unwrap()
}

fn code<T>(r: polyjose::Result<T>) -> &'static str {
    match r {
        Ok(_) => "ok",
        Err(e) => e.code(),
    }
}

/// The inner signer: RFC 7515 A.3.1's P-256 key.
fn es256_key() -> Jwk {
    jwk(P256)
}

/// RFC 8037 Appendix A.1: the Ed25519 key.
fn ed25519_key() -> Jwk {
    jwk(&format!(
        r#"{{"kty":"OKP","crv":"Ed25519","x":"{}","d":"{}"}}"#,
        common::ED25519_X,
        common::ED25519_D
    ))
}

fn public(key: &Jwk) -> Jwk {
    key.to_public().unwrap()
}

/// `iss`, `sub` and `exp`, the inner claims of most tests.
fn claims() -> Claims {
    let mut c = Claims::new();
    c.iss = Some(ISSUER.into());
    c.sub = Some("alice".into());
    c.exp = NumericDate::from_secs(EXP);
    c
}

/// A signed JWT (T08's `jwt::sign`) over `claims`.
fn signed(claims: &Claims, alg: SigningAlg, key: &Jwk) -> String {
    jwt::sign(claims, &IssueOptions::new(alg), key).unwrap()
}

/// An ES256 inner JWT over [`claims`].
fn inner_es256() -> String {
    signed(&claims(), SigningAlg::ES256, &es256_key())
}

/// `jws::sign_compact` over `payload` with the protected header given as
/// JSON text (signed as written, RFC 7515 §5.1 step 5).
fn sign_raw(header_json: &str, payload: &[u8], key: &Jwk) -> String {
    let protected = ProtectedHeader::from_encoded(&b64url_encode(header_json.as_bytes())).unwrap();
    sign_compact(&protected, payload, key, &SignOptions::new()).unwrap()
}

/// An encryptor for one recipient, with `protected` as its extra
/// protected header parameters.
fn encryptor(enc: ContentEncAlg, recipient: Recipient, protected: Header) -> Encryptor {
    Encryptor::new(enc)
        .recipient(recipient)
        .protected_header(protected)
}

/// The A128KW + A128GCM encryptor of most tests, with `protected` as its
/// extra protected header parameters.
fn kw(protected: &str) -> Encryptor {
    encryptor(
        E::A128GCM,
        Recipient::new(A::A128KW, &jwk(KEK)),
        header(protected),
    )
}

/// `plaintext` as a compact JWE with A128KW + A128GCM and the protected
/// header parameters `protected`, built with 0003's encryptor directly, so
/// the outer header can be anything (no `cty`, a wrong `cty`, replicated
/// claims).
fn nest_raw(plaintext: &str, protected: &str) -> String {
    kw(protected).encrypt_compact(plaintext.as_bytes()).unwrap()
}

/// `inner` as a nested JWT made by `jwt::encrypt_nested` with A128KW +
/// A128GCM and no caller protected header.
fn nest(inner: &str) -> String {
    jwt::encrypt_nested(inner, &kw("{}")).unwrap()
}

/// The protected header of compact JWE `token`, as sent.
fn outer_header_of(token: &str) -> Header {
    let first = token.split('.').next().unwrap();
    Header::from_json(&b64url_decode(first).unwrap()).unwrap()
}

/// Every JWE algorithm these tests decrypt with, and every `enc`.
fn decrypt_policy() -> DecryptPolicy {
    DecryptPolicy::new(
        &[
            A::Dir,
            A::A128KW,
            A::EcdhEs,
            A::EcdhEsA128KW,
            A::Pbes2Hs256A128KW,
            A::RsaOaep256,
        ],
        E::KNOWN,
    )
    .unwrap()
}

/// `decrypt_nested` with the A128KW key, the ES256 public key and a
/// default policy at `now`.
fn open_at(token: &str, now: i64) -> polyjose::Result<VerifiedNestedJwt> {
    let clock = FixedClock(now);
    let policy = Policy::new(&clock, &SIGNING).unwrap();
    let key = public(&es256_key());
    jwt::decrypt_nested(
        token,
        &jwk(KEK),
        &decrypt_policy(),
        Keys::One(&key),
        &policy,
    )
}

fn open(token: &str) -> polyjose::Result<VerifiedNestedJwt> {
    open_at(token, NOW)
}

/// `token` (five parts) with the low bit of its authentication tag's last
/// octet flipped.
fn flip_tag(token: &str) -> String {
    let (head, tag) = token.rsplit_once('.').unwrap();
    let mut octets = b64url_decode(tag).unwrap();
    *octets.last_mut().unwrap() ^= 0x01;
    format!("{head}.{}", b64url_encode(&octets))
}

// ---------------------------------------------------------------------------
// Decrypt-then-verify across the key management modes (RFC 7519 §7.2)
// ---------------------------------------------------------------------------

/// RFC 7519 §7.1 step 5, §7.2 step 8, §11.2: an ES256 inner JWT nested by
/// `encrypt_nested` with `dir`, A128KW, ECDH-ES+A128KW (P-256), ECDH-ES
/// (X25519) and PBES2-HS256+A128KW is a compact JWE with `cty: JWT`, and
/// it decrypts, verifies and validates; the result carries the inner
/// verification, the outer protected header and the recipient index.
#[test]
fn every_outer_mode_decrypts_then_verifies() {
    let dir = generate(KeySpec::Oct { bytes: 32 }).unwrap();
    let p256 = generate(KeySpec::Ec(EcCurve::P256)).unwrap();
    let x25519 = generate(KeySpec::Okp(OkpCurve::X25519)).unwrap();
    let password = jwk(&format!(
        r#"{{"kty":"oct","k":"{}"}}"#,
        b64url_encode(PASSWORD)
    ));
    let cases: [(Recipient, ContentEncAlg, &Jwk, &str); 5] = [
        (Recipient::new(A::Dir, &dir), E::A256GCM, &dir, "dir"),
        (
            Recipient::new(A::A128KW, &jwk(KEK)),
            E::A128GCM,
            &jwk(KEK),
            "A128KW",
        ),
        (
            Recipient::new(A::EcdhEsA128KW, &public(&p256)),
            E::A128GCM,
            &p256,
            "ECDH-ES+A128KW",
        ),
        (
            Recipient::new(A::EcdhEs, &public(&x25519)),
            E::A256GCM,
            &x25519,
            "ECDH-ES",
        ),
        (
            Recipient::new(A::Pbes2Hs256A128KW, &password).p2c(1_000),
            E::A128GCM,
            &password,
            "PBES2-HS256+A128KW",
        ),
    ];
    let clock = FixedClock(NOW);
    let policy = Policy::new(&clock, &SIGNING).unwrap();
    let verifier = public(&es256_key());
    let inner = inner_es256();
    for (recipient, enc, decrypt_key, alg) in cases {
        let e = Encryptor::new(enc.clone()).recipient(recipient);
        let token = jwt::encrypt_nested(&inner, &e).unwrap_or_else(|e| panic!("{alg}: {e}"));
        assert_eq!(token.split('.').count(), 5, "{alg}");
        assert_eq!(outer_header_of(&token).cty.as_deref(), Some("JWT"), "{alg}");
        let v = jwt::decrypt_nested(
            &token,
            decrypt_key,
            &decrypt_policy(),
            Keys::One(&verifier),
            &policy,
        )
        .unwrap_or_else(|e| panic!("{alg}: {e}"));
        assert_eq!(v.inner.claims, claims(), "{alg}");
        assert_eq!(v.inner.alg, SigningAlg::ES256, "{alg}");
        assert_eq!(v.inner.header.typ.as_deref(), Some("JWT"), "{alg}");
        assert_eq!(v.outer_header.alg.as_deref(), Some(alg));
        assert_eq!(v.outer_header.enc, Some(enc), "{alg}");
        assert_eq!(v.outer_header.cty.as_deref(), Some("JWT"), "{alg}");
        assert_eq!(v.recipient, 0, "{alg}");
    }
}

/// The RFC 7515 A.2 RSA private key (RFC 7518 §6.3.2), whose public half
/// is [`RSA_PUBLIC`].
fn rsa_private() -> Jwk {
    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/data/keys/rfc/rfc7515-a2-rsa-private.jwk.json");
    let key = Jwk::from_json(&std::fs::read(path).unwrap()).unwrap();
    assert!(!key.is_public());
    assert_eq!(
        key.to_public().unwrap().to_json().as_str(),
        jwk(RSA_PUBLIC).to_json().as_str()
    );
    key
}

/// ADR 0067: an EdDSA inner JWT nested by `encrypt_nested` for an
/// RSA-OAEP-256 recipient decrypts with the RSA private key and verifies
/// (RFC 7519 §7.2). The public key is no decryption candidate (RFC 8725
/// §3.1): `KeyAlgorithmMismatch`.
#[test]
fn rsa_oaep_256_nested_jwt_decrypts_with_the_private_key_only() {
    let rsa = jwk(RSA_PUBLIC);
    let inner = signed(&claims(), SigningAlg::EdDSA, &ed25519_key());
    let e = Encryptor::new(E::A256GCM).recipient(Recipient::new(A::RsaOaep256, &rsa));
    let token = jwt::encrypt_nested(&inner, &e).unwrap();
    assert_eq!(token.split('.').count(), 5);
    let h = outer_header_of(&token);
    assert_eq!(h.alg.as_deref(), Some("RSA-OAEP-256"));
    assert_eq!(h.cty.as_deref(), Some("JWT"));
    let clock = FixedClock(NOW);
    let policy = Policy::new(&clock, &SIGNING).unwrap();
    let verifier = public(&ed25519_key());
    let r = jwt::decrypt_nested(
        &token,
        &rsa,
        &decrypt_policy(),
        Keys::One(&verifier),
        &policy,
    );
    assert_eq!(r.map(|_| ()), Err(Error::KeyAlgorithmMismatch));
    let v = jwt::decrypt_nested(
        &token,
        &rsa_private(),
        &decrypt_policy(),
        Keys::One(&verifier),
        &policy,
    )
    .unwrap();
    assert_eq!(v.inner.claims, claims());
    assert_eq!(v.inner.alg, SigningAlg::EdDSA);
    assert_eq!(v.outer_header.alg.as_deref(), Some("RSA-OAEP-256"));
    assert_eq!(v.recipient, 0);
}

/// ADR 0067: one RSA key pair both ways. The inner JWT is RS256-signed
/// with the RFC 7515 A.2 private key (RFC 7518 §3.3), encrypted to its
/// public half with RSA-OAEP-256, then decrypted with the private key and
/// verified with the public key.
#[test]
fn rs256_inner_jwt_under_rsa_oaep_256_round_trips() {
    let private = rsa_private();
    let rsa = jwk(RSA_PUBLIC);
    let inner = signed(&claims(), SigningAlg::RS256, &private);
    let e = Encryptor::new(E::A128CbcHs256).recipient(Recipient::new(A::RsaOaep256, &rsa));
    let token = jwt::encrypt_nested(&inner, &e).unwrap();
    let clock = FixedClock(NOW);
    let policy = Policy::new(&clock, &[SigningAlg::RS256]).unwrap();
    let v = jwt::decrypt_nested(
        &token,
        &private,
        &decrypt_policy(),
        Keys::One(&rsa),
        &policy,
    )
    .unwrap();
    assert_eq!(v.inner.claims, claims());
    assert_eq!(v.inner.alg, SigningAlg::RS256);
    // Signing with the public key is a key mismatch (ADR 0067).
    assert_eq!(
        jwt::sign(&claims(), &IssueOptions::new(SigningAlg::RS256), &rsa).map(|_| ()),
        Err(Error::KeyAlgorithmMismatch)
    );
}

/// The EdDSA inner JWT itself verifies under a non-RSA outer layer.
#[test]
fn an_eddsa_inner_jwt_verifies() {
    let inner = signed(&claims(), SigningAlg::EdDSA, &ed25519_key());
    let clock = FixedClock(NOW);
    let policy = Policy::new(&clock, &SIGNING).unwrap();
    let verifier = public(&ed25519_key());
    let v = jwt::decrypt_nested(
        &nest(&inner),
        &jwk(KEK),
        &decrypt_policy(),
        Keys::One(&verifier),
        &policy,
    )
    .unwrap();
    assert_eq!(v.inner.alg, SigningAlg::EdDSA);
    assert_eq!(v.inner.claims, claims());
}

// ---------------------------------------------------------------------------
// Sign-then-encrypt (RFC 7519 §5.2, §7.1 step 5, §11.2)
// ---------------------------------------------------------------------------

/// RFC 7519 §5.2: `encrypt_nested` sets `cty: "JWT"` in the JWE Protected
/// Header, keeps the caller's other protected parameters, rewrites a
/// caller `cty` that already means `JWT` to the exact spelling, and does
/// not change the caller's encryptor, which stays reusable.
#[test]
fn encrypt_nested_sets_cty_jwt_and_keeps_the_callers_header() {
    let inner = inner_es256();
    let e = kw(r#"{"typ":"JWT","kid":"outer-1","x-tenant":"acme"}"#);
    let first = jwt::encrypt_nested(&inner, &e).unwrap();
    let second = jwt::encrypt_nested(&inner, &e).unwrap();
    assert_ne!(first, second, "fresh CEK and IV each time (ADR 0005)");
    for token in [&first, &second] {
        let h = outer_header_of(token);
        assert_eq!(h.cty.as_deref(), Some("JWT"));
        assert_eq!(h.typ.as_deref(), Some("JWT"));
        assert_eq!(h.kid.as_deref(), Some("outer-1"));
        assert!(h.other_params().contains("x-tenant"));
        let v = open(token).unwrap();
        assert_eq!(v.outer_header, h);
    }
    for cty in ["JWT", "jwt", "application/JWT", "Application/jwt"] {
        let token = jwt::encrypt_nested(&inner, &kw(&format!(r#"{{"cty":"{cty}"}}"#))).unwrap();
        assert_eq!(outer_header_of(&token).cty.as_deref(), Some("JWT"), "{cty}");
        assert_eq!(code(open(&token)), "ok", "{cty}");
    }
}

/// ADR 0027 §7: a caller `cty` other than `JWT` (RFC 7515 §4.1.10
/// comparison) is `InvalidHeader`, never silently replaced.
#[test]
fn encrypt_nested_refuses_a_different_caller_cty() {
    let inner = inner_es256();
    for cty in ["JOSE", "at+jwt", "JWT ", "text/JWT", "application/jwt;v=1"] {
        let r = jwt::encrypt_nested(&inner, &kw(&format!(r#"{{"cty":"{cty}"}}"#)));
        assert!(matches!(r, Err(Error::InvalidHeader(_))), "{cty:?}: {r:?}");
    }
}

/// RFC 7515 §7.1, ADR 0027 §6–§7: the input must be a three-part compact
/// JWS. A nested JWT (five parts), a JWS JSON serialization, an empty
/// signature part (an Unsecured JWS, RFC 7519 §6; RFC 8725 §3.2), a
/// protected header that is not base64url-encoded JSON object text
/// (RFC 7515 §5.2 steps 2–3), or anything else is `InvalidFormat`,
/// before the caller's `cty` or `zip` is looked at.
#[test]
fn encrypt_nested_needs_a_compact_jws() {
    let inner = inner_es256();
    let jwe = nest(&inner);
    let json = format!(
        r#"{{"payload":"{}","protected":"{}","signature":"{}"}}"#,
        inner.split('.').nth(1).unwrap(),
        inner.split('.').next().unwrap(),
        inner.split('.').nth(2).unwrap(),
    );
    let with_newline = format!("{inner}\n");
    let (head, rest) = inner.split_once('.').unwrap();
    let (payload, _) = rest.split_once('.').unwrap();
    // A signed JWT with its signature part emptied.
    let no_signature = format!("{head}.{payload}.");
    // Protected headers that are not base64url JSON objects.
    let with_header = |h: &[u8]| format!("{}.{payload}.c2ln", b64url_encode(h));
    let not_json = with_header(b"not json");
    let an_array = with_header(br#"["alg","none"]"#);
    let duplicate_alg = with_header(br#"{"alg":"ES256","alg":"none"}"#);
    let not_utf8 = with_header(b"{\"alg\":\"\xff\"}");
    for input in [
        "",
        "not a jws",
        "a.b",
        jwe.as_str(),
        json.as_str(),
        with_newline.as_str(),
        ".eyJ9.sig",
        no_signature.as_str(),
        // RFC 7519 §6.1: the example Unsecured JWT.
        "eyJhbGciOiJub25lIn0.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.",
        // Review probe (b): `{"alg":"none"}`, `{"sub":"x"}`, no signature.
        "eyJhbGciOiJub25lIn0.eyJzdWIiOiJ4In0.",
        // Not base64url: one character in a final quantum, and a
        // non-canonical final quantum (RFC 4648 §3.5, §4).
        "e.eyJ9.sig",
        "QR.eyJ9.sig",
        not_json.as_str(),
        an_array.as_str(),
        duplicate_alg.as_str(),
        not_utf8.as_str(),
    ] {
        for e in [kw("{}"), kw(r#"{"cty":"JOSE"}"#), kw("{}").compress()] {
            assert!(
                matches!(jwt::encrypt_nested(input, &e), Err(Error::InvalidFormat(_))),
                "{input:?}"
            );
        }
    }
}

/// RFC 8725 §3.2, ADR 0007, ADR 0027 §8: `none` is never produced. An
/// inner protected header with `alg: none` is `AlgorithmNotAllowed` even
/// with a non-empty (fake) signature part, before the caller's `cty` and
/// `zip` are looked at. A missing or non-string `alg` (RFC 7515 §4.1.1:
/// it "MUST be present" and is a string) is `InvalidHeader("alg")`. Only
/// the protected header is decoded.
#[test]
fn encrypt_nested_refuses_an_unsecured_or_alg_less_jws() {
    let encryptors = [
        kw("{}"),
        kw(r#"{"typ":"JWT","kid":"outer-1"}"#),
        kw(r#"{"cty":"JOSE"}"#),
        kw("{}").compress(),
        kw(r#"{"cty":"JOSE"}"#).compress(),
    ];
    let with_header = |h: &str| format!("{}.eyJzdWIiOiJ4In0.c2ln", b64url_encode(h.as_bytes()));
    for h in [
        r#"{"alg":"none"}"#,
        r#"{"typ":"JWT","alg":"none"}"#,
        r#"{"alg":"none","kid":"k1","crit":["exp"],"exp":1}"#,
        "  {\"alg\" : \"none\"}\n",
    ] {
        let input = with_header(h);
        for e in &encryptors {
            assert_eq!(
                jwt::encrypt_nested(&input, e),
                Err(Error::AlgorithmNotAllowed),
                "{h}"
            );
        }
    }
    // The review's probe (b) with a fake signature part.
    for e in &encryptors {
        assert_eq!(
            jwt::encrypt_nested("eyJhbGciOiJub25lIn0.eyJzdWIiOiJ4In0.c2ln", e),
            Err(Error::AlgorithmNotAllowed)
        );
    }
    for h in [
        "{}",
        r#"{"typ":"JWT"}"#,
        r#"{"alg":null}"#,
        r#"{"alg":1}"#,
        r#"{"alg":["none"]}"#,
        r#"{"alg":{"none":true}}"#,
        r#"{"Alg":"none"}"#,
    ] {
        let input = with_header(h);
        for e in &encryptors {
            assert_eq!(
                jwt::encrypt_nested(&input, e),
                Err(Error::InvalidHeader("alg")),
                "{h}"
            );
        }
    }
    // RFC 7515 §4.1.1: any other string `alg` is the receiver's to check
    // against its allow-list; the issuer checks the shape and `none` only.
    let other = with_header(r#"{"alg":"x-unregistered"}"#);
    assert_eq!(code(jwt::encrypt_nested(&other, &kw("{}"))), "ok");
}

/// RFC 8725 §3.6: compression before encryption "SHOULD NOT" be done
/// (compressed data "often reveals information about the plaintext"), so
/// `encrypt_nested` refuses an encryptor that would set `zip`, in every
/// build: one built with `Encryptor::compress()`, or one whose protected
/// header sets a `zip` member (RFC 7516 §4.1.3). `InvalidHeader("zip")`,
/// after the caller's `cty` check.
#[test]
fn encrypt_nested_refuses_compression() {
    let inner = inner_es256();
    for e in [
        kw("{}").compress(),
        kw(r#"{"cty":"JWT"}"#).compress(),
        kw(r#"{"typ":"JWT","kid":"outer-1"}"#).compress(),
        kw(r#"{"zip":"DEF"}"#),
        kw(r#"{"zip":"XYZ"}"#),
        kw(r#"{"zip":"def"}"#),
        kw(r#"{"cty":"JWT","zip":"DEF"}"#),
        kw(r#"{"zip":"DEF"}"#).compress(),
    ] {
        assert_eq!(
            jwt::encrypt_nested(&inner, &e),
            Err(Error::InvalidHeader("zip")),
            "{e:?}"
        );
    }
    // The caller's `cty` is checked first.
    for e in [
        kw(r#"{"cty":"JOSE"}"#).compress(),
        kw(r#"{"cty":"JOSE","zip":"DEF"}"#),
    ] {
        assert_eq!(
            jwt::encrypt_nested(&inner, &e),
            Err(Error::InvalidHeader("cty")),
            "{e:?}"
        );
    }
}

/// With the `deflate` codec (ADR 0017), the same encryptor would compress
/// (`zip: "DEF"`, RFC 7516 §4.1.3), so the refusal is `encrypt_nested`'s
/// own (RFC 8725 §3.6). Receiving is unchanged: a compressed nested JWT
/// made with 0003's encryptor directly still decrypts and verifies, since
/// RFC 7516 §5.2 step 17 allows it and `DecryptPolicy::max_decompressed_len`
/// bounds it.
#[cfg(feature = "deflate")]
#[test]
fn encrypt_nested_refuses_deflate_but_decrypt_nested_accepts_it() {
    let inner = inner_es256();
    let compressing = kw("{}").compress();
    let plain_jwe = compressing.encrypt_compact(inner.as_bytes()).unwrap();
    assert_eq!(outer_header_of(&plain_jwe).zip.as_deref(), Some("DEF"));
    assert_eq!(
        jwt::encrypt_nested(&inner, &compressing),
        Err(Error::InvalidHeader("zip"))
    );
    let received = kw(r#"{"cty":"JWT"}"#)
        .compress()
        .encrypt_compact(inner.as_bytes())
        .unwrap();
    assert_eq!(outer_header_of(&received).zip.as_deref(), Some("DEF"));
    let v = open(&received).unwrap();
    assert_eq!(v.inner.claims.iss.as_deref(), Some(ISSUER));
    assert_eq!(v.outer_header.zip.as_deref(), Some("DEF"));
}

/// RFC 7516 §7.1: the output is compact, so the encryptor's compact
/// restrictions apply (`Encryptor::encrypt_compact` errors pass through).
#[test]
fn encrypt_nested_is_compact_only() {
    let inner = inner_es256();
    let no_recipient = Encryptor::new(E::A128GCM);
    let shared = kw("{}").shared_unprotected_header(header(r#"{"x":1}"#));
    let aad = kw("{}").aad(b"aad".to_vec());
    for e in [no_recipient, shared, aad] {
        assert!(
            matches!(
                jwt::encrypt_nested(&inner, &e),
                Err(Error::InvalidFormat(_))
            ),
            "{e:?}"
        );
    }
}

// ---------------------------------------------------------------------------
// Both layers validated (RFC 8725 §3.3)
// ---------------------------------------------------------------------------

/// RFC 8725 §3.3: decrypting is not enough. An inner JWS signed with a
/// different key, then encrypted correctly, is `InvalidSignature`.
#[test]
fn an_inner_signature_from_another_key_is_invalid_signature() {
    let other = generate(KeySpec::Ec(EcCurve::P256)).unwrap();
    let inner = signed(&claims(), SigningAlg::ES256, &other);
    assert_eq!(code(open(&nest(&inner))), "InvalidSignature");
}

/// RFC 7519 §4.1.4: the inner claims are validated; expired is
/// `TokenExpired`.
#[test]
fn an_expired_inner_jwt_is_token_expired() {
    let token = nest(&inner_es256());
    assert_eq!(code(open_at(&token, NOW)), "ok");
    assert_eq!(open_at(&token, LATE), Err(Error::TokenExpired));
}

/// RFC 7516 §5.2 step 16: a tampered authentication tag is
/// `DecryptionFailed`, detail-free (the 0003 error contract).
#[test]
fn a_tampered_outer_tag_is_decryption_failed() {
    let token = flip_tag(&nest(&inner_es256()));
    assert_eq!(open(&token), Err(Error::DecryptionFailed));
}

/// RFC 8725 §3.1, ADR 0007: the outer `enc` must be in the
/// `DecryptPolicy`, else `AlgorithmNotAllowed` before any cryptography.
#[test]
fn an_outer_enc_outside_the_decrypt_policy_is_algorithm_not_allowed() {
    let token = nest(&inner_es256());
    let only_a256gcm = DecryptPolicy::new(&[A::A128KW], &[E::A256GCM]).unwrap();
    let clock = FixedClock(NOW);
    let policy = Policy::new(&clock, &SIGNING).unwrap();
    let key = public(&es256_key());
    let r = jwt::decrypt_nested(&token, &jwk(KEK), &only_a256gcm, Keys::One(&key), &policy);
    assert!(matches!(r, Err(Error::AlgorithmNotAllowed)), "{r:?}");
    // And the outer alg likewise.
    let only_a256kw = DecryptPolicy::new(&[A::A256KW], &[E::A128GCM]).unwrap();
    let r = jwt::decrypt_nested(&token, &jwk(KEK), &only_a256kw, Keys::One(&key), &policy);
    assert!(matches!(r, Err(Error::AlgorithmNotAllowed)), "{r:?}");
}

/// RFC 8725 §3.1: the inner `alg` must be in the JWT `Policy`; an HS256
/// inner token under an ES256/EdDSA policy is `AlgorithmNotAllowed`, the
/// JWE key never standing in for the JWS key.
#[test]
fn an_inner_alg_outside_the_jwt_policy_is_algorithm_not_allowed() {
    let hmac = jwk(
        r#"{"kty":"oct","k":"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"}"#,
    );
    let inner = signed(&claims(), SigningAlg::HS256, &hmac);
    assert!(matches!(
        open(&nest(&inner)),
        Err(Error::AlgorithmNotAllowed)
    ));
}

/// RFC 8725 §3.2, ADR 0007: an inner Unsecured JWS (`alg: none`) is never
/// accepted, even inside a valid JWE, with an empty or a fake signature.
/// `encrypt_nested` never makes one, so the JWE is built with 0003's
/// encryptor directly.
#[test]
fn an_inner_alg_none_is_algorithm_not_allowed() {
    let payload = b64url_encode(claims().to_json().as_bytes());
    let header = b64url_encode(br#"{"alg":"none"}"#);
    for inner in [
        format!("{header}.{payload}."),
        format!("{header}.{payload}.c2ln"),
    ] {
        assert!(jwt::encrypt_nested(&inner, &kw("{}")).is_err(), "{inner}");
        assert!(
            matches!(
                open(&nest_raw(&inner, r#"{"cty":"JWT"}"#)),
                Err(Error::AlgorithmNotAllowed)
            ),
            "{inner}"
        );
    }
}

// ---------------------------------------------------------------------------
// Shape and typing (ADR 0027 §6–§7)
// ---------------------------------------------------------------------------

/// RFC 7519 §5.2: the outer `cty` "MUST be present" and be `JWT`.
/// Without it the JWE is an encrypt-only JWT (not supported in 0.1.0),
/// with another value it is not a nested JWT: `InvalidHeader` either way.
#[test]
fn an_outer_cty_other_than_jwt_is_invalid_header() {
    let inner = inner_es256();
    for protected in [
        r#"{}"#,
        r#"{"cty":"JOSE"}"#,
        r#"{"cty":"at+jwt"}"#,
        r#"{"cty":"JWT "}"#,
        r#"{"cty":"text/JWT"}"#,
    ] {
        let token = nest_raw(&inner, protected);
        assert!(
            matches!(open(&token), Err(Error::InvalidHeader(_))),
            "{protected}"
        );
    }
    // The claims as the plaintext: an encrypt-only JWT.
    let encrypt_only = nest_raw(&claims().to_json(), r#"{}"#);
    assert!(matches!(open(&encrypt_only), Err(Error::InvalidHeader(_))));
}

/// RFC 7515 §4.1.10 (ADR 0027 §5, §7): `cty` compares as a media type, so
/// `jwt` and `application/JWT` are `JWT`.
#[test]
fn an_outer_cty_compares_as_a_media_type() {
    let inner = inner_es256();
    for cty in ["JWT", "jwt", "application/JWT", "Application/jwt"] {
        let token = nest_raw(&inner, &format!(r#"{{"cty":"{cty}"}}"#));
        let v = open(&token).unwrap_or_else(|e| panic!("{cty}: {e}"));
        assert_eq!(v.outer_header.cty.as_deref(), Some(cty));
    }
}

/// ADR 0027 §7, depth 1: an inner plaintext that is a JWE (five parts) is
/// `InvalidFormat`, as is one that is no JWS at all.
#[test]
fn an_inner_jwe_is_invalid_format() {
    let doubly_nested = nest_raw(&nest(&inner_es256()), r#"{"cty":"JWT"}"#);
    assert!(matches!(open(&doubly_nested), Err(Error::InvalidFormat(_))));
    for plaintext in ["", "a.b", "a.b.c.d", "{\"iss\":\"x\"}"] {
        assert!(
            matches!(
                open(&nest_raw(plaintext, r#"{"cty":"JWT"}"#)),
                Err(Error::InvalidFormat(_))
            ),
            "{plaintext:?}"
        );
    }
}

/// ADR 0027 §5, §7: an inner JWS whose own `cty` is `JWT` would nest a
/// JWS in a JWS (depth 2), which is not supported: `InvalidHeader`.
#[test]
fn an_inner_jws_with_cty_jwt_is_invalid_header() {
    let payload = claims().to_json();
    for cty in ["JWT", "jwt", "application/jwt"] {
        let inner = sign_raw(
            &format!(r#"{{"alg":"ES256","cty":"{cty}"}}"#),
            payload.as_bytes(),
            &es256_key(),
        );
        assert!(
            matches!(open(&nest(&inner)), Err(Error::InvalidHeader(_))),
            "{cty}"
        );
    }
}

/// ADR 0027 §7: signed and nested JWTs have separate entry points. A
/// three-part signed JWT given to `decrypt_nested` is `InvalidFormat`, and
/// a nested JWT given to `jwt::verify` is `InvalidFormat`.
#[test]
fn signed_and_nested_jwts_have_separate_entry_points() {
    let inner = inner_es256();
    assert!(matches!(open(&inner), Err(Error::InvalidFormat(_))));
    let clock = FixedClock(NOW);
    let policy = Policy::new(&clock, &SIGNING).unwrap();
    let key = public(&es256_key());
    assert!(matches!(
        jwt::verify(&nest(&inner), Keys::One(&key), &policy),
        Err(Error::InvalidFormat(_))
    ));
}

/// The seven claims RFC 9068 §2.2 requires of a JWT access token.
fn access_token_claims() -> Claims {
    let mut c = claims();
    c.aud = Some(Audience::One(AUDIENCE.into()));
    c.insert("client_id", "s6BhdRkqt3").unwrap();
    c.iat = NumericDate::from_secs(EXP - 1_000);
    c.jti = Some("dbe39bf3a3ba4238a513f51d6e1691c4".into());
    c
}

/// RFC 8725 §3.11: explicit typing applies to the inner JWT; the outer
/// `typ`, if present, must satisfy the same `typ` policy (ADR 0027 §7).
/// Under `Policy::access_token` (RFC 9068 §4), an inner `typ: at+jwt`
/// with no outer `typ` passes, an outer `secevent+jwt` (or `JWT`) does
/// not, and an untyped inner token does not either.
#[test]
fn explicit_typing_is_checked_on_the_inner_jws() {
    let key = es256_key();
    let at = jwt::sign(
        &access_token_claims(),
        &IssueOptions::new(SigningAlg::ES256).access_token(),
        &key,
    )
    .unwrap();
    let generic = signed(&access_token_claims(), SigningAlg::ES256, &key);
    let clock = FixedClock(NOW);
    let policy = Policy::access_token(&clock, &SIGNING, &[ISSUER], &[AUDIENCE]).unwrap();
    let verifier = public(&key);
    let run = |token: &str| {
        jwt::decrypt_nested(
            token,
            &jwk(KEK),
            &decrypt_policy(),
            Keys::One(&verifier),
            &policy,
        )
    };
    let v = run(&nest(&at)).unwrap();
    assert_eq!(v.inner.header.typ.as_deref(), Some("at+jwt"));
    assert_eq!(v.outer_header.typ, None);
    assert_eq!(
        code(run(&nest_raw(&at, r#"{"cty":"JWT","typ":"at+jwt"}"#))),
        "ok"
    );
    for outer in [
        r#"{"cty":"JWT","typ":"secevent+jwt"}"#,
        r#"{"cty":"JWT","typ":"JWT"}"#,
    ] {
        assert!(
            matches!(run(&nest_raw(&at, outer)), Err(Error::InvalidHeader(_))),
            "{outer}"
        );
    }
    // The outer typ does not stand in for the inner one.
    assert!(matches!(
        run(&nest_raw(&generic, r#"{"cty":"JWT","typ":"at+jwt"}"#)),
        Err(Error::InvalidHeader(_))
    ));
}

/// ADR 0027 §7 under the default `typ` mode: an outer `typ` must be absent
/// or `JWT`, like the inner one.
#[test]
fn the_default_typ_mode_applies_to_the_outer_typ() {
    let inner = inner_es256();
    for ok in [
        r#"{"cty":"JWT","typ":"JWT"}"#,
        r#"{"cty":"JWT","typ":"jwt"}"#,
    ] {
        assert_eq!(code(open(&nest_raw(&inner, ok))), "ok", "{ok}");
    }
    let token = nest_raw(&inner, r#"{"cty":"JWT","typ":"secevent+jwt"}"#);
    assert!(matches!(open(&token), Err(Error::InvalidHeader(_))));
}

/// Review N3, ADR 0027 §7: under an explicit-type policy
/// (`Policy::access_token`, `Policy::expect_typ`) an outer JWE `typ` that
/// is present must match the same type, so the common issuer habit of an
/// outer `typ: JWT` is `InvalidHeader("typ")`; RFC 8725 §3.11 types the
/// inner JWT. An issuer omits the outer `typ`, as `encrypt_nested` does
/// unless the caller's protected header sets one.
#[test]
fn an_outer_typ_jwt_fails_an_explicit_type_policy() {
    let key = es256_key();
    let at = jwt::sign(
        &access_token_claims(),
        &IssueOptions::new(SigningAlg::ES256).access_token(),
        &key,
    )
    .unwrap();
    let clock = FixedClock(NOW);
    let verifier = public(&key);
    let policies = [
        Policy::access_token(&clock, &SIGNING, &[ISSUER], &[AUDIENCE]).unwrap(),
        Policy::new(&clock, &SIGNING)
            .unwrap()
            .audiences(&[AUDIENCE])
            .expect_typ("at+jwt"),
    ];
    let omitted = jwt::encrypt_nested(&at, &kw("{}")).unwrap();
    let outer_jwt = jwt::encrypt_nested(&at, &kw(r#"{"typ":"JWT"}"#)).unwrap();
    let outer_same = jwt::encrypt_nested(&at, &kw(r#"{"typ":"at+jwt"}"#)).unwrap();
    assert_eq!(outer_header_of(&omitted).typ, None);
    assert_eq!(outer_header_of(&outer_jwt).typ.as_deref(), Some("JWT"));
    for policy in &policies {
        let run = |token: &str| {
            jwt::decrypt_nested(
                token,
                &jwk(KEK),
                &decrypt_policy(),
                Keys::One(&verifier),
                policy,
            )
        };
        assert_eq!(code(run(&omitted)), "ok");
        assert_eq!(code(run(&outer_same)), "ok");
        assert_eq!(
            run(&outer_jwt).map(|_| ()),
            Err(Error::InvalidHeader("typ"))
        );
    }
}

// ---------------------------------------------------------------------------
// Replicated claims (RFC 7519 §5.3)
// ---------------------------------------------------------------------------

/// `inner` encrypted with `cty: JWT` and `members` added to the outer
/// protected header, as replicated claims.
fn nest_with(inner: &str, members: &str) -> String {
    nest_raw(inner, &format!(r#"{{"cty":"JWT",{members}}}"#))
}

/// RFC 7519 §5.3: replicated `iss`, `sub` and `aud` must be identical to
/// the inner claims (ADR 0027 §7: JSON-equal).
#[test]
fn replicated_claims_equal_to_the_inner_ones_pass() {
    let mut c = claims();
    c.aud = Some(Audience::One("a".into()));
    let inner = signed(&c, SigningAlg::ES256, &es256_key());
    let clock = FixedClock(NOW);
    let policy = Policy::new(&clock, &SIGNING).unwrap().audience("a");
    let key = public(&es256_key());
    let run = |token: &str| {
        jwt::decrypt_nested(
            token,
            &jwk(KEK),
            &decrypt_policy(),
            Keys::One(&key),
            &policy,
        )
    };
    for members in [
        format!(r#""iss":"{ISSUER}""#),
        r#""sub":"alice""#.to_owned(),
        r#""aud":"a""#.to_owned(),
        format!(r#""iss":"{ISSUER}","sub":"alice","aud":"a""#),
    ] {
        let v = run(&nest_with(&inner, &members)).unwrap_or_else(|e| panic!("{members}: {e}"));
        assert!(v.outer_header.contains(members.split('"').nth(1).unwrap()));
    }
    // A Many audience matches the same array.
    let mut many = claims();
    many.aud = Some(Audience::Many(vec!["a".into(), "b".into()]));
    let inner = signed(&many, SigningAlg::ES256, &es256_key());
    assert_eq!(code(run(&nest_with(&inner, r#""aud":["a","b"]"#))), "ok");
}

/// RFC 7519 §5.3: a replicated claim that differs is `InvalidClaim`. The
/// form matters (ADR 0027 §7: JSON equality): an outer `aud: ["a"]` does
/// not equal an inner `aud: "a"`, and an outer claim the inner Claims Set
/// lacks is a mismatch too.
#[test]
fn replicated_claims_that_differ_are_invalid_claim() {
    let mut c = claims();
    c.aud = Some(Audience::One("a".into()));
    let inner = signed(&c, SigningAlg::ES256, &es256_key());
    let clock = FixedClock(NOW);
    let policy = Policy::new(&clock, &SIGNING).unwrap().audience("a");
    let key = public(&es256_key());
    let run = |token: &str| {
        jwt::decrypt_nested(
            token,
            &jwk(KEK),
            &decrypt_policy(),
            Keys::One(&key),
            &policy,
        )
    };
    let cases = [
        (r#""iss":"https://evil.example""#, "iss"),
        (r#""iss":"HTTPS://ISSUER.EXAMPLE""#, "iss"),
        (r#""sub":"mallory""#, "sub"),
        (r#""aud":["a"]"#, "aud"),
        (r#""aud":"b""#, "aud"),
        (r#""aud":1"#, "aud"),
    ];
    for (members, name) in cases {
        assert_eq!(
            run(&nest_with(&inner, members)),
            Err(Error::InvalidClaim(name)),
            "{members}"
        );
    }
    // The inner token has no `jti`; a replicated `jti` is not checked.
    assert_eq!(code(run(&nest_with(&inner, r#""jti":"x""#))), "ok");
    // An outer `sub` with no inner `sub`.
    let mut no_sub = c.clone();
    no_sub.sub = None;
    let inner = signed(&no_sub, SigningAlg::ES256, &es256_key());
    assert_eq!(
        run(&nest_with(&inner, r#""sub":"alice""#)),
        Err(Error::InvalidClaim("sub"))
    );
}

// ---------------------------------------------------------------------------
// Precedence (ADR 0027 §9)
// ---------------------------------------------------------------------------

/// ADR 0027 §9: the JWE errors come first, then N1, then the inner steps,
/// then N2.
#[test]
fn the_layers_fail_in_the_adr_0027_order() {
    let other = generate(KeySpec::Ec(EcCurve::P256)).unwrap();
    let bad_signature = signed(&claims(), SigningAlg::ES256, &other);
    // Outer tampered and inner signature invalid: the JWE decides.
    assert_eq!(
        open(&flip_tag(&nest(&bad_signature))),
        Err(Error::DecryptionFailed)
    );
    // Outer cty missing and inner expired: N1 decides.
    let no_cty = nest_raw(&inner_es256(), r#"{}"#);
    assert!(matches!(
        open_at(&no_cty, LATE),
        Err(Error::InvalidHeader(_))
    ));
    // Outer cty missing and inner signature invalid: N1 decides.
    assert!(matches!(
        open(&nest_raw(&bad_signature, r#"{}"#)),
        Err(Error::InvalidHeader(_))
    ));
    // A replicated claim that differs and the inner expired: the inner
    // claims (J5) come before N2.
    let mismatch = nest_with(&inner_es256(), r#""iss":"https://evil.example""#);
    assert_eq!(open_at(&mismatch, LATE), Err(Error::TokenExpired));
    assert_eq!(open_at(&mismatch, NOW), Err(Error::InvalidClaim("iss")));
    // A replicated claim that differs and the inner signature invalid:
    // the signature (step 9) comes first.
    let mismatch = nest_with(&bad_signature, r#""iss":"https://evil.example""#);
    assert_eq!(code(open(&mismatch)), "InvalidSignature");
    // The outer enc not allowed and the outer cty missing: the JWE
    // contract runs before N1.
    let only_a256gcm = DecryptPolicy::new(&[A::A128KW], &[E::A256GCM]).unwrap();
    let clock = FixedClock(NOW);
    let policy = Policy::new(&clock, &SIGNING).unwrap();
    let key = public(&es256_key());
    assert!(matches!(
        jwt::decrypt_nested(&no_cty, &jwk(KEK), &only_a256gcm, Keys::One(&key), &policy),
        Err(Error::AlgorithmNotAllowed)
    ));
}

// ---------------------------------------------------------------------------
// Compact only; the outer typing from the protected header (ADR 0050 §3)
// ---------------------------------------------------------------------------

/// ADR 0027 §6, ADR 0050 §3: a JWE JSON Serialization, flattened or
/// general, is `InvalidFormat`, even a valid one whose `cty: JWT` is
/// protected, and one whose `cty: JWT` is only in the shared unprotected
/// header (where anyone could have put it).
#[test]
fn a_json_jwe_is_invalid_format() {
    let inner = inner_es256();
    let recipient = || Recipient::new(A::A128KW, &jwk(KEK));
    let protected_cty = || encryptor(E::A128GCM, recipient(), header(r#"{"cty":"JWT"}"#));
    let unprotected_cty = || {
        Encryptor::new(E::A128GCM)
            .recipient(recipient())
            .shared_unprotected_header(header(r#"{"cty":"JWT"}"#))
    };
    for form in [JsonForm::Flattened, JsonForm::General] {
        for e in [protected_cty(), unprotected_cty()] {
            let jwe = e.encrypt_json(inner.as_bytes(), form).unwrap();
            assert!(
                matches!(open(&jwe), Err(Error::InvalidFormat(_))),
                "{form:?} {jwe}"
            );
            // With surrounding JSON whitespace too.
            let spaced = format!("\r\n {jwe}");
            assert!(matches!(open(&spaced), Err(Error::InvalidFormat(_))));
        }
    }
}

// ---------------------------------------------------------------------------
// Secrets (ADR 0049 §4)
// ---------------------------------------------------------------------------

/// ADR 0049 §4, ADR 0027 §7: no claim string of the decrypted inner token
/// is in the result's `Debug` or in any error. The marker is in every
/// string claim: `iss`, `sub`, an `aud` element, `jti` (RFC 7519 §4.1)
/// and a private claim. It reaches the output only if the inner token, its
/// payload or a claim string leaks: `Claims`' `Debug` prints `iss`, `sub`,
/// `jti` and each `aud` element as `"<redacted>"`, and the other claims
/// through `Value`'s redacting `Debug`.
#[test]
fn the_inner_token_never_appears_in_debug_or_errors() {
    const MARKER: &str = "MARKER-7c1f2b9e-secret-claim-value";
    let mut c = claims();
    c.iss = Some(format!("{MARKER}-iss"));
    c.sub = Some(format!("{MARKER}-sub"));
    c.aud = Some(Audience::Many(vec![
        AUDIENCE.into(),
        format!("{MARKER}-aud"),
    ]));
    c.jti = Some(format!("{MARKER}-jti"));
    c.insert("secret", MARKER).unwrap();
    let inner = signed(&c, SigningAlg::ES256, &es256_key());
    // `open_at` with the policy accepting the token's audience, so every
    // step runs (ADR 0027 §9 J6).
    let key = public(&es256_key());
    let open_at = |token: &str, now: i64| {
        let clock = FixedClock(now);
        let policy = Policy::new(&clock, &SIGNING).unwrap().audience(AUDIENCE);
        jwt::decrypt_nested(
            token,
            &jwk(KEK),
            &decrypt_policy(),
            Keys::One(&key),
            &policy,
        )
    };
    let open = |token: &str| open_at(token, NOW);
    let payload_b64 = inner.split('.').nth(1).unwrap().to_owned();
    let signature_b64 = inner.split('.').nth(2).unwrap().to_owned();
    let leaks = |text: &str| {
        text.contains(MARKER)
            || text.contains(&inner)
            || text.contains(&payload_b64)
            || text.contains(&signature_b64)
    };

    let v = open(&nest(&inner)).unwrap();
    // Every marker made it into the result, so its absence from `Debug`
    // is redaction, not a missing claim.
    assert_eq!(v.inner.claims, c);
    let debug = format!("{v:?} {v:#?} {:?}", v.inner);
    assert!(!leaks(&debug), "{debug}");

    let other = generate(KeySpec::Ec(EcCurve::P256)).unwrap();
    let errors = [
        // N2
        open(&nest_with(&inner, r#""iss":"https://evil.example""#)),
        // J5
        open_at(&nest(&inner), LATE),
        // step 9
        open(&nest(&signed(&c, SigningAlg::ES256, &other))),
        // J1
        open(&nest(&sign_raw(
            r#"{"alg":"ES256","cty":"JWT"}"#,
            c.to_json().as_bytes(),
            &es256_key(),
        ))),
        // N1
        open(&nest_raw(&inner, r#"{}"#)),
        // The JWE
        open(&flip_tag(&nest(&inner))),
    ];
    for r in errors {
        let e = r.unwrap_err();
        let text = format!("{e} {e:?} {}", e.code());
        assert!(!leaks(&text), "{text}");
    }
}

// ---------------------------------------------------------------------------
// PBES2 budget through the nested entry point (ADR 0050 §2)
// ---------------------------------------------------------------------------

/// ADR 0050 §2: a `DecryptPolicy` PBES2 budget bounds `p2c` for a nested
/// JWT too: over budget is the uniform `DecryptionFailed`, at or under it
/// decrypts and verifies.
#[test]
fn the_pbes2_budget_applies_to_nested_decryption() {
    let password =
        Jwk::from_json(format!(r#"{{"kty":"oct","k":"{}"}}"#, b64url_encode(PASSWORD)).as_bytes())
            .unwrap();
    let token = jwt::encrypt_nested(
        &inner_es256(),
        &Encryptor::new(E::A128GCM)
            .recipient(Recipient::new(A::Pbes2Hs256A128KW, &password).p2c(1_000)),
    )
    .unwrap();
    let clock = FixedClock(NOW);
    let policy = Policy::new(&clock, &SIGNING).unwrap();
    let key = public(&es256_key());
    let run = |budget: u32| {
        let dp = DecryptPolicy::new(&[A::Pbes2Hs256A128KW], &[E::A128GCM])
            .unwrap()
            .max_pbes2_count(budget);
        jwt::decrypt_nested(&token, &password, &dp, Keys::One(&key), &policy)
    };
    assert_eq!(run(999).unwrap_err(), Error::DecryptionFailed);
    assert_eq!(run(1).unwrap_err(), Error::DecryptionFailed);
    assert!(run(1_000).is_ok());
    assert!(run(10_000).is_ok());
}

// ---------------------------------------------------------------------------
// F02 tester probes: error order and header-only decoding
// ---------------------------------------------------------------------------

/// ADR 0027 §8 / F02: the documented order (shape, inner `alg`, caller
/// `cty`, `zip`, encrypt) is exact for every two-fault pairing.
#[test]
fn encrypt_nested_error_order_is_exact_for_every_pair() {
    let good = inner_es256();
    let hdr = |h: &str| format!("{}.eyJzdWIiOiJ4In0.c2ln", b64url_encode(h.as_bytes()));
    let none = hdr(r#"{"alg":"none"}"#);
    let no_alg = hdr("{}");
    let bad_shape = "a.b".to_string();
    let bad_cty = || kw(r#"{"cty":"JOSE"}"#);
    let zipped = || kw(r#"{"zip":"DEF"}"#);
    let enc_fail = || kw("{}").aad(b"aad".to_vec());
    let both = |c: &str| kw(&format!(r#"{{"cty":"JOSE","zip":"{c}"}}"#));
    // (input, encryptor, expected code)
    let cases: Vec<(&str, Encryptor, &str)> = vec![
        // shape beats everything
        (&bad_shape, kw("{}"), "InvalidFormat"),
        (&bad_shape, bad_cty(), "InvalidFormat"),
        (&bad_shape, zipped(), "InvalidFormat"),
        (&bad_shape, enc_fail(), "InvalidFormat"),
        // inner alg beats cty, zip, encrypt
        (&none, bad_cty(), "AlgorithmNotAllowed"),
        (&none, zipped(), "AlgorithmNotAllowed"),
        (&none, enc_fail(), "AlgorithmNotAllowed"),
        (&no_alg, bad_cty(), "InvalidHeader"),
        (&no_alg, zipped(), "InvalidHeader"),
        // cty beats zip and encrypt
        (&good, both("DEF"), "InvalidHeader"),
        (&good, bad_cty().aad(b"x".to_vec()), "InvalidHeader"),
        // zip beats encrypt
        (&good, zipped().aad(b"x".to_vec()), "InvalidHeader"),
        // encrypt last
        (&good, enc_fail(), "ok_or_other"),
    ];
    for (input, e, want) in cases {
        let got = jwt::encrypt_nested(input, &e);
        if want == "ok_or_other" {
            assert!(got.is_err(), "encrypt failure must surface");
            continue;
        }
        assert_eq!(code(got), want, "{input}");
    }
    // distinguish the two invalid_header causes
    assert_eq!(
        jwt::encrypt_nested(&no_alg, &bad_cty()),
        Err(Error::InvalidHeader("alg"))
    );
    assert_eq!(
        jwt::encrypt_nested(&good, &both("DEF")),
        Err(Error::InvalidHeader("cty"))
    );
    assert_eq!(
        jwt::encrypt_nested(&good, &zipped().aad(b"x".to_vec())),
        Err(Error::InvalidHeader("zip"))
    );
    assert_eq!(
        jwt::encrypt_nested(&none, &zipped()),
        Err(Error::AlgorithmNotAllowed)
    );
}

/// Only the protected header is decoded: a payload part that is not valid
/// base64url (but is base64url characters) never changes the result.
#[test]
fn encrypt_nested_never_decodes_the_payload() {
    let h = |s: &str| b64url_encode(s.as_bytes());
    // "A" and "QR" are not canonical base64url quanta; "####" is not chars.
    for payload in ["A", "QR", "AAAAA", "_-_-_"] {
        let ok = format!("{}.{payload}.c2ln", h(r#"{"alg":"ES256"}"#));
        assert_eq!(code(jwt::encrypt_nested(&ok, &kw("{}"))), "ok", "{payload}");
        let none = format!("{}.{payload}.c2ln", h(r#"{"alg":"none"}"#));
        assert_eq!(
            jwt::encrypt_nested(&none, &kw("{}")),
            Err(Error::AlgorithmNotAllowed),
            "{payload}"
        );
    }
    // Empty payload part is shape-valid too.
    let empty = format!("{}..c2ln", h(r#"{"alg":"ES256"}"#));
    assert_eq!(code(jwt::encrypt_nested(&empty, &kw("{}"))), "ok");
}

/// Odd inner `alg` spellings: duplicates are a parse error (InvalidFormat,
/// as documented), null/number/array are `InvalidHeader("alg")`, and an
/// escaped spelling of `none` is still `none` after JSON unescaping.
#[test]
fn encrypt_nested_inner_alg_edge_spellings() {
    let hdr = |h: &str| format!("{}.eyJ9.c2ln", b64url_encode(h.as_bytes()));
    for h in [
        r#"{"alg":"none","alg":"ES256"}"#,
        r#"{"alg":"ES256","alg":"none"}"#,
    ] {
        assert!(
            matches!(
                jwt::encrypt_nested(&hdr(h), &kw("{}")),
                Err(Error::InvalidFormat(_))
            ),
            "{h}"
        );
    }
    for h in [r#"{"alg":null}"#, r#"{"alg":1}"#, r#"{"alg":true}"#] {
        assert_eq!(
            jwt::encrypt_nested(&hdr(h), &kw("{}")),
            Err(Error::InvalidHeader("alg")),
            "{h}"
        );
    }
    assert_eq!(
        jwt::encrypt_nested(&hdr(r#"{"alg":"none"}"#), &kw("{}")),
        Err(Error::AlgorithmNotAllowed)
    );
    // A JSON-escaped spelling of `none` is still `none` once unescaped.
    assert_eq!(
        jwt::encrypt_nested(&hdr("{\"alg\":\"\\u006eone\"}"), &kw("{}")),
        Err(Error::AlgorithmNotAllowed)
    );
}