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
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
//! JWS Compact Serialization (RFC 7515 Section 3.1).
//!
//! Format: `BASE64URL(header).BASE64URL(payload).BASE64URL(signature)`

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

/// `crit` header parameters this library understands natively (RFC 7515
/// §4.1.11). A caller may extend the understood set for JAdES (`etsiU`,
/// `sigT`, …) via [`SignOptions::understood_crit`] /
/// [`VerifyOptions::understood_crit`]; anything outside the union of this
/// list and the caller's list is rejected. RFC 7797 `b64` lives here
/// because the library implements its semantics.
pub const LIB_UNDERSTOOD_CRIT: &[&str] = &["b64"];

/// Options controlling the JWS signing input (RFC 7797 unencoded payload
/// and the understood-`crit` allow-list).
///
/// The default — `SignOptions::default()` — reproduces the classic RFC 7515
/// behaviour: base64url-encoded payload, attached, and only the library's
/// built-in understood `crit` params permitted.
///
/// The struct is `#[non_exhaustive]` so new policy switches can be added
/// without breaking callers: start from [`SignOptions::new`] and use the
/// `with_*` builders (or assign the public fields on a `mut` binding).
///
/// ```
/// use jose_rs::jws::SignOptions;
///
/// let opts = SignOptions::new()
///     .with_understood_crit(["etsiU"])
///     .with_key_reference_headers(true);
/// assert!(opts.b64);
/// assert!(opts.allow_key_reference_headers);
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SignOptions {
    /// RFC 7797: when `false`, the payload is carried unencoded and the
    /// signing input is `ASCII(protected) || '.' || payload` over the raw
    /// payload bytes. When `false` the protected header MUST contain
    /// `"b64": false` and list `"b64"` in `crit` — this is enforced.
    ///
    /// Defaults to `true` (classic base64url) — see the manual [`Default`]
    /// impl. A derived `Default` would make this `false`, silently selecting
    /// RFC 7797 unencoded mode, so it is set explicitly here.
    pub b64: bool,
    /// Additional `crit` header parameters the caller understands and has
    /// processed out-of-band (e.g. JAdES `etsiU`, `sigT`). These are
    /// permitted in `crit` on top of [`LIB_UNDERSTOOD_CRIT`].
    pub understood_crit: Vec<String>,
    /// Permit the key-reference members `jku`, `jwk`, `x5u` and `x5c`
    /// ([`crate::header::KEY_REFERENCE_MEMBERS`]) in the protected header and
    /// in a JSON-serialization unprotected header. Defaults to `false`.
    ///
    /// This crate never dereferences these members, but a peer may, so a
    /// header carrying them is refused unless the caller opts in. Set this
    /// when the members are deliberate, e.g. an `x5c` chain added by
    /// [`crate::jws::x5::bind_cert_to_header`].
    pub allow_key_reference_headers: bool,
}

impl SignOptions {
    /// Classic RFC 7515 behaviour: base64url-encoded, attached payload,
    /// no extra understood `crit`, no key-reference header members.
    pub fn new() -> Self {
        Self {
            b64: true,
            understood_crit: Vec::new(),
            allow_key_reference_headers: false,
        }
    }

    /// Set [`b64`](Self::b64): `false` selects the RFC 7797 unencoded
    /// payload (the protected header must then carry `"b64": false` and list
    /// `"b64"` in `crit`).
    #[must_use]
    pub fn with_b64(mut self, b64: bool) -> Self {
        self.b64 = b64;
        self
    }

    /// Set [`understood_crit`](Self::understood_crit), replacing any
    /// previous value.
    #[must_use]
    pub fn with_understood_crit<I, S>(mut self, names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.understood_crit = names.into_iter().map(Into::into).collect();
        self
    }

    /// Set [`allow_key_reference_headers`](Self::allow_key_reference_headers).
    #[must_use]
    pub fn with_key_reference_headers(mut self, allow: bool) -> Self {
        self.allow_key_reference_headers = allow;
        self
    }
}

impl Default for SignOptions {
    /// Classic RFC 7515 behaviour (`b64 = true`). Defined manually so the
    /// default is not the surprising `b64 = false` a derive would produce.
    fn default() -> Self {
        Self::new()
    }
}

/// Options controlling JWS verification (RFC 7797 unencoded payload and the
/// understood-`crit` allow-list).
#[derive(Debug, Clone, Default)]
pub struct VerifyOptions {
    /// Additional `crit` header parameters the caller understands. A `crit`
    /// entry outside the union of [`LIB_UNDERSTOOD_CRIT`] and this list is
    /// rejected (RFC 7515 §4.1.11).
    pub understood_crit: Vec<String>,
}

impl VerifyOptions {
    /// Classic behaviour: only the library's built-in understood `crit`.
    pub fn new() -> Self {
        Self::default()
    }
}

/// Validate the protected header's `crit` list against the union of the
/// library's understood params and the caller-supplied understood set
/// (RFC 7515 §4.1.11).
///
/// An empty `crit` array is itself a protocol violation (RFC 7515 says
/// `crit` MUST NOT be empty when present). Any entry not understood is
/// rejected, and any entry that is not actually present in the header is
/// rejected too — §4.1.11 requires every parameter named in `crit` to be
/// present. (`b64`'s presence is enforced separately in [`resolve_b64`],
/// which knows the param's default semantics, so it is exempt here.)
/// Returns whether `b64` appeared in `crit`.
fn validate_crit(header: &JoseHeader, understood_extra: &[String]) -> Result<bool> {
    let Some(crit) = header.crit.as_ref() else {
        return Ok(false);
    };
    if crit.is_empty() {
        return Err(JoseError::InvalidHeader(
            "crit must not be empty when present".into(),
        ));
    }
    let mut saw_b64 = false;
    for param in crit {
        if param == "b64" {
            saw_b64 = true;
            // Presence of the b64 param itself is checked in resolve_b64.
            continue;
        }
        let understood = LIB_UNDERSTOOD_CRIT.contains(&param.as_str())
            || understood_extra.iter().any(|u| u == param);
        if !understood {
            return Err(JoseError::InvalidHeader(format!(
                "unsupported crit extension: {param}"
            )));
        }
        // RFC 7515 §4.1.11: a parameter named in `crit` MUST be present in the
        // header. Registered parameters live in typed fields; caller
        // extensions (e.g. JAdES `etsiU`) live in `extra`.
        if !header_has_param(header, param) {
            return Err(JoseError::InvalidHeader(format!(
                "crit names {param} but it is absent from the protected header (RFC 7515 §4.1.11)"
            )));
        }
    }
    Ok(saw_b64)
}

fn header_has_param(header: &JoseHeader, param: &str) -> bool {
    match param {
        "alg" => true,
        "enc" => header.enc.is_some(),
        "kid" => header.kid.is_some(),
        "typ" => header.typ.is_some(),
        "cty" => header.cty.is_some(),
        "jku" => header.jku.is_some(),
        "jwk" => header.jwk.is_some(),
        "x5u" => header.x5u.is_some(),
        "x5c" => header.x5c.is_some(),
        "x5t" => header.x5t.is_some(),
        "x5t#S256" => header.x5t_s256.is_some(),
        "crit" => header.crit.is_some(),
        _ => header.extra.contains_key(param),
    }
}

/// Read the RFC 7797 `b64` header param (default `true`) from the protected
/// header's `extra` map, enforcing the §6 rule that `b64`, when present,
/// must be listed in `crit`. Returns the effective `b64` value.
fn resolve_b64(header: &JoseHeader, crit_listed_b64: bool) -> Result<bool> {
    match header.extra.get("b64") {
        None => {
            // RFC 7515 §4.1.11: every parameter named in `crit` MUST be
            // present in the header. A `crit` listing `b64` with no `b64`
            // param is non-conformant and must be rejected (on both the sign
            // and verify sides) rather than silently defaulting to `true`.
            if crit_listed_b64 {
                return Err(JoseError::InvalidHeader(
                    "b64 is listed in crit but no b64 header param is present (RFC 7515 §4.1.11)"
                        .into(),
                ));
            }
            Ok(true)
        }
        Some(value) => {
            let b = value.as_bool().ok_or_else(|| {
                JoseError::InvalidHeader("b64 header param must be a boolean".into())
            })?;
            // RFC 7797 §6: if b64 is present it MUST be integrity-protected
            // by being listed in crit.
            if !crit_listed_b64 {
                return Err(JoseError::InvalidHeader(
                    "b64 header param must be listed in crit (RFC 7797 §6)".into(),
                ));
            }
            Ok(b)
        }
    }
}

/// Build the JWS signing input for a (possibly unencoded) payload.
///
/// RFC 7515: `ASCII(BASE64URL(protected)) || '.' || BASE64URL(payload)`.
/// RFC 7797 with `b64:false`: `ASCII(BASE64URL(protected)) || '.' ||
/// payload` where the payload bytes are appended verbatim.
pub(crate) fn signing_input(protected_b64: &str, payload: &[u8], b64: bool) -> Vec<u8> {
    let mut input = Vec::with_capacity(protected_b64.len() + 1 + payload.len());
    input.extend_from_slice(protected_b64.as_bytes());
    input.push(b'.');
    if b64 {
        input.extend_from_slice(base64url::encode(payload).as_bytes());
    } else {
        input.extend_from_slice(payload);
    }
    input
}

/// Build a signing input from an already-prepared payload segment (base64url
/// text for `b64=true`, raw payload bytes for `b64=false`). Lets multi-signer
/// callers encode the shared payload once and reuse the segment for every
/// signature instead of re-encoding it per entry.
pub(crate) fn signing_input_from_segment(protected_b64: &str, payload_segment: &[u8]) -> Vec<u8> {
    let mut input = Vec::with_capacity(protected_b64.len() + 1 + payload_segment.len());
    input.extend_from_slice(protected_b64.as_bytes());
    input.push(b'.');
    input.extend_from_slice(payload_segment);
    input
}

pub(crate) fn ensure_token_size(token: &str) -> Result<()> {
    if token.len() > crate::MAX_TOKEN_BYTES {
        return Err(JoseError::InvalidToken(format!(
            "token size {} exceeds MAX_TOKEN_BYTES ({})",
            token.len(),
            crate::MAX_TOKEN_BYTES
        )));
    }
    Ok(())
}

/// Producer-side `crit` rules of RFC 7515 §4.1.11 that [`validate_crit`]
/// (shared with verification) does not cover:
///
/// - "Producers MUST NOT include Header Parameter names defined by this
///   specification or [JWA] for use with JWS ... in the `crit` list": any
///   name registered by RFC 7515, RFC 7516 or RFC 7518 is refused, even if
///   the caller lists it in [`SignOptions::understood_crit`]. RFC 7797 `b64`
///   is an extension and stays allowed (RFC 7797 §6 requires it in `crit`).
/// - Producers MUST NOT include "duplicate names" in the `crit` list.
///
/// Verification keeps accepting registered names that the caller declares
/// understood: §4.1.11 only says recipients MAY reject them.
fn validate_sign_crit_names(header: &JoseHeader) -> Result<()> {
    let Some(crit) = header.crit.as_ref() else {
        return Ok(());
    };
    for (i, name) in crit.iter().enumerate() {
        if crate::header::is_registered_member(name) {
            return Err(JoseError::InvalidHeader(format!(
                "crit must not list the registered header parameter {name} (RFC 7515 §4.1.11)"
            )));
        }
        if crit[..i].contains(name) {
            return Err(JoseError::InvalidHeader(format!(
                "crit lists {name} more than once (RFC 7515 §4.1.11)"
            )));
        }
    }
    Ok(())
}

/// A protected header that passed every sign-side check, ready to sign.
pub(crate) struct PreparedSignHeader {
    /// Effective RFC 7797 `b64` flag (whether to base64url the payload).
    pub(crate) b64: bool,
    /// `BASE64URL(UTF8(protected header))`, the first signing-input segment.
    pub(crate) protected_b64: String,
}

/// Cross-check the protected header against the signer and the RFC 7797 /
/// understood-`crit` / key-reference policy carried in `opts`, then
/// serialize it.
///
/// This is the single sign-side gate shared by the compact, flattened and
/// general JSON serializers (and so by JWT encoding); the serialized header
/// is only obtainable through it. It first rejects an `extra` map that
/// shadows a typed member: the `alg` and `crit` checks below only see the
/// typed fields, so `extra["alg"] = "none"` or `extra["crit"]` would
/// otherwise be signed unvalidated as a duplicate JSON member that
/// last-key-wins verifiers read instead (RFC 7515 §4 requires unique member
/// names). It then rejects JWE-only members
/// ([`crate::header::JWE_ONLY_MEMBERS`]) and the `crit` names producers must
/// not emit ([`validate_sign_crit_names`]). Serialization goes through
/// [`JoseHeader::to_protected_b64`], which also applies the key-reference
/// policy and the size limit.
pub(crate) fn prepare_sign_header(
    header: &JoseHeader,
    signer: &dyn kryptering::Signer,
    opts: &SignOptions,
) -> Result<PreparedSignHeader> {
    header.ensure_no_duplicate_members()?;
    if let Some(name) = header.jwe_only_member() {
        return Err(JoseError::InvalidHeader(format!(
            "{name} is a JWE-only header member and must not appear in a JWS header \
             (RFC 7516 §9; IANA JOSE header registry)"
        )));
    }
    validate_sign_crit_names(header)?;
    let crit_listed_b64 = validate_crit(header, &opts.understood_crit)?;
    if header.alg == "none" {
        return Err(JoseError::InvalidHeader(
            "alg=\"none\" is not permitted".into(),
        ));
    }
    let header_alg = JwsAlgorithm::from_str(&header.alg)?;
    if !header_alg.matches_crypto(signer.algorithm())? {
        return Err(JoseError::InvalidHeader(format!(
            "header alg {} does not match signer algorithm",
            header.alg
        )));
    }
    // Effective b64 from the header, cross-checked against the caller's
    // intent: the header is authoritative (it is what gets signed), but it
    // must agree with opts.b64 so a caller cannot think it signed unencoded
    // while emitting an encoded payload.
    let header_b64 = resolve_b64(header, crit_listed_b64)?;
    if header_b64 != opts.b64 {
        return Err(JoseError::InvalidHeader(format!(
            "header b64={header_b64} disagrees with requested b64={}",
            opts.b64
        )));
    }
    Ok(PreparedSignHeader {
        b64: header_b64,
        protected_b64: header.to_protected_b64(opts.allow_key_reference_headers)?,
    })
}

/// Sign a payload and produce a JWS Compact Serialization string.
///
/// The `signer` provides the cryptographic operation -- it can be a software
/// key or an HSM-backed key. The supplied `header.alg` is cross-checked
/// against `signer.algorithm()` before any cryptographic operation;
/// mismatches (including `alg: "none"` or a non-empty `crit`) are rejected.
///
/// Header content is also restricted so that every token this crate emits is
/// unambiguous and decodable by this crate:
///
/// - a `header.extra` entry that repeats a typed member such as `alg`, `kid`
///   or `crit` is rejected (it would emit a duplicate JSON member);
/// - JWE-only members (`enc`, `zip`, `epk`, `apu`, `apv`, `iv`, `tag`,
///   `p2s`, `p2c`; see [`crate::header::JWE_ONLY_MEMBERS`]) are rejected;
/// - a `crit` list naming a registered header parameter, or naming one
///   parameter twice, is rejected (RFC 7515 §4.1.11);
/// - `jku`, `jwk`, `x5u` and `x5c` are rejected unless
///   [`SignOptions::allow_key_reference_headers`] is set (use
///   [`sign_with_options`]);
/// - a token longer than [`crate::MAX_TOKEN_BYTES`] is refused.
pub fn sign(
    signer: &dyn kryptering::Signer,
    payload: &[u8],
    header: &JoseHeader,
) -> Result<String> {
    sign_with_options(signer, payload, header, &SignOptions::new())
}

/// Sign a payload and produce a JWS Compact Serialization, honouring the
/// RFC 7797 `b64` and understood-`crit` policy in `opts`.
///
/// With `opts.b64 == false` (RFC 7797 unencoded payload) the payload is
/// embedded verbatim in the second compact segment. RFC 7797 §5.2 forbids a
/// `.` in an unencoded compact payload (it would be confused with the
/// segment separator); such a payload is rejected here.
pub fn sign_with_options(
    signer: &dyn kryptering::Signer,
    payload: &[u8],
    header: &JoseHeader,
    opts: &SignOptions,
) -> Result<String> {
    let PreparedSignHeader {
        b64,
        protected_b64: header_b64,
    } = prepare_sign_header(header, signer, opts)?;

    let payload_segment = if b64 {
        base64url::encode(payload)
    } else {
        // RFC 7797 §5.2: an unencoded compact payload must not contain a dot.
        if payload.contains(&b'.') {
            return Err(JoseError::InvalidToken(
                "unencoded (b64=false) compact payload must not contain '.'".into(),
            ));
        }
        let payload_str = std::str::from_utf8(payload).map_err(|_| {
            JoseError::InvalidToken(
                "unencoded (b64=false) compact payload must be valid UTF-8".into(),
            )
        })?;
        payload_str.to_string()
    };

    let input = signing_input_from_segment(&header_b64, payload_segment.as_bytes());
    // Refuse before the (possibly HSM-backed) signing operation when the
    // token cannot fit even without its signature, and again once assembled:
    // `verify` rejects compact tokens over MAX_TOKEN_BYTES.
    crate::ensure_emit_size(input.len() + 1)?;
    let signature = signer.sign(&input).map_err(JoseError::Crypto)?;
    let sig_b64 = base64url::encode(&signature);
    let token = format!("{header_b64}.{payload_segment}.{sig_b64}");
    crate::ensure_emit_size(token.len())?;
    Ok(token)
}

/// Validate a protected header against the verifier and the
/// understood-`crit` / RFC 7797 policy in `opts`. Returns the effective
/// `b64` flag so the caller can decide how to reconstruct the signing input.
pub(crate) fn validate_header_opts(
    header_b64: &str,
    verifier: &dyn kryptering::Verifier,
    opts: &VerifyOptions,
) -> Result<bool> {
    let header_json = base64url::decode(header_b64)?;
    let header: JoseHeader = serde_json::from_slice(&header_json)?;

    // RFC 7515 §4.1.11: reject crit params we do not understand or that are
    // named in `crit` but absent from the header.
    let crit_listed_b64 = validate_crit(&header, &opts.understood_crit)?;

    // Reject alg="none" at the parse layer — never reach the verifier.
    if header.alg == "none" {
        return Err(JoseError::InvalidToken(
            "alg=\"none\" is not permitted".into(),
        ));
    }

    let header_alg = JwsAlgorithm::from_str(&header.alg)?;
    if !header_alg.matches_crypto(verifier.algorithm())? {
        return Err(JoseError::InvalidToken(format!(
            "header alg {} does not match verifier algorithm",
            header.alg
        )));
    }

    resolve_b64(&header, crit_listed_b64)
}

/// Validate a protected header for whole-JWS policy without binding it to a
/// particular verifier. General JWS payload encoding is shared by every
/// signature, so `b64` agreement must be checked before per-verifier algorithm
/// filtering hides otherwise valid signature entries.
pub(crate) fn validate_header_b64_opts(header_b64: &str, opts: &VerifyOptions) -> Result<bool> {
    let header_json = base64url::decode(header_b64)?;
    let header: JoseHeader = serde_json::from_slice(&header_json)?;

    let crit_listed_b64 = validate_crit(&header, &opts.understood_crit)?;

    if header.alg == "none" {
        return Err(JoseError::InvalidToken(
            "alg=\"none\" is not permitted".into(),
        ));
    }

    let header_alg = JwsAlgorithm::from_str(&header.alg)?;
    header_alg.to_crypto()?;

    resolve_b64(&header, crit_listed_b64)
}

/// Verify a JWS Compact Serialization string.
///
/// Returns the decoded payload on success. The token's `alg` header is
/// cross-checked against `verifier.algorithm()` — mismatches are rejected
/// before any cryptographic operation. `alg: "none"` is always rejected.
/// Raw Edwards verifiers accept their fully specified name and legacy `EdDSA`.
/// Applications requiring one wire spelling must use a JWT algorithm allowlist.
pub fn verify(verifier: &dyn kryptering::Verifier, token: &str) -> Result<Vec<u8>> {
    verify_with_options(verifier, token, &VerifyOptions::new())
}

/// Verify a JWS Compact Serialization, honouring the RFC 7797 `b64` and
/// understood-`crit` policy in `opts`.
///
/// With an unencoded payload (`b64:false`) the second compact segment is the
/// raw payload bytes (not base64url) and is returned verbatim; the signing
/// input is reconstructed per RFC 7797.
pub fn verify_with_options(
    verifier: &dyn kryptering::Verifier,
    token: &str,
    opts: &VerifyOptions,
) -> Result<Vec<u8>> {
    ensure_token_size(token)?;
    let parts: Vec<&str> = token.splitn(3, '.').collect();
    if parts.len() != 3 {
        return Err(JoseError::InvalidToken(
            "expected 3 dot-separated parts".into(),
        ));
    }
    let b64 = validate_header_opts(parts[0], verifier, opts)?;
    // The signing input is `ASCII(protected) || '.' || payload-segment`, where
    // the payload segment is exactly the transmitted second compact part
    // (base64url text for b64=true, raw bytes for b64=false). Reuse it
    // verbatim instead of decoding then re-encoding the payload, which would
    // add an avoidable O(payload_size) decode+encode on every verification.
    let input = signing_input_from_segment(parts[0], parts[1].as_bytes());
    let signature = base64url::decode(parts[2])?;
    let valid = verifier
        .verify(&input, &signature)
        .map_err(JoseError::Crypto)?;
    if !valid {
        return Err(JoseError::InvalidToken(
            crate::SIGNATURE_VERIFICATION_FAILED.into(),
        ));
    }
    // Decode the payload only after the signature verifies; still rejects an
    // invalid-base64url payload (for an authenticated token) per spec.
    let payload = if b64 {
        base64url::decode(parts[1])?
    } else {
        parts[1].as_bytes().to_vec()
    };
    Ok(payload)
}

/// Sign a payload using a JWK directly — the one-shot signer-side API.
///
/// The signing algorithm is derived from `jwk.alg` (which must be set to
/// one of the JWS algorithm identifiers). The supplied `header.alg` is
/// cross-checked against it, `Jwk::check_op(Sign)` is enforced, the
/// signer is built internally, and `sign` runs. All the phase-4 sign-side
/// bindings (header/signer alg agreement, `alg: "none"` rejection,
/// non-empty `crit` rejection) apply transitively.
pub fn sign_with_jwk(jwk: &crate::jwk::Jwk, payload: &[u8], header: &JoseHeader) -> Result<String> {
    sign_with_jwk_options(jwk, payload, header, &SignOptions::new())
}

/// [`sign_with_jwk`] with explicit [`SignOptions`]: RFC 7797 unencoded
/// payloads, caller-understood `crit` parameters, and the opt-in for
/// key-reference header members (`jku`, `jwk`, `x5u`, `x5c`).
///
/// All [`sign_with_jwk`] checks apply: the header `alg` must match `jwk.alg`
/// and `Jwk::check_op(Sign)` is enforced.
pub fn sign_with_jwk_options(
    jwk: &crate::jwk::Jwk,
    payload: &[u8],
    header: &JoseHeader,
    opts: &SignOptions,
) -> Result<String> {
    let signer = signer_from_jwk(jwk, header)?;

    // Standard sign — applies the full phase-4 sign-side binding.
    sign_with_options(&signer, payload, header, opts)
}

/// Verify a JWS Compact Serialization string using a JWK directly.
///
/// This is the safer one-shot API: it decodes the token's protected
/// header, derives the JWS algorithm from it, enforces `Jwk::check_op`
/// for `Verify`, requires any pinned `jwk.alg` to match, constructs the
/// appropriate `kryptering::SoftwareVerifier` internally, and runs
/// verification. The caller does not need to pick an algorithm, build
/// a verifier, or remember to check `use`/`key_ops`.
/// HMAC key selection and minimum length are checked against the token's
/// algorithm even when `jwk.alg` is absent. AKP keys still require `alg`.
///
/// Returns the decoded payload on success. All the usual JWS-layer
/// hardening (alg-header binding, `alg: "none"` rejection, non-empty
/// `crit` rejection, `MAX_TOKEN_BYTES` cap) applies transitively.
pub fn verify_with_jwk(jwk: &crate::jwk::Jwk, token: &str) -> Result<Vec<u8>> {
    // Read the token's header to determine the algorithm.
    let header = decode_header(token)?;
    let verifier = verifier_from_jwk(jwk, &header.alg)?;

    // Standard verify — applies the full JWS-layer binding.
    verify(&verifier, token)
}

/// Build a signer from a JWK for a given protected header.
///
/// This is the whole JWK-aware signing rule set, shared verbatim with the JSON serialization
/// paths (plan L2): the algorithm comes from `jwk.alg` (which must be set), the header `alg` must
/// agree with it, `use`/`key_ops` are enforced for [`JwkOp::Sign`], and the key is converted with
/// the algorithm's strength rules applied (`jwk_to_signature_key`). Nothing here signs anything;
/// the caller hands the result to [`sign`], which keeps its own header bindings.
///
/// The rule set is a function rather than a copy because "the compact and JSON paths enforce the
/// same key rules" is not a property you can maintain in two places.
pub(crate) fn signer_from_jwk(
    jwk: &crate::jwk::Jwk,
    header: &JoseHeader,
) -> Result<kryptering::SoftwareSigner> {
    // 1. Derive the algorithm from the JWK.
    let jwk_alg_str = jwk
        .alg
        .as_deref()
        .ok_or_else(|| JoseError::Key("JWK alg must be set for sign_with_jwk".into()))?;
    let jwk_alg = JwsAlgorithm::from_str(jwk_alg_str)?;
    let sig_alg = jwk_alg.crypto_for_jwk(jwk)?;

    // 2. Header must agree with the JWK's pinned alg.
    if !crate::jwk::convert::signature_pin_matches(jwk, jwk_alg_str, &header.alg) {
        return Err(JoseError::InvalidHeader(format!(
            "header alg {} does not match JWK alg {jwk_alg_str}",
            header.alg
        )));
    }

    // 3. Enforce use / key_ops.
    jwk.check_op(crate::jwk::JwkOp::Sign)?;

    // 4. Convert to SoftwareKey and build the signer.
    let sw_key = crate::jwk::jwk_to_signature_key(jwk, jwk_alg, crate::jwk::JwkOp::Sign)?;
    kryptering::SoftwareSigner::new(sig_alg, sw_key).map_err(JoseError::Crypto)
}

/// Build a verifier from a JWK for an algorithm named by an *untrusted* header value.
///
/// The rules mirror [`signer_from_jwk`] with the direction reversed: the algorithm comes from the
/// token, a `jwk.alg` pin must match it (including same-curve Edwards aliases), `use`/`key_ops` are enforced for
/// [`JwkOp::Verify`], and the key is converted under that algorithm's strength rules — which is
/// why an HS256 key is refused for an HS512 token even with no `alg` pinned, and why a short
/// HMAC key cannot be talked into a weaker algorithm by editing the header.
pub(crate) fn verifier_from_jwk(
    jwk: &crate::jwk::Jwk,
    header_alg: &str,
) -> Result<kryptering::SoftwareVerifier> {
    let parsed = JwsAlgorithm::from_str(header_alg)?;
    let sig_alg = parsed.crypto_for_jwk(jwk)?;

    // RFC 8725 §3.1: preserve pins, allowing only the curve-bound Edwards
    // equivalence in ADR 0043. Caller wire-name allowlists remain exact.
    if let Some(jwk_alg) = jwk.alg.as_deref() {
        if !crate::jwk::convert::signature_pin_matches(jwk, jwk_alg, header_alg) {
            return Err(JoseError::InvalidToken(format!(
                "JWK alg {jwk_alg} does not match token header alg {header_alg}"
            )));
        }
    }

    // Enforce use / key_ops.
    jwk.check_op(crate::jwk::JwkOp::Verify)?;

    let sw_key = crate::jwk::jwk_to_signature_key(jwk, parsed, crate::jwk::JwkOp::Verify)?;
    kryptering::SoftwareVerifier::new(sig_alg, sw_key).map_err(JoseError::Crypto)
}

/// Verify a JWS and return the payload *with the header that authenticated it*.
///
/// Same verification as [`verify_with_jwk`]; the difference is what comes back.
/// [`Authenticated`](crate::Authenticated) carries the protected header the signature actually covered, so a
/// caller does not re-parse (and cannot accidentally read an unauthenticated copy).
/// A compact JWS carries no unprotected metadata, so `unprotected` is empty here by
/// construction rather than by luck.
///
/// ```
/// use jose_rs::jwk;
/// use jose_rs::jws::compact;
/// use jose_rs::JoseHeader;
///
/// let mut jwk = jwk::generate_ec("P-256")?;
/// jwk.alg = Some("ES256".into());
/// let token = compact::sign_with_jwk(&jwk, b"data", &JoseHeader::new("ES256"))?;
/// let outcome = compact::verify_with_jwk_authenticated(&jwk, &token)?;
/// assert_eq!(outcome.value, b"data");
/// assert_eq!(outcome.algorithm(), "ES256");
/// # Ok::<(), jose_rs::JoseError>(())
/// ```
pub fn verify_with_jwk_authenticated(
    jwk: &crate::jwk::Jwk,
    token: &str,
) -> Result<crate::Authenticated<Vec<u8>>> {
    let payload = verify_with_jwk(jwk, token)?;
    let protected = decode_header(token)?;
    Ok(crate::Authenticated::new(payload, protected, Vec::new()))
}

/// [`verify_with_jwk_authenticated`] for the low-level verifier boundary (HSM-backed
/// verifiers and the like).
pub fn verify_authenticated(
    verifier: &dyn kryptering::Verifier,
    token: &str,
) -> Result<crate::Authenticated<Vec<u8>>> {
    let payload = verify(verifier, token)?;
    let protected = decode_header(token)?;
    Ok(crate::Authenticated::new(payload, protected, Vec::new()))
}

/// Decode the header from a JWS Compact Serialization without verifying.
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)
}

#[cfg(test)]
mod tests {
    use super::*;
    use kryptering::{
        HashAlgorithm, SignatureAlgorithm, SoftwareKey, SoftwareSigner, SoftwareVerifier,
    };

    struct PanicSigner;

    impl kryptering::Signer for PanicSigner {
        fn algorithm(&self) -> SignatureAlgorithm {
            SignatureAlgorithm::Hmac(HashAlgorithm::Sha256)
        }

        fn sign(&self, _data: &[u8]) -> kryptering::Result<Vec<u8>> {
            panic!("signer must not be called before payload validation")
        }
    }

    fn hmac_key() -> SoftwareKey {
        SoftwareKey::from_symmetric_bytes(
            kryptering::KeyAlgorithm::Hmac,
            b"my-secret-key-at-least-32-bytes!",
        )
        .unwrap()
    }

    fn hmac_signer() -> SoftwareSigner {
        SoftwareSigner::new(SignatureAlgorithm::Hmac(HashAlgorithm::Sha256), hmac_key()).unwrap()
    }

    fn hmac_verifier() -> SoftwareVerifier {
        SoftwareVerifier::new(SignatureAlgorithm::Hmac(HashAlgorithm::Sha256), hmac_key()).unwrap()
    }

    fn b64_false_header() -> JoseHeader {
        let mut header = JoseHeader::new("HS256");
        header.crit = Some(vec!["b64".to_string()]);
        header
            .extra
            .insert("b64".to_string(), serde_json::Value::Bool(false));
        header
    }

    #[test]
    fn sign_verify_hmac_roundtrip() {
        let header = JoseHeader::new("HS256");
        let payload = b"hello, world!";

        let token = sign(&hmac_signer(), payload, &header).unwrap();

        // Token should have 3 dot-separated parts.
        assert_eq!(token.split('.').count(), 3);

        // Verify and recover payload.
        let recovered = verify(&hmac_verifier(), &token).unwrap();
        assert_eq!(recovered, payload);
    }

    #[test]
    fn sign_verify_ed25519_roundtrip() {
        use ed25519_dalek::SigningKey;
        let signing_key =
            SigningKey::generate(&mut getrandom::rand_core::UnwrapErr(getrandom::SysRng));
        let verifying_key = signing_key.verifying_key();

        use pkcs8::spki::EncodePublicKey;
        use pkcs8::EncodePrivateKey;
        let private_der = signing_key.to_pkcs8_der().unwrap();
        let public_der = verifying_key.to_public_key_der().unwrap();
        let signer_key =
            SoftwareKey::from_pkcs8_der(kryptering::KeyAlgorithm::Ed25519, private_der.as_bytes())
                .unwrap();
        let verifier_key =
            SoftwareKey::from_spki_der(kryptering::KeyAlgorithm::Ed25519, public_der.as_bytes())
                .unwrap();

        let signer = SoftwareSigner::new(SignatureAlgorithm::Ed25519, signer_key).unwrap();
        let verifier = SoftwareVerifier::new(SignatureAlgorithm::Ed25519, verifier_key).unwrap();

        let header = JoseHeader::new("EdDSA");
        let payload = b"EdDSA test payload";

        let token = sign(&signer, payload, &header).unwrap();
        let recovered = verify(&verifier, &token).unwrap();
        assert_eq!(recovered, payload);

        // Decode header without verification.
        let decoded = decode_header(&token).unwrap();
        assert_eq!(decoded.alg, "EdDSA");
    }

    #[test]
    fn verify_wrong_key_fails() {
        let header = JoseHeader::new("HS256");
        let payload = b"secret data";

        let token = sign(&hmac_signer(), payload, &header).unwrap();

        // Verify with a different key.
        let wrong_key = SoftwareKey::from_symmetric_bytes(
            kryptering::KeyAlgorithm::Hmac,
            b"wrong-key-that-is-also-32-bytes!",
        )
        .unwrap();
        let wrong_verifier =
            SoftwareVerifier::new(SignatureAlgorithm::Hmac(HashAlgorithm::Sha256), wrong_key)
                .unwrap();

        let result = verify(&wrong_verifier, &token);
        assert!(result.is_err());
    }

    #[test]
    fn malformed_token_wrong_parts() {
        let result = verify(&hmac_verifier(), "only.two");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("3 dot-separated parts"),
            "unexpected error: {err}"
        );

        let result2 = verify(&hmac_verifier(), "noparts");
        assert!(result2.is_err());
    }

    #[test]
    fn tampered_payload_fails_verification() {
        let header = JoseHeader::new("HS256");
        let payload = b"original payload";

        let token = sign(&hmac_signer(), payload, &header).unwrap();

        // Tamper with the payload part (second segment).
        let parts: Vec<&str> = token.splitn(3, '.').collect();
        let tampered_payload = base64url::encode(b"tampered payload");
        let tampered_token = format!("{}.{}.{}", parts[0], tampered_payload, parts[2]);

        let result = verify(&hmac_verifier(), &tampered_token);
        assert!(result.is_err());
    }

    /// Algorithm confusion regression (J-01): a token with header alg="RS256"
    /// MUST be rejected by an HMAC verifier, even if the attacker crafted a
    /// matching HMAC signature using the RSA public key as the HMAC secret.
    ///
    /// The attacker-forged token is constructed manually because the
    /// phase-4 sign-side binding refuses to emit such a token through
    /// the library's own API.
    #[test]
    fn alg_header_mismatch_is_rejected() {
        use kryptering::Signer;
        let payload = b"payload";

        // Attacker-forged token: header says RS256, but the signature is
        // HMAC-SHA256 over the signing input using the verifier's key.
        let mut header = JoseHeader::new("RS256");
        header.kid = Some("attacker".into());
        let header_b64 = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let payload_b64 = base64url::encode(payload);
        let signing_input = format!("{header_b64}.{payload_b64}");
        let sig = hmac_signer().sign(signing_input.as_bytes()).unwrap();
        let token = format!("{signing_input}.{}", base64url::encode(&sig));

        // HMAC verifier must refuse because header alg disagrees with verifier algorithm.
        let result = verify(&hmac_verifier(), &token);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("does not match verifier algorithm"),
            "unexpected error: {err}"
        );
    }

    /// none-downgrade regression (J-03): a token with alg="none" must be
    /// rejected unconditionally, even if the caller hands in a real verifier.
    #[test]
    fn alg_none_is_rejected() {
        let payload = b"payload";
        let header = JoseHeader::new("none");
        // Build a token with alg="none" manually — no signer will accept "none",
        // so we craft the parts directly.
        let header_b64 = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let payload_b64 = base64url::encode(payload);
        let token = format!("{header_b64}.{payload_b64}.");

        let result = verify(&hmac_verifier(), &token);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("none"), "unexpected error: {err}");
    }

    /// Phase 9: sign_with_jwk + verify_with_jwk round-trip.
    #[test]
    fn sign_with_jwk_roundtrip() {
        let mut jwk = crate::jwk::generate_symmetric(32).unwrap();
        jwk.alg = Some("HS256".into());

        let header = JoseHeader::new("HS256");
        let token = sign_with_jwk(&jwk, b"hello", &header).unwrap();

        let recovered = verify_with_jwk(&jwk, &token).unwrap();
        assert_eq!(recovered, b"hello");
    }

    /// Phase 9: sign_with_jwk rejects a JWK with no alg pinned.
    #[test]
    fn sign_with_jwk_rejects_missing_alg() {
        let jwk = crate::jwk::generate_symmetric(32).unwrap(); // no alg set
        let header = JoseHeader::new("HS256");
        let err = sign_with_jwk(&jwk, b"p", &header).unwrap_err().to_string();
        assert!(err.contains("alg must be set"), "unexpected: {err}");
    }

    /// Phase 9: sign_with_jwk rejects use="enc" even on the sign side.
    #[test]
    fn sign_with_jwk_rejects_use_enc() {
        let mut jwk = crate::jwk::generate_symmetric(32).unwrap();
        jwk.alg = Some("HS256".into());
        jwk.use_ = Some("enc".into());

        let header = JoseHeader::new("HS256");
        let err = sign_with_jwk(&jwk, b"p", &header).unwrap_err().to_string();
        assert!(err.contains("`use` is enc"), "unexpected: {err}");
    }

    /// Phase 9: header alg must agree with jwk.alg.
    #[test]
    fn sign_with_jwk_header_alg_must_match() {
        let mut jwk = crate::jwk::generate_symmetric(32).unwrap();
        jwk.alg = Some("HS256".into());
        // Header claims HS384 but JWK is HS256.
        let header = JoseHeader::new("HS384");
        let err = sign_with_jwk(&jwk, b"p", &header).unwrap_err().to_string();
        assert!(err.contains("does not match JWK alg"), "unexpected: {err}");
    }

    /// Phase 8: verify_with_jwk happy path (HMAC).
    #[test]
    fn verify_with_jwk_hmac_roundtrip() {
        // Generate a symmetric JWK for HS256.
        let mut jwk = crate::jwk::generate_symmetric(32).unwrap();
        jwk.alg = Some("HS256".into());

        // Sign via SoftwareKey path for setup.
        let sw = crate::jwk::jwk_to_software_key(&jwk).unwrap();
        let signer =
            kryptering::SoftwareSigner::new(JwsAlgorithm::HS256.to_crypto().unwrap(), sw).unwrap();
        let header = JoseHeader::new("HS256");
        let token = sign(&signer, b"payload", &header).unwrap();

        // Verify via the one-shot JWK API.
        let recovered = verify_with_jwk(&jwk, &token).unwrap();
        assert_eq!(recovered, b"payload");
    }

    /// Phase 8: verify_with_jwk enforces use="enc" blocks Verify.
    #[test]
    fn verify_with_jwk_use_enc_is_rejected() {
        let mut jwk = crate::jwk::generate_symmetric(32).unwrap();
        jwk.alg = Some("HS256".into());
        jwk.use_ = Some("enc".into());

        let sw = crate::jwk::jwk_to_software_key(&jwk).unwrap();
        let signer =
            kryptering::SoftwareSigner::new(JwsAlgorithm::HS256.to_crypto().unwrap(), sw).unwrap();
        let header = JoseHeader::new("HS256");
        let token = sign(&signer, b"payload", &header).unwrap();

        let err = verify_with_jwk(&jwk, &token).unwrap_err().to_string();
        assert!(err.contains("`use` is enc"), "unexpected: {err}");
    }

    /// Phase 8: verify_with_jwk enforces JWK alg must match token header alg.
    #[test]
    fn verify_with_jwk_pinned_alg_mismatch() {
        let mut jwk = crate::jwk::generate_symmetric(32).unwrap();
        jwk.alg = Some("HS384".into()); // JWK claims HS384...

        // ...but we build an HS256-keyed signer and sign with HS256.
        let k_bytes = crate::base64url::decode(jwk.k.as_ref().unwrap()).unwrap();
        let signer = kryptering::SoftwareSigner::new(
            JwsAlgorithm::HS256.to_crypto().unwrap(),
            kryptering::SoftwareKey::from_symmetric_bytes(kryptering::KeyAlgorithm::Hmac, &k_bytes)
                .unwrap(),
        )
        .unwrap();
        let header = JoseHeader::new("HS256");
        let token = sign(&signer, b"payload", &header).unwrap();

        let err = verify_with_jwk(&jwk, &token).unwrap_err().to_string();
        assert!(
            err.contains("does not match token header alg"),
            "unexpected: {err}"
        );
    }

    /// Phase 4: sign-side mismatch between header.alg and signer.algorithm()
    /// is rejected. Mirror of the verify-side alg-confusion fix.
    #[test]
    fn sign_rejects_header_alg_mismatch() {
        // HMAC signer, but header advertises RS256.
        let header = JoseHeader::new("RS256");
        let err = sign(&hmac_signer(), b"payload", &header)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("does not match signer algorithm"),
            "unexpected error: {err}"
        );
    }

    /// Phase 4: sign refuses alg="none" unconditionally.
    #[test]
    fn sign_rejects_alg_none() {
        let header = JoseHeader::new("none");
        let err = sign(&hmac_signer(), b"payload", &header)
            .unwrap_err()
            .to_string();
        assert!(err.contains("none"), "unexpected error: {err}");
    }

    /// Phase 4: sign refuses a non-empty crit header.
    #[test]
    fn sign_rejects_crit() {
        let mut header = JoseHeader::new("HS256");
        header.crit = Some(vec!["ext".into()]);
        let err = sign(&hmac_signer(), b"payload", &header)
            .unwrap_err()
            .to_string();
        assert!(err.contains("crit"), "unexpected error: {err}");
    }

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

    #[test]
    fn oversize_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}");
    }

    /// crit enforcement regression (J-04): a crit array naming an extension
    /// the library does not understand must be rejected on the verify path.
    /// Token constructed manually because the sign-side binding refuses to
    /// emit such a token.
    #[test]
    fn unknown_crit_is_rejected() {
        use kryptering::Signer;
        let payload = b"payload";
        let mut header = JoseHeader::new("HS256");
        header.crit = Some(vec!["x-unknown-ext".to_string()]);
        let header_b64 = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let payload_b64 = base64url::encode(payload);
        let signing_input = format!("{header_b64}.{payload_b64}");
        let sig = hmac_signer().sign(signing_input.as_bytes()).unwrap();
        let token = format!("{signing_input}.{}", base64url::encode(&sig));

        let result = verify(&hmac_verifier(), &token);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("crit"), "unexpected error: {err}");
    }

    /// An empty `crit` array is itself a protocol violation (RFC 7515
    /// §4.1.11) and must be rejected.
    #[test]
    fn empty_crit_is_rejected() {
        use kryptering::Signer;
        let mut header = JoseHeader::new("HS256");
        header.crit = Some(vec![]);
        let header_b64 = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let payload_b64 = base64url::encode(b"p");
        let signing_input = format!("{header_b64}.{payload_b64}");
        let sig = hmac_signer().sign(signing_input.as_bytes()).unwrap();
        let token = format!("{signing_input}.{}", base64url::encode(&sig));
        let err = verify(&hmac_verifier(), &token).unwrap_err().to_string();
        assert!(err.contains("crit must not be empty"), "unexpected: {err}");
    }

    /// RFC 7797 round-trip: sign and verify with an unencoded payload.
    #[test]
    fn b64_false_roundtrip() {
        let header = b64_false_header();

        let payload = b"unencoded RFC 7797 payload";
        let opts = SignOptions {
            b64: false,
            understood_crit: vec![],
            allow_key_reference_headers: false,
        };
        let token = sign_with_options(&hmac_signer(), payload, &header, &opts).unwrap();

        // The middle segment is the raw payload, not base64url.
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts[1].as_bytes(), payload);

        let recovered =
            verify_with_options(&hmac_verifier(), &token, &VerifyOptions::new()).unwrap();
        assert_eq!(recovered, payload);
    }

    /// RFC 7797 §6: a `b64` param that is not listed in `crit` must be
    /// rejected (it would otherwise be unprotected).
    #[test]
    fn b64_false_without_crit_is_rejected() {
        let mut header = JoseHeader::new("HS256");
        // b64=false but crit does NOT list it.
        header
            .extra
            .insert("b64".to_string(), serde_json::Value::Bool(false));
        let opts = SignOptions {
            b64: false,
            understood_crit: vec![],
            allow_key_reference_headers: false,
        };
        let err = sign_with_options(&hmac_signer(), b"p", &header, &opts)
            .unwrap_err()
            .to_string();
        assert!(err.contains("must be listed in crit"), "unexpected: {err}");
    }

    /// RFC 7515 §4.1.11: `crit` listing `b64` with no `b64` header param is
    /// non-conformant — the sign side must refuse to emit such a token.
    #[test]
    fn crit_lists_b64_without_param_is_rejected_on_sign() {
        let mut header = JoseHeader::new("HS256");
        header.crit = Some(vec!["b64".to_string()]);
        // No b64 param in extra.
        let err = sign_with_options(&PanicSigner, b"p", &header, &SignOptions::new())
            .unwrap_err()
            .to_string();
        assert!(err.contains("no b64 header param"), "unexpected: {err}");
    }

    /// RFC 7515 §4.1.11: the verify side likewise rejects a `crit` naming
    /// `b64` when the header omits the `b64` param.
    #[test]
    fn crit_lists_b64_without_param_is_rejected_on_verify() {
        use kryptering::Signer;
        let mut header = JoseHeader::new("HS256");
        header.crit = Some(vec!["b64".to_string()]);
        let header_b64 = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let payload_b64 = base64url::encode(b"p");
        let signing_input = format!("{header_b64}.{payload_b64}");
        let sig = hmac_signer().sign(signing_input.as_bytes()).unwrap();
        let token = format!("{signing_input}.{}", base64url::encode(&sig));
        let err = verify(&hmac_verifier(), &token).unwrap_err().to_string();
        assert!(err.contains("no b64 header param"), "unexpected: {err}");
    }

    /// RFC 7515 §4.1.11: a `crit`-listed extension that is absent from the
    /// header is rejected on the sign side (even when declared understood).
    #[test]
    fn crit_lists_absent_extension_is_rejected_on_sign() {
        let mut header = JoseHeader::new("HS256");
        header.crit = Some(vec!["etsiU".to_string()]);
        // etsiU is declared understood but never added to the header.
        let opts = SignOptions {
            b64: true,
            understood_crit: vec!["etsiU".to_string()],
            allow_key_reference_headers: false,
        };
        let err = sign_with_options(&PanicSigner, b"p", &header, &opts)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("absent from the protected header"),
            "unexpected: {err}"
        );
    }

    /// The verify side likewise rejects a `crit`-listed extension that is
    /// absent from the header.
    #[test]
    fn crit_lists_absent_extension_is_rejected_on_verify() {
        use kryptering::Signer;
        let mut header = JoseHeader::new("HS256");
        header.crit = Some(vec!["etsiU".to_string()]);
        let header_b64 = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let payload_b64 = base64url::encode(b"p");
        let signing_input = format!("{header_b64}.{payload_b64}");
        let sig = hmac_signer().sign(signing_input.as_bytes()).unwrap();
        let token = format!("{signing_input}.{}", base64url::encode(&sig));
        let vopts = VerifyOptions {
            understood_crit: vec!["etsiU".to_string()],
        };
        let err = verify_with_options(&hmac_verifier(), &token, &vopts)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("absent from the protected header"),
            "unexpected: {err}"
        );
    }

    /// An unencoded compact payload containing a dot is rejected (RFC 7797
    /// §5.2 — it would collide with the segment separator).
    #[test]
    fn b64_false_dotted_payload_is_rejected() {
        let header = b64_false_header();
        let opts = SignOptions {
            b64: false,
            understood_crit: vec![],
            allow_key_reference_headers: false,
        };
        let err = sign_with_options(&hmac_signer(), b"a.b", &header, &opts)
            .unwrap_err()
            .to_string();
        assert!(err.contains("must not contain"), "unexpected: {err}");
    }

    #[test]
    fn b64_false_dotted_payload_is_rejected_before_signing() {
        let header = b64_false_header();
        let opts = SignOptions {
            b64: false,
            understood_crit: vec![],
            allow_key_reference_headers: false,
        };
        let err = sign_with_options(&PanicSigner, b"a.b", &header, &opts)
            .unwrap_err()
            .to_string();
        assert!(err.contains("must not contain"), "unexpected: {err}");
    }

    #[test]
    fn b64_false_non_utf8_payload_is_rejected_before_signing() {
        let header = b64_false_header();
        let opts = SignOptions {
            b64: false,
            understood_crit: vec![],
            allow_key_reference_headers: false,
        };
        let err = sign_with_options(&PanicSigner, &[0xff], &header, &opts)
            .unwrap_err()
            .to_string();
        assert!(err.contains("valid UTF-8"), "unexpected: {err}");
    }

    /// A caller-supplied understood crit param (JAdES-style) is accepted.
    #[test]
    fn caller_understood_crit_is_accepted() {
        let mut header = JoseHeader::new("HS256");
        header.crit = Some(vec!["etsiU".to_string()]);
        header
            .extra
            .insert("etsiU".to_string(), serde_json::Value::Array(vec![]));
        let opts = SignOptions {
            b64: true,
            understood_crit: vec!["etsiU".to_string()],
            allow_key_reference_headers: false,
        };
        let token = sign_with_options(&hmac_signer(), b"p", &header, &opts).unwrap();
        let vopts = VerifyOptions {
            understood_crit: vec!["etsiU".to_string()],
        };
        let recovered = verify_with_options(&hmac_verifier(), &token, &vopts).unwrap();
        assert_eq!(recovered, b"p");
        // Without declaring etsiU understood, verification rejects it.
        let err = verify_with_options(&hmac_verifier(), &token, &VerifyOptions::new())
            .unwrap_err()
            .to_string();
        assert!(err.contains("crit"), "unexpected: {err}");
    }

    /// RFC 7515 §4.1.11: "Producers MUST NOT include Header Parameter names
    /// defined by this specification or [JWA] for use with JWS ... in the
    /// `crit` list". Declaring the name understood does not lift the
    /// producer rule, and the check runs before the signer is invoked.
    #[test]
    fn registered_crit_param_is_rejected_at_sign() {
        let mut header = JoseHeader::new("HS256");
        header.kid = Some("key-1".to_string());
        header.crit = Some(vec!["kid".to_string()]);

        let opts = SignOptions::new().with_understood_crit(["kid"]);
        let err = sign_with_options(&PanicSigner, b"p", &header, &opts)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("registered header parameter kid"),
            "unexpected: {err}"
        );
    }

    /// RFC 7515 §4.1.11 only says recipients MAY treat a registered name in
    /// `crit` as invalid, so a peer's token with `crit: ["kid"]` still
    /// verifies when the caller declares `kid` understood. The token is
    /// built by hand because this crate refuses to emit it.
    #[test]
    fn registered_crit_param_from_peer_is_accepted_when_understood() {
        use kryptering::Signer;
        let mut header = JoseHeader::new("HS256");
        header.kid = Some("key-1".to_string());
        header.crit = Some(vec!["kid".to_string()]);
        let header_b64 = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let signing_input = format!("{header_b64}.{}", base64url::encode(b"p"));
        let sig = hmac_signer().sign(signing_input.as_bytes()).unwrap();
        let token = format!("{signing_input}.{}", base64url::encode(&sig));

        let vopts = VerifyOptions {
            understood_crit: vec!["kid".to_string()],
        };
        let recovered = verify_with_options(&hmac_verifier(), &token, &vopts).unwrap();
        assert_eq!(recovered, b"p");
    }

    /// RFC 7515 §4.1.11: producers MUST NOT include "duplicate names" in
    /// `crit`, including a repeated RFC 7797 `b64`.
    #[test]
    fn duplicate_crit_names_are_rejected_at_sign() {
        let mut header = JoseHeader::new("HS256");
        header
            .extra
            .insert("etsiU".into(), serde_json::json!(["x"]));
        header.crit = Some(vec!["etsiU".to_string(), "etsiU".to_string()]);
        let opts = SignOptions::new().with_understood_crit(["etsiU"]);
        let err = sign_with_options(&PanicSigner, b"p", &header, &opts)
            .unwrap_err()
            .to_string();
        assert!(err.contains("more than once"), "unexpected: {err}");

        let mut header = JoseHeader::new("HS256");
        header.extra.insert("b64".into(), serde_json::json!(false));
        header.crit = Some(vec!["b64".to_string(), "b64".to_string()]);
        let err = sign_with_options(
            &PanicSigner,
            b"p",
            &header,
            &SignOptions::new().with_b64(false),
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("more than once"), "unexpected: {err}");
    }

    /// ML-DSA sign/verify round-trip via the JWK API.
    ///
    /// One test per variant — ML-DSA keypairs are large (the expanded
    /// signing key for ML-DSA-87 is ~5 KiB), so looping all three in one
    /// test function blows the default debug-build stack.
    #[cfg(feature = "post-quantum")]
    fn mldsa_roundtrip(variant: kryptering::MlDsaVariant) {
        let jwk = crate::jwk::generate::generate_mldsa(variant).unwrap();
        let header = JoseHeader::new(variant.name());
        let payload = b"post-quantum JWS payload";

        let token = sign_with_jwk(&jwk, payload, &header)
            .unwrap_or_else(|e| panic!("{} sign failed: {e}", variant.name()));
        assert_eq!(token.split('.').count(), 3);

        let recovered = verify_with_jwk(&jwk, &token)
            .unwrap_or_else(|e| panic!("{} verify failed: {e}", variant.name()));
        assert_eq!(recovered, payload);
    }

    #[cfg(feature = "post-quantum")]
    #[test]
    fn sign_verify_mldsa_44_roundtrip() {
        mldsa_roundtrip(kryptering::MlDsaVariant::MlDsa44);
    }

    #[cfg(feature = "post-quantum")]
    #[test]
    fn sign_verify_mldsa_65_roundtrip() {
        mldsa_roundtrip(kryptering::MlDsaVariant::MlDsa65);
    }

    /// ML-DSA-87's expanded signing key is large enough that seed expansion
    /// plus ML-DSA signing blow the default debug-build test-thread
    /// stack (2 MiB). Run this variant on a fresh 8 MiB thread so the
    /// test actually completes. Release builds fit in the default stack,
    /// so this is purely a test-harness concern.
    #[cfg(feature = "post-quantum")]
    #[test]
    fn sign_verify_mldsa_87_roundtrip() {
        std::thread::Builder::new()
            .stack_size(8 * 1024 * 1024)
            .spawn(|| mldsa_roundtrip(kryptering::MlDsaVariant::MlDsa87))
            .expect("spawn mldsa-87 test thread")
            .join()
            .expect("mldsa-87 test thread panicked");
    }

    /// ML-DSA alg-confusion regression: a token signed with ML-DSA-44 must
    /// be rejected by a JWK pinned to ML-DSA-65. The phase-4 alg-binding
    /// catches the mismatch before any crypto runs.
    #[cfg(feature = "post-quantum")]
    #[test]
    fn mldsa_variant_mismatch_is_rejected() {
        use kryptering::MlDsaVariant;
        let jwk_44 = crate::jwk::generate::generate_mldsa(MlDsaVariant::MlDsa44).unwrap();
        let jwk_65 = crate::jwk::generate::generate_mldsa(MlDsaVariant::MlDsa65).unwrap();

        let header = JoseHeader::new("ML-DSA-44");
        let token = sign_with_jwk(&jwk_44, b"payload", &header).unwrap();

        // Verifier pinned to ML-DSA-65 must refuse a ML-DSA-44 token.
        let err = verify_with_jwk(&jwk_65, &token).unwrap_err().to_string();
        assert!(err.contains("does not match"), "unexpected error: {err}");
    }
}