jose-rs 0.14.0

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

use crate::algorithm::{JweAlgorithm, JweEncryption};
use crate::base64url;
use crate::error::{JoseError, Result};
use crate::header::JoseHeader;

use crate::jwe::internal::{
    self, all_enc_algorithms, ensure_token_size, jwe_alg_decrypt_op, jwe_alg_encrypt_op,
    parse_envelope, recipient_key, recover_cek, KeyMaterial,
};

pub use crate::jwe::internal::{JweDecryptOptions, JweEncryptOptions};

/// Encrypt plaintext and produce a JWE Compact Serialization string.
///
/// - For `dir`: `key` is the CEK (must match the `enc` algorithm's key size).
/// - For `A128KW` / `A192KW` / `A256KW`: `key` is the Key Encryption Key.
/// - For `RSA-OAEP` / `RSA-OAEP-256`: `key` is the RSA public key in SPKI DER
///   format.
pub fn encrypt(
    key: &[u8],
    plaintext: &[u8],
    alg: JweAlgorithm,
    enc: JweEncryption,
) -> Result<String> {
    encrypt_with_header(JoseHeader::for_jwe(alg, enc), key, plaintext, alg, enc)
}

/// Encrypt plaintext with an explicit authenticated protected header.
///
/// Key formats are the same as for [`encrypt`]. The header's `alg` and `enc`
/// must match the supplied algorithms (RFC 8725 ยง3.1). Every serialized
/// header member is authenticated as additional authenticated data; changing
/// it invalidates the token. JWK metadata is not checked by this raw-key API;
/// use [`encrypt_with_jwk_header`] to enforce JWK operation permissions.
///
/// Uses the strict [`JweEncryptOptions::new`] policy; see
/// [`encrypt_with_header_options`] to permit key-reference members.
///
/// # Errors
///
/// Returns [`JoseError::InvalidHeader`] when:
///
/// - `header.alg` / `header.enc` disagree with `alg` / `enc`;
/// - `header.extra` repeats a member that a typed [`JoseHeader`] field
///   already serializes (`alg`, `enc`, `kid`, `typ`, `cty`, `jku`, `jwk`,
///   `x5u`, `x5c`, `x5t`, `x5t#S256`, `crit`), which would put an ambiguous
///   duplicate key in the protected header (RFC 7515 ยง4);
/// - `header.extra` contains a registered member this crate does not
///   implement for JWE compact: `zip` (compression, which RFC 8725 ยง3.6
///   advises against), `b64`, `epk`, `apu`, `apv`, `p2s`, `p2c`, `iv` or
///   `tag`;
/// - `header.crit` is set (no JWE critical extensions are implemented);
/// - the header carries `jku`, `jwk`, `x5u` or `x5c` (see
///   [`JweEncryptOptions::allow_key_reference_headers`]);
/// - the encoded header exceeds [`crate::MAX_TOKEN_BYTES`].
///
/// Returns [`JoseError::InvalidToken`] when the resulting token would exceed
/// [`crate::MAX_TOKEN_BYTES`]. Together these mirror [`decrypt`], so every
/// token this function returns can be decrypted by this crate. Other errors
/// are returned for unsupported algorithms, invalid key material or key
/// sizes, or an encryption failure.
pub fn encrypt_with_header(
    header: JoseHeader,
    key: &[u8],
    plaintext: &[u8],
    alg: JweAlgorithm,
    enc: JweEncryption,
) -> Result<String> {
    encrypt_with_header_options(header, key, plaintext, alg, enc, &JweEncryptOptions::new())
}

/// [`encrypt_with_header`] with explicit [`JweEncryptOptions`].
///
/// # Errors
///
/// As for [`encrypt_with_header`], except that key-reference members are
/// accepted when `opts.allow_key_reference_headers` is set.
pub fn encrypt_with_header_options(
    header: JoseHeader,
    key: &[u8],
    plaintext: &[u8],
    alg: JweAlgorithm,
    enc: JweEncryption,
    opts: &JweEncryptOptions,
) -> Result<String> {
    // RFC 7516 ยง7.1 defines no `aad` member, so this serialization cannot
    // honour external AAD. Refusing beats encrypting under an AAD the
    // recipient has no way to learn.
    ensure_no_external_aad(opts.external_aad())?;

    // Raw bytes can only mean a transported or wrapped key, so the key
    // agreement algorithms are unreachable from here by construction; see
    // [`KeyMaterial`].
    encrypt_with_header_options_material(
        header,
        KeyMaterial::Bytes(zeroize::Zeroizing::new(key.to_vec())),
        plaintext,
        alg,
        enc,
        opts,
    )
}

/// Shared compact-emit core for both key shapes.
fn encrypt_with_header_options_material(
    header: JoseHeader,
    key: KeyMaterial,
    plaintext: &[u8],
    alg: JweAlgorithm,
    enc: JweEncryption,
    opts: &JweEncryptOptions,
) -> Result<String> {
    ensure_no_external_aad(opts.external_aad())?;

    // All emit-side policy lives in the shared core, which the JSON
    // serializations call too; this function only joins the five parts.
    let core = internal::encrypt_core(&header, key, plaintext, alg, enc, opts, None)?;

    let encrypted_key_b64 = base64url::encode(&core.encrypted_key);
    let iv_b64 = base64url::encode(&core.iv);
    let ciphertext_b64 = base64url::encode(&core.ciphertext);
    let tag_b64 = base64url::encode(&core.tag);

    let token = format!(
        "{}.{}.{}.{}.{}",
        core.header_b64, encrypted_key_b64, iv_b64, ciphertext_b64, tag_b64
    );
    // `decrypt` refuses tokens over MAX_TOKEN_BYTES.
    crate::ensure_emit_size(token.len())?;
    Ok(token)
}

/// Encrypt plaintext using a JWK directly โ€” the one-shot JWE encrypt API.
///
/// The key management algorithm is read from `jwk.alg` and
/// `Jwk::check_op` is enforced: `Encrypt` for `dir`, `WrapKey` for
/// `A*KW` / `RSA-OAEP*`. The caller supplies the content-encryption
/// algorithm.
pub fn encrypt_with_jwk(
    jwk: &crate::jwk::Jwk,
    plaintext: &[u8],
    enc: JweEncryption,
) -> Result<String> {
    let jwk_alg_str = jwk
        .alg
        .as_deref()
        .ok_or_else(|| JoseError::Key("JWK alg must be set for encrypt_with_jwk".into()))?;
    let alg = JweAlgorithm::from_str(jwk_alg_str)?;
    jwk.check_op(jwe_alg_encrypt_op(alg))?;
    encrypt_with_header_options_material(
        JoseHeader::for_jwe(alg, enc),
        recipient_key(jwk, alg, false)?,
        plaintext,
        alg,
        enc,
        &JweEncryptOptions::new(),
    )
}

/// Encrypt plaintext using a JWK and an explicit authenticated protected header.
///
/// Refuse external additional authenticated data on the compact path.
///
/// The option is shared between serializations (`JweEncryptOptions` /
/// `JweDecryptOptions` are used by both), so each front end has to say what it
/// cannot do with it. Silent omission here would produce a token whose AAD
/// input differs from the one the sender believed it authenticated.
fn ensure_no_external_aad(external_aad: Option<&[u8]>) -> Result<()> {
    if external_aad.is_some() {
        return Err(JoseError::InvalidHeader(
            "external additional authenticated data requires the JWE JSON serialization \u{2014} \
             the compact form has no \"aad\" member (RFC 7516 \u{a7}7.1)"
                .into(),
        ));
    }
    Ok(())
}

/// The key-management algorithm comes from `jwk.alg`, which must be set and
/// match `header.alg`; `header.enc` must match `enc`. Enforces `Encrypt` for
/// `dir` and `WrapKey` for AES key wrap and RSA-OAEP. All serialized protected
/// header members are authenticated, allowing application fields such as
/// `kid`, `typ`, and `cty` without modifying the encryption implementation.
///
/// # Errors
///
/// Returns an error when the JWK algorithm or operation permissions reject
/// encryption, the header algorithms disagree, key material is invalid, or
/// encryption fails. The header is validated exactly as in
/// [`encrypt_with_header`] (duplicate typed members, unimplemented members
/// such as `zip`, `crit`, key-reference members, and the size limit), using
/// the strict [`JweEncryptOptions::new`] policy.
pub fn encrypt_with_jwk_header(
    jwk: &crate::jwk::Jwk,
    header: JoseHeader,
    plaintext: &[u8],
    enc: JweEncryption,
) -> Result<String> {
    encrypt_with_jwk_header_options(jwk, header, plaintext, enc, &JweEncryptOptions::new())
}

/// [`encrypt_with_jwk_header`] with explicit [`JweEncryptOptions`].
///
/// # Errors
///
/// As for [`encrypt_with_jwk_header`], except that key-reference members are
/// accepted when `opts.allow_key_reference_headers` is set.
pub fn encrypt_with_jwk_header_options(
    jwk: &crate::jwk::Jwk,
    header: JoseHeader,
    plaintext: &[u8],
    enc: JweEncryption,
    opts: &JweEncryptOptions,
) -> Result<String> {
    let jwk_alg_str = jwk
        .alg
        .as_deref()
        .ok_or_else(|| JoseError::Key("JWK alg must be set for encrypt_with_jwk".into()))?;
    let alg = JweAlgorithm::from_str(jwk_alg_str)?;
    jwk.check_op(jwe_alg_encrypt_op(alg))?;
    encrypt_with_header_options_material(
        header,
        recipient_key(jwk, alg, false)?,
        plaintext,
        alg,
        enc,
        opts,
    )
}

/// The three PBES2 algorithms, as an allow-list.
///
/// A password has nothing that can pin an algorithm: a JWK carries `alg` and a password
/// carries nothing, so the token header would otherwise name the key-management mode and
/// that alone decides how the password is consumed. Restricting the list to the
/// password family is what makes the substitution attack on `alg` structurally
/// impossible here: a message claiming `dir` or `A128KW` is refused before the password
/// reaches anything, because a password must never be handed to an algorithm that would
/// use its bytes as a key.
pub(crate) fn pbes2_algorithms() -> Vec<JweAlgorithm> {
    vec![
        JweAlgorithm::Pbes2Hs256A128kw,
        JweAlgorithm::Pbes2Hs384A192kw,
        JweAlgorithm::Pbes2Hs512A256kw,
    ]
}

/// Encrypt a JWE Compact Serialization with a password (RFC 7518 ยง4.8).
///
/// `alg` must be one of the three PBES2 algorithms; anything else is refused rather
/// than reinterpreted, because the alternatives would use the password's bytes directly
/// as a key.
///
/// The iteration count is
/// [`PBES2_DEFAULT_ITERATIONS`](crate::jwe::password::PBES2_DEFAULT_ITERATIONS) unless
/// [`JweEncryptOptions::with_pbes2_iterations`] changes it โ€” see that method for why
/// raising it is spending someone else's CPU. The salt input is fresh per message and
/// 16 octets long.
///
/// ```no_run
/// use jose_rs::algorithm::{JweAlgorithm, JweEncryption};
/// use jose_rs::jwe::{compact, Password};
///
/// let token = compact::encrypt_with_password(
///     &Password::from_utf8("a passphrase"),
///     b"payload",
///     JweAlgorithm::Pbes2Hs256A128kw,
///     JweEncryption::A128GCM,
/// )
/// .unwrap();
/// ```
///
/// # Errors
///
/// [`crate::JoseError::Key`] for a non-PBES2 `alg` or an empty password,
/// [`crate::JoseError::InvalidHeader`] for an iteration count below the floor, and the
/// usual header/serialization errors.
pub fn encrypt_with_password(
    password: &crate::jwe::password::Password,
    plaintext: &[u8],
    alg: JweAlgorithm,
    enc: JweEncryption,
) -> Result<String> {
    encrypt_with_password_options(password, plaintext, alg, enc, &JweEncryptOptions::new())
}

/// [`encrypt_with_password`] with the caller's [`JweEncryptOptions`].
pub fn encrypt_with_password_options(
    password: &crate::jwe::password::Password,
    plaintext: &[u8],
    alg: JweAlgorithm,
    enc: JweEncryption,
    opts: &JweEncryptOptions,
) -> Result<String> {
    let header = JoseHeader::for_jwe(alg, enc);
    encrypt_with_password_header_options(password, header, plaintext, alg, enc, opts)
}

/// [`encrypt_with_password`] with a caller-supplied header.
///
/// `p2s` and `p2c` are generated by the library and a header carrying either is refused,
/// as they are for every algorithm: the salt is a nonce and the count is the recipient's
/// work budget.
pub fn encrypt_with_password_header(
    password: &crate::jwe::password::Password,
    header: JoseHeader,
    plaintext: &[u8],
    alg: JweAlgorithm,
    enc: JweEncryption,
) -> Result<String> {
    encrypt_with_password_header_options(
        password,
        header,
        plaintext,
        alg,
        enc,
        &JweEncryptOptions::new(),
    )
}

/// [`encrypt_with_password_header`] with the caller's [`JweEncryptOptions`].
pub fn encrypt_with_password_header_options(
    password: &crate::jwe::password::Password,
    header: JoseHeader,
    plaintext: &[u8],
    alg: JweAlgorithm,
    enc: JweEncryption,
    opts: &JweEncryptOptions,
) -> Result<String> {
    encrypt_with_header_options_material(
        header,
        internal::password_key(password, alg)?,
        plaintext,
        alg,
        enc,
        opts,
    )
}

/// Decrypt a JWE Compact Serialization with a password.
///
/// The key-management algorithm cannot be pinned to the secret here (a password has no
/// `alg`), so the pin is provided by the type instead: the allow-list is the three PBES2
/// algorithms, so a message naming `dir`, `A128KW`, `RSA-OAEP-256` or an ECDH mode is
/// refused before the password is offered to anything. Pass
/// [`decrypt_with_password_options`] a narrower list to pin a single PBES2 variant.
///
/// A wrong password fails at the wrapped key's integrity check and is reported as such โ€”
/// PBES2 has no implicit rejection to preserve, since RFC 3394's wrap authenticates.
///
/// # Errors
///
/// As for [`decrypt_with_jwk`], plus the work-budget refusal: a `p2c` above
/// [`JweDecryptOptions::pbes2_max_iterations`] is rejected before any derivation, so a
/// sender cannot bill this process for CPU.
pub fn decrypt_with_password(
    password: &crate::jwe::password::Password,
    token: &str,
) -> Result<Vec<u8>> {
    // Pin to the password family, and let nothing else in: the header's `alg` selects
    // which PBES2 variant runs, which is harmless (each derives a different key), while
    // a byte-key algorithm reaching a password is not harmless and is refused here.
    let options = JweDecryptOptions::new(pbes2_algorithms(), all_enc_algorithms());
    decrypt_with_password_options(password, token, &options)
}

/// [`decrypt_with_password`] with the caller's [`JweDecryptOptions`].
///
/// The options' algorithm allow-list is honoured as given, but a list containing
/// anything outside the PBES2 family is narrowed to the family: this function's whole
/// purpose is that a password is only ever consumed by a password-based algorithm.
pub fn decrypt_with_password_options(
    password: &crate::jwe::password::Password,
    token: &str,
    options: &JweDecryptOptions,
) -> Result<Vec<u8>> {
    let header = decode_header(token)?;
    let alg = JweAlgorithm::from_str(&header.alg)?;
    if !pbes2_algorithms().contains(&alg) {
        return Err(JoseError::Key(format!(
            "{} is not a password-based algorithm, so no password is offered to it; use the \
             key APIs (RFC 7518 \u{a7}4.8)",
            alg.as_str()
        )));
    }
    // `options` is honoured exactly as the caller set it โ€” content allow-list, plaintext
    // limit, external AAD, `crit`, work budget. Nothing here narrows it, because the
    // boundary does not need narrowing to hold: `alg` was just checked against the
    // password family, `password_key` refuses a non-PBES2 algorithm, and `recover_cek`
    // accepts a password only for PBES2. Three independent layers, none of them a
    // silently overridden caller setting.
    let key = internal::password_key(password, alg)?;
    decrypt_with_options_material(&key, token, options)
}

/// Decrypt a JWE token using a JWK directly โ€” the one-shot JWE decrypt API.
///
/// The JWK MUST pin `alg`: the key-management algorithm is bound to the
/// key, not taken from the attacker-controlled token header. The token's
/// header `alg` must agree with `jwk.alg`, and the decrypt path is run
/// through an allow-list pinned to that single algorithm so a substituted
/// header `alg` is rejected before any key material is touched.
/// `Jwk::check_op` is enforced: `Decrypt` for `dir`, `UnwrapKey` for
/// `A*KW` / `RSA-OAEP*`.
pub fn decrypt_with_jwk(jwk: &crate::jwk::Jwk, token: &str) -> Result<Vec<u8>> {
    // Read the header's alg for dispatch.
    let header = decode_header(token)?;
    let alg = JweAlgorithm::from_str(&header.alg)?;

    // The JWK must pin alg โ€” otherwise the key-management algorithm would be
    // dictated entirely by the token header (algorithm-substitution risk when
    // a single key is reused across configurations).
    let jwk_alg = jwk
        .alg
        .as_deref()
        .ok_or_else(|| JoseError::Key("JWK alg must be set for decrypt_with_jwk".into()))?;
    if jwk_alg != header.alg {
        return Err(JoseError::InvalidToken(format!(
            "JWK alg {jwk_alg} does not match token header alg {}",
            header.alg
        )));
    }

    jwk.check_op(jwe_alg_decrypt_op(alg))?;
    let key = recipient_key(jwk, alg, true)?;

    // Pin the key-management algorithm to the JWK's alg. Content encryption
    // (`enc`) stays flexible โ€” its key length is bound to the CEK size and
    // re-validated in the key-management layer โ€” so we permit every supported
    // `enc`.
    let options = JweDecryptOptions::new(vec![alg], all_enc_algorithms());
    decrypt_with_options_material(&key, token, &options)
}

/// Decrypt a JWE and return the plaintext with the header the AEAD tag authenticated.
///
/// The protected header is included in the AEAD additional-authenticated-data, so the
/// copy returned here is the one the tag covered โ€” the distinction matters most when a
/// caller is deciding *what the plaintext may be used for* from `zip`, `cty` or a
/// private member, and a forged unprotected value would otherwise steer that decision.
pub fn decrypt_with_jwk_authenticated(
    jwk: &crate::jwk::Jwk,
    token: &str,
) -> Result<crate::Authenticated<Vec<u8>>> {
    let plaintext = decrypt_with_jwk(jwk, token)?;
    let protected = decode_header(token)?;
    Ok(crate::Authenticated::new(plaintext, protected, Vec::new()))
}

/// Decrypt a JWE Compact Serialization string and return the plaintext.
///
/// Accepts any key-management / content-encryption algorithm the library
/// supports. For strict deployments, use [`decrypt_with_options`] to pin
/// an explicit allow-list.
///
/// - For `dir`: `key` is the CEK.
/// - For `A128KW` / `A192KW` / `A256KW`: `key` is the Key Encryption Key.
/// - For `RSA-OAEP` / `RSA-OAEP-256`: `key` is the RSA private key in PKCS#8
///   DER format.
pub fn decrypt(key: &[u8], token: &str) -> Result<Vec<u8>> {
    decrypt_with_options(key, token, &JweDecryptOptions::permissive())
}

/// Decrypt a JWE Compact Serialization token, enforcing the caller's
/// algorithm allow-list.
///
/// Rejects the token before any cryptographic operation if its `alg` or
/// `enc` header is outside the allow-list supplied via `options`.
/// Enforces [`JweDecryptOptions::with_max_plaintext`] when configured. No
/// plaintext is returned until authentication and the exact size check pass.
pub fn decrypt_with_options(
    key: &[u8],
    token: &str,
    options: &JweDecryptOptions,
) -> Result<Vec<u8>> {
    decrypt_with_options_material(
        &KeyMaterial::Bytes(zeroize::Zeroizing::new(key.to_vec())),
        token,
        options,
    )
}

/// Shared compact-decrypt core for both key shapes.
///
/// The protected header is kept (not discarded as the raw-key path used to do)
/// because key agreement reads the peer value `epk` from it โ€” the
/// integrity-protected one, which is the only place a peer key is believed.
fn decrypt_with_options_material(
    key: &KeyMaterial,
    token: &str,
    options: &JweDecryptOptions,
) -> Result<Vec<u8>> {
    ensure_token_size(token)?;
    // Symmetric with the emit side: a compact token cannot carry external
    // additional authenticated data, so options that supply it mean the caller
    // is holding the wrong serialization, not that the tag will simply fail.
    ensure_no_external_aad(options.external_aad())?;

    // 1. Parse compact serialization.
    let parts: Vec<&str> = token.splitn(6, '.').collect();
    if parts.len() != 5 {
        return Err(JoseError::InvalidToken(
            "JWE compact serialization must have 5 dot-separated parts".into(),
        ));
    }

    let (header_b64, encrypted_key_b64, iv_b64, ciphertext_b64, tag_b64) =
        (parts[0], parts[1], parts[2], parts[3], parts[4]);

    // 2. Decode the protected header, apply the shared header policy, and
    //    decode the remaining parts. The verbatim `header_b64` is kept for
    //    use as additional authenticated data.
    // The compact serialization exposes no header to the caller, so the
    // parsed protected header is discarded here; the JSON serializations
    // return it as authenticated metadata.
    // RFC 7516 ยง7.1 defines no unprotected header member, so `alg` cannot
    // legitimately come from anywhere but the protected header here.
    let (envelope, protected) = parse_envelope(
        header_b64,
        None,
        encrypted_key_b64,
        iv_b64,
        ciphertext_b64,
        tag_b64,
        options,
    )?;

    // 3. Recover CEK.
    let cek = recover_cek(
        key,
        envelope.alg,
        envelope.enc,
        &envelope.encrypted_key,
        &protected,
        options.pbes2_max_iterations(),
    )?;

    // 4. Content decryption; AAD = ASCII(BASE64URL(header)).
    let aad = envelope.header_b64.as_bytes();
    internal::finish_decrypt(&envelope, &cek, aad, options)
}

/// Decode the protected header from a JWE compact token without decrypting.
pub fn decode_header(token: &str) -> Result<JoseHeader> {
    ensure_token_size(token)?;
    let header_b64 = token
        .split('.')
        .next()
        .ok_or_else(|| JoseError::InvalidToken("empty token".into()))?;
    let header_json = base64url::decode(header_b64)?;
    serde_json::from_slice(&header_json).map_err(Into::into)
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::algorithm::{JweAlgorithm, JweEncryption};
    use crate::jwe::internal::{jwe_alg_to_keytransport, parse_rsa_public_key};

    // -- dir + AES-GCM roundtrips --

    #[test]
    fn dir_a256gcm_roundtrip() {
        let cek = [0x42u8; 32]; // 256-bit CEK for A256GCM
        let plaintext = b"Hello, JWE world!";

        let token = encrypt(&cek, plaintext, JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        // Should have 5 dot-separated parts.
        assert_eq!(token.split('.').count(), 5);

        // Encrypted key part should be empty for dir.
        let parts: Vec<&str> = token.splitn(5, '.').collect();
        assert_eq!(parts[1], "", "dir: encrypted key must be empty");

        let recovered = decrypt(&cek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    #[test]
    fn dir_a128gcm_roundtrip() {
        let cek = [0x33u8; 16];
        let plaintext = b"AES-128-GCM test";

        let token = encrypt(&cek, plaintext, JweAlgorithm::Dir, JweEncryption::A128GCM).unwrap();
        let recovered = decrypt(&cek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    #[test]
    fn dir_a192gcm_roundtrip() {
        let cek = [0x55u8; 24];
        let plaintext = b"AES-192-GCM test";

        let token = encrypt(&cek, plaintext, JweAlgorithm::Dir, JweEncryption::A192GCM).unwrap();
        let recovered = decrypt(&cek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    // -- AES Key Wrap + AES-GCM roundtrips --

    #[test]
    fn a256kw_a128gcm_roundtrip() {
        let kek = [0xABu8; 32]; // 256-bit KEK
        let plaintext = b"Wrapped key encryption test";

        let token = encrypt(
            &kek,
            plaintext,
            JweAlgorithm::A256KW,
            JweEncryption::A128GCM,
        )
        .unwrap();

        // Encrypted key part must not be empty for key wrapping.
        let parts: Vec<&str> = token.splitn(5, '.').collect();
        assert!(
            !parts[1].is_empty(),
            "A256KW: encrypted key must not be empty"
        );

        let recovered = decrypt(&kek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    #[test]
    fn a128kw_a256gcm_roundtrip() {
        let kek = [0xCDu8; 16]; // 128-bit KEK
        let plaintext = b"A128KW + A256GCM";

        let token = encrypt(
            &kek,
            plaintext,
            JweAlgorithm::A128KW,
            JweEncryption::A256GCM,
        )
        .unwrap();
        let recovered = decrypt(&kek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    #[test]
    fn a192kw_a256gcm_roundtrip() {
        let kek = [0xEFu8; 24]; // 192-bit KEK
        let plaintext = b"A192KW + A256GCM";

        let token = encrypt(
            &kek,
            plaintext,
            JweAlgorithm::A192KW,
            JweEncryption::A256GCM,
        )
        .unwrap();
        let recovered = decrypt(&kek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    // -- RSA-OAEP + AES-GCM roundtrips --

    fn generate_rsa_keypair() -> (Vec<u8>, Vec<u8>) {
        use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey};
        let mut rng = getrandom::rand_core::UnwrapErr(getrandom::SysRng);
        let private_key = rsa::PrivateKey::new(&mut rng, 2048).unwrap();
        let public_key = rsa::PublicKey::from(&private_key);

        let pub_der = public_key.to_public_key_der().unwrap();
        let priv_der = private_key.to_pkcs8_der().unwrap();

        (pub_der.as_ref().to_vec(), priv_der.as_bytes().to_vec())
    }

    #[cfg(feature = "rsa-oaep")]
    #[test]
    fn rsa_oaep_a256gcm_roundtrip() {
        let (pub_der, priv_der) = generate_rsa_keypair();
        let plaintext = b"RSA-OAEP encrypted message";

        let token = encrypt(
            &pub_der,
            plaintext,
            JweAlgorithm::RsaOaep,
            JweEncryption::A256GCM,
        )
        .unwrap();
        let recovered = decrypt(&priv_der, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    #[test]
    fn rsa_oaep_256_a256gcm_roundtrip() {
        let (pub_der, priv_der) = generate_rsa_keypair();
        let plaintext = b"RSA-OAEP-256 encrypted message";

        let token = encrypt(
            &pub_der,
            plaintext,
            JweAlgorithm::RsaOaep256,
            JweEncryption::A256GCM,
        )
        .unwrap();
        let recovered = decrypt(&priv_der, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    fn assert_rsa_oaep_failure_classes_are_indistinguishable(alg: JweAlgorithm) {
        let (pub_der, priv_der) = generate_rsa_keypair();
        let public_key = parse_rsa_public_key(&pub_der).unwrap();

        for enc in [JweEncryption::A256GCM, JweEncryption::A256CbcHs512] {
            let token = encrypt(&pub_der, b"RSA-OAEP implicit rejection", alg, enc).unwrap();
            let parts: Vec<&str> = token.splitn(5, '.').collect();

            // An all-zero RSA ciphertext deterministically fails OAEP decoding.
            let encrypted_key = base64url::decode(parts[1]).unwrap();
            let invalid_oaep = format!(
                "{}.{}.{}.{}.{}",
                parts[0],
                base64url::encode(&vec![0; encrypted_key.len()]),
                parts[2],
                parts[3],
                parts[4]
            );

            // A valid OAEP ciphertext carrying the wrong CEK length must take
            // the same implicit-rejection path as an OAEP decoding failure.
            let short_cek = kryptering::keytransport::kt_encrypt(
                jwe_alg_to_keytransport(alg).unwrap(),
                &public_key,
                &[0x42],
                None,
            )
            .unwrap();
            let invalid_cek_length = format!(
                "{}.{}.{}.{}.{}",
                parts[0],
                base64url::encode(&short_cek),
                parts[2],
                parts[3],
                parts[4]
            );

            // Preserve the valid RSA-OAEP ciphertext and invalidate only the
            // content-authentication tag.
            let mut tag = base64url::decode(parts[4]).unwrap();
            tag[0] ^= 1;
            let invalid_tag = format!(
                "{}.{}.{}.{}.{}",
                parts[0],
                parts[1],
                parts[2],
                parts[3],
                base64url::encode(&tag)
            );

            let unwrap_error = decrypt(&priv_der, &invalid_oaep).unwrap_err().to_string();
            let cek_length_error = decrypt(&priv_der, &invalid_cek_length)
                .unwrap_err()
                .to_string();
            let content_error = decrypt(&priv_der, &invalid_tag).unwrap_err().to_string();

            assert_eq!(
                unwrap_error,
                content_error,
                "failure oracle for {}/{}",
                alg.as_str(),
                enc.as_str()
            );
            assert_eq!(
                cek_length_error,
                content_error,
                "CEK-length oracle for {}/{}",
                alg.as_str(),
                enc.as_str()
            );
            assert!(!unwrap_error.contains("OAEP"), "unexpected: {unwrap_error}");
        }
    }

    /// RSA-OAEP implicit rejection must make an invalid wrapped CEK
    /// indistinguishable from a valid unwrap followed by failed content
    /// authentication.
    #[test]
    fn rsa_oaep_failure_classes_are_indistinguishable() {
        assert_rsa_oaep_failure_classes_are_indistinguishable(JweAlgorithm::RsaOaep256);
    }

    /// The deprecated SHA-1 RSA-OAEP variant shares the same implicit-
    /// rejection guarantee.
    #[cfg(feature = "rsa-oaep")]
    #[test]
    fn deprecated_rsa_oaep_failure_classes_are_indistinguishable() {
        assert_rsa_oaep_failure_classes_are_indistinguishable(JweAlgorithm::RsaOaep);
    }

    // -- AES-CBC-HS roundtrips --

    #[test]
    fn a128cbc_hs256_roundtrip() {
        let cek = [0x42u8; 32]; // 32-byte CEK: 16 HMAC + 16 AES
        let plaintext = b"AES-128-CBC-HS256 test";

        let token = encrypt(
            &cek,
            plaintext,
            JweAlgorithm::Dir,
            JweEncryption::A128CbcHs256,
        )
        .unwrap();
        let recovered = decrypt(&cek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    #[test]
    fn a192cbc_hs384_roundtrip() {
        let cek = [0x55u8; 48]; // 48-byte CEK: 24 HMAC + 24 AES
        let plaintext = b"AES-192-CBC-HS384 test";

        let token = encrypt(
            &cek,
            plaintext,
            JweAlgorithm::Dir,
            JweEncryption::A192CbcHs384,
        )
        .unwrap();
        let recovered = decrypt(&cek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    #[test]
    fn a256cbc_hs512_roundtrip() {
        let cek = [0x77u8; 64]; // 64-byte CEK: 32 HMAC + 32 AES
        let plaintext = b"AES-256-CBC-HS512 test";

        let token = encrypt(
            &cek,
            plaintext,
            JweAlgorithm::Dir,
            JweEncryption::A256CbcHs512,
        )
        .unwrap();
        let recovered = decrypt(&cek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    #[test]
    fn a256kw_a128cbc_hs256_roundtrip() {
        let kek = [0xBBu8; 32]; // 256-bit KEK
        let plaintext = b"Key-wrapped CBC-HS test";

        let token = encrypt(
            &kek,
            plaintext,
            JweAlgorithm::A256KW,
            JweEncryption::A128CbcHs256,
        )
        .unwrap();
        let recovered = decrypt(&kek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    // -- Error cases --

    #[test]
    fn wrong_key_fails_decryption_gcm() {
        let key1 = [0x42u8; 32];
        let key2 = [0x99u8; 32];
        let plaintext = b"secret data";

        let token = encrypt(&key1, plaintext, JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();
        let result = decrypt(&key2, &token);
        assert!(result.is_err(), "decryption with wrong key should fail");
    }

    #[test]
    fn wrong_key_fails_decryption_cbc_hs() {
        let key1 = [0x42u8; 32];
        let key2 = [0x99u8; 32];
        let plaintext = b"secret data";

        let token = encrypt(
            &key1,
            plaintext,
            JweAlgorithm::Dir,
            JweEncryption::A128CbcHs256,
        )
        .unwrap();
        let result = decrypt(&key2, &token);
        assert!(result.is_err(), "decryption with wrong key should fail");
    }

    #[test]
    fn malformed_token_returns_error() {
        let key = [0x42u8; 32];

        // Too few parts.
        let result = decrypt(&key, "one.two.three");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("5 dot-separated parts"),
            "unexpected error: {err}"
        );

        // Empty string.
        let result = decrypt(&key, "");
        assert!(result.is_err());
    }

    #[test]
    fn tampered_ciphertext_fails_gcm() {
        let key = [0x42u8; 32];
        let plaintext = b"integrity test";

        let token = encrypt(&key, plaintext, JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        // Tamper with the ciphertext part (fourth segment).
        let parts: Vec<&str> = token.splitn(5, '.').collect();
        let mut ct_bytes = base64url::decode(parts[3]).unwrap();
        if !ct_bytes.is_empty() {
            ct_bytes[0] ^= 0xFF;
        }
        let tampered_ct = base64url::encode(&ct_bytes);
        let tampered_token = format!(
            "{}.{}.{}.{}.{}",
            parts[0], parts[1], parts[2], tampered_ct, parts[4]
        );

        let result = decrypt(&key, &tampered_token);
        assert!(result.is_err(), "tampered ciphertext should fail GCM auth");
    }

    #[test]
    fn tampered_ciphertext_fails_cbc_hs() {
        let key = [0x42u8; 64];
        let plaintext = b"integrity test cbc";

        let token = encrypt(
            &key,
            plaintext,
            JweAlgorithm::Dir,
            JweEncryption::A256CbcHs512,
        )
        .unwrap();

        // Tamper with the ciphertext part (fourth segment).
        let parts: Vec<&str> = token.splitn(5, '.').collect();
        let mut ct_bytes = base64url::decode(parts[3]).unwrap();
        if !ct_bytes.is_empty() {
            ct_bytes[0] ^= 0xFF;
        }
        let tampered_ct = base64url::encode(&ct_bytes);
        let tampered_token = format!(
            "{}.{}.{}.{}.{}",
            parts[0], parts[1], parts[2], tampered_ct, parts[4]
        );

        let result = decrypt(&key, &tampered_token);
        assert!(
            result.is_err(),
            "tampered ciphertext should fail CBC-HS auth"
        );
    }

    #[test]
    fn dir_wrong_cek_size_fails() {
        let key = [0x42u8; 15]; // Wrong size for any algorithm
        let plaintext = b"test";

        let result = encrypt(&key, plaintext, JweAlgorithm::Dir, JweEncryption::A256GCM);
        assert!(result.is_err());
    }

    #[test]
    fn decode_header_works() {
        let cek = [0x42u8; 32];
        let plaintext = b"header test";

        let token = encrypt(&cek, plaintext, JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        let header = decode_header(&token).unwrap();
        assert_eq!(header.alg, "dir");
        assert_eq!(header.enc.as_deref(), Some("A256GCM"));
    }

    #[test]
    fn empty_plaintext_roundtrip() {
        let cek = [0x42u8; 32];
        let plaintext = b"";

        let token = encrypt(&cek, plaintext, JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();
        let recovered = decrypt(&cek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    #[test]
    fn large_plaintext_roundtrip() {
        let cek = [0x42u8; 32];
        let plaintext: Vec<u8> = (0..10_000).map(|i| (i % 256) as u8).collect();

        let token = encrypt(&cek, &plaintext, JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();
        let recovered = decrypt(&cek, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    /// Phase 9: encrypt_with_jwk + decrypt_with_jwk roundtrip, dir + A256GCM.
    #[test]
    fn jwk_dir_roundtrip() {
        let mut jwk = crate::jwk::generate_symmetric(32).unwrap();
        jwk.alg = Some("dir".into());
        let plaintext = b"jwk-dir";

        let token = encrypt_with_jwk(&jwk, plaintext, JweEncryption::A256GCM).unwrap();
        let recovered = decrypt_with_jwk(&jwk, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    /// Phase 9: encrypt_with_jwk + decrypt_with_jwk roundtrip, A256KW + A128GCM.
    #[test]
    fn jwk_aes_kw_roundtrip() {
        let mut jwk = crate::jwk::generate_symmetric(32).unwrap();
        jwk.alg = Some("A256KW".into());
        let plaintext = b"jwk-a256kw";

        let token = encrypt_with_jwk(&jwk, plaintext, JweEncryption::A128GCM).unwrap();
        let recovered = decrypt_with_jwk(&jwk, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    /// JWE symmetric one-shot APIs must not accept non-oct JWKs just because
    /// they carry a stray `k` parameter.
    #[test]
    fn jwk_symmetric_alg_rejects_non_oct_kty() {
        for alg in ["dir", "A256KW"] {
            let mut jwk = crate::jwk::generate_symmetric(32).unwrap();
            jwk.kty = "RSA".into();
            jwk.alg = Some(alg.into());

            let err = encrypt_with_jwk(&jwk, b"p", JweEncryption::A256GCM)
                .unwrap_err()
                .to_string();
            assert!(err.contains("requires kty oct"), "unexpected: {err}");
        }
    }

    /// Phase 9: encrypt_with_jwk + decrypt_with_jwk roundtrip, RSA-OAEP-256.
    #[test]
    fn jwk_rsa_oaep_roundtrip() {
        let mut jwk = crate::jwk::generate_rsa(2048).unwrap();
        jwk.alg = Some("RSA-OAEP-256".into());
        let plaintext = b"jwk-rsa-oaep";

        let token = encrypt_with_jwk(&jwk, plaintext, JweEncryption::A256GCM).unwrap();
        let recovered = decrypt_with_jwk(&jwk, &token).unwrap();
        assert_eq!(recovered, plaintext);
    }

    /// Phase 9: encrypt_with_jwk rejects JWK with no alg.
    #[test]
    fn jwk_encrypt_requires_alg() {
        let jwk = crate::jwk::generate_symmetric(32).unwrap();
        let err = encrypt_with_jwk(&jwk, b"p", JweEncryption::A256GCM)
            .unwrap_err()
            .to_string();
        assert!(err.contains("alg must be set"), "unexpected: {err}");
    }

    /// Phase 9: encrypt_with_jwk honours use="sig" โ†’ reject.
    #[test]
    fn jwk_encrypt_rejects_use_sig() {
        let mut jwk = crate::jwk::generate_symmetric(32).unwrap();
        jwk.alg = Some("dir".into());
        jwk.use_ = Some("sig".into());
        let err = encrypt_with_jwk(&jwk, b"p", JweEncryption::A256GCM)
            .unwrap_err()
            .to_string();
        assert!(err.contains("`use` is sig"), "unexpected: {err}");
    }

    /// Phase 9: decrypt_with_jwk rejects use="sig" โ†’ reject.
    #[test]
    fn jwk_decrypt_rejects_use_sig() {
        let mut jwk = crate::jwk::generate_symmetric(32).unwrap();
        jwk.alg = Some("dir".into());
        // Encrypt using raw bytes to build a token, then flip use before decrypt.
        let k = crate::base64url::decode(jwk.k.as_ref().unwrap()).unwrap();
        let token = encrypt(&k, b"p", JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        jwk.use_ = Some("sig".into());
        let err = decrypt_with_jwk(&jwk, &token).unwrap_err().to_string();
        assert!(err.contains("`use` is sig"), "unexpected: {err}");
    }

    /// Hardening regression: decrypt_with_jwk hard-requires `jwk.alg` so the
    /// key-management algorithm is bound to the key, not taken from the
    /// attacker-controlled token header. A JWK with no `alg` must be rejected
    /// before any key material is touched.
    #[test]
    fn jwk_decrypt_requires_alg() {
        // Build a valid dir/A256GCM token with raw bytes.
        let jwk = crate::jwk::generate_symmetric(32).unwrap(); // no alg set
        let k = crate::base64url::decode(jwk.k.as_ref().unwrap()).unwrap();
        let token = encrypt(&k, b"p", JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        let err = decrypt_with_jwk(&jwk, &token).unwrap_err().to_string();
        assert!(err.contains("alg must be set"), "unexpected: {err}");
    }

    /// Phase 9: decrypt_with_jwk rejects alg mismatch between JWK and token.
    #[test]
    fn jwk_decrypt_pinned_alg_mismatch() {
        // Encrypt with dir, but JWK claims A256KW at decrypt time.
        let jwk_bytes = crate::jwk::generate_symmetric(32).unwrap();
        let k = crate::base64url::decode(jwk_bytes.k.as_ref().unwrap()).unwrap();
        let token = encrypt(&k, b"p", JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        let mut jwk = jwk_bytes;
        jwk.alg = Some("A256KW".into());
        let err = decrypt_with_jwk(&jwk, &token).unwrap_err().to_string();
        assert!(
            err.contains("does not match token header alg"),
            "unexpected: {err}"
        );
    }

    /// Phase 3: oversized JWE tokens are rejected before any decoding.
    #[test]
    fn oversize_jwe_token_is_rejected() {
        let big = "a".repeat(crate::MAX_TOKEN_BYTES + 1);
        let cek = [0x42u8; 32];
        let err = decrypt(&cek, &big).unwrap_err().to_string();
        assert!(err.contains("MAX_TOKEN_BYTES"), "unexpected error: {err}");
    }

    #[test]
    fn oversize_jwe_decode_header_is_rejected() {
        let big = "a".repeat(crate::MAX_TOKEN_BYTES + 1);
        let err = decode_header(&big).unwrap_err().to_string();
        assert!(err.contains("MAX_TOKEN_BYTES"), "unexpected error: {err}");
    }

    /// Phase 3: A128KW rejects a 32-byte KEK.
    #[test]
    fn a128kw_rejects_wrong_size_kek_on_encrypt() {
        let too_big = [0x11u8; 32];
        let err = encrypt(&too_big, b"p", JweAlgorithm::A128KW, JweEncryption::A128GCM)
            .unwrap_err()
            .to_string();
        assert!(err.contains("A128KW"), "unexpected error: {err}");
        assert!(err.contains("16 bytes"), "unexpected error: {err}");
    }

    /// Phase 3: A256KW rejects a 16-byte KEK.
    #[test]
    fn a256kw_rejects_wrong_size_kek_on_encrypt() {
        let too_small = [0x22u8; 16];
        let err = encrypt(
            &too_small,
            b"p",
            JweAlgorithm::A256KW,
            JweEncryption::A128GCM,
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("A256KW"), "unexpected error: {err}");
        assert!(err.contains("32 bytes"), "unexpected error: {err}");
    }

    /// Phase 3: decryption also rejects a mis-sized KEK.
    #[test]
    fn aes_kw_rejects_wrong_size_kek_on_decrypt() {
        // Encrypt with a correct KEK...
        let kek = [0xABu8; 32];
        let token = encrypt(&kek, b"p", JweAlgorithm::A256KW, JweEncryption::A128GCM).unwrap();
        // ...then attempt decryption with a wrong-size key.
        let wrong_size = [0xABu8; 16];
        let err = decrypt(&wrong_size, &token).unwrap_err().to_string();
        assert!(err.contains("A256KW"), "unexpected error: {err}");
        assert!(err.contains("32 bytes"), "unexpected error: {err}");
    }

    /// J-09 regression: a JWE whose alg is not in the caller's allow-list is rejected.
    #[test]
    fn allow_list_rejects_wrong_alg() {
        // Token created with dir + A256GCM...
        let cek = [0x42u8; 32];
        let token = encrypt(&cek, b"p", JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        // ...but caller only accepts AES key-wrap algorithms.
        let options =
            JweDecryptOptions::new(vec![JweAlgorithm::A256KW], vec![JweEncryption::A256GCM]);
        let result = decrypt_with_options(&cek, &token, &options);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("allow-list"), "unexpected error: {err}");
    }

    /// J-09 regression: a JWE whose enc is not in the caller's allow-list is rejected.
    #[test]
    fn allow_list_rejects_wrong_enc() {
        // Token uses A256GCM...
        let cek = [0x42u8; 32];
        let token = encrypt(&cek, b"p", JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        // ...but caller only accepts CBC-HS.
        let options =
            JweDecryptOptions::new(vec![JweAlgorithm::Dir], vec![JweEncryption::A256CbcHs512]);
        let result = decrypt_with_options(&cek, &token, &options);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("allow-list"), "unexpected error: {err}");
    }

    /// J-09 regression: permitted combinations still succeed.
    #[test]
    fn allow_list_accepts_permitted() {
        let cek = [0x42u8; 32];
        let plaintext = b"allow-listed";
        let token = encrypt(&cek, plaintext, JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        let options = JweDecryptOptions::new(vec![JweAlgorithm::Dir], vec![JweEncryption::A256GCM]);
        let recovered = decrypt_with_options(&cek, &token, &options).unwrap();
        assert_eq!(recovered, plaintext);
    }

    /// J-04 regression: a JWE with a non-empty crit header must be rejected.
    #[test]
    fn nonempty_crit_rejected_on_decrypt() {
        let cek = [0x42u8; 32];
        let token = encrypt(&cek, b"p", JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        // Rewrite the header to include a non-empty crit.
        let parts: Vec<&str> = token.splitn(5, '.').collect();
        let mut header: JoseHeader =
            serde_json::from_slice(&base64url::decode(parts[0]).unwrap()).unwrap();
        header.crit = Some(vec!["myext".to_string()]);
        let new_header_b64 = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let tampered_token = format!(
            "{}.{}.{}.{}.{}",
            new_header_b64, parts[1], parts[2], parts[3], parts[4]
        );

        let result = decrypt(&cek, &tampered_token);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("crit"), "unexpected error: {err}");
    }

    /// Regression: an empty-but-present crit array must be rejected on JWE
    /// decrypt (RFC 7515 ยง4.1.11 requires crit to be non-empty).
    #[test]
    fn empty_crit_rejected_on_decrypt() {
        let cek = [0x42u8; 32];
        let token = encrypt(&cek, b"p", JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        // Rewrite the header to include an empty crit array.
        let parts: Vec<&str> = token.splitn(5, '.').collect();
        let mut header: JoseHeader =
            serde_json::from_slice(&base64url::decode(parts[0]).unwrap()).unwrap();
        header.crit = Some(Vec::new());
        let new_header_b64 = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let tampered_token = format!(
            "{}.{}.{}.{}.{}",
            new_header_b64, parts[1], parts[2], parts[3], parts[4]
        );

        let result = decrypt(&cek, &tampered_token);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("crit"), "unexpected error: {err}");
    }

    /// Regression: a JWE header declaring `zip` (content compression, which
    /// this library does not implement) must be rejected on decrypt instead
    /// of returning the compressed bytes as plaintext.
    #[test]
    fn zip_header_rejected_on_decrypt() {
        let cek = [0x42u8; 32];
        let token = encrypt(&cek, b"p", JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();

        // Rewrite the header to declare DEFLATE compression.
        let parts: Vec<&str> = token.splitn(5, '.').collect();
        let mut header: JoseHeader =
            serde_json::from_slice(&base64url::decode(parts[0]).unwrap()).unwrap();
        header.extra.insert(
            "zip".to_string(),
            serde_json::Value::String("DEF".to_string()),
        );
        let new_header_b64 = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let tampered_token = format!(
            "{}.{}.{}.{}.{}",
            new_header_b64, parts[1], parts[2], parts[3], parts[4]
        );

        let result = decrypt(&cek, &tampered_token);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("zip"), "unexpected error: {err}");
    }

    #[test]
    fn wrong_kek_fails_unwrap() {
        let kek1 = [0xABu8; 32];
        let kek2 = [0xCDu8; 32];
        let plaintext = b"kek test";

        let token = encrypt(
            &kek1,
            plaintext,
            JweAlgorithm::A256KW,
            JweEncryption::A128GCM,
        )
        .unwrap();
        let result = decrypt(&kek2, &token);
        assert!(result.is_err(), "wrong KEK should fail unwrap");
    }
}