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
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
//! JWS JSON Serialization (RFC 7515 Section 7.2).
//!
//! Supports both Flattened (Section 7.2.2) and General (Section 7.2.1)
//! forms, plus the JAdES-enabling extensions:
//!
//! - **Detached payload** (RFC 7515 Appendix F): the `payload` member is
//!   omitted from the JSON and supplied out-of-band at verify time.
//! - **Per-signature unprotected headers** (`header` member): populated on
//!   the sign side and consulted (returned) on the verify side — JAdES
//!   carries `etsiU` here.
//! - **Per-signature verification results**: [`verify_general_all`] returns
//!   one outcome per signature so a caller can see every signer's status,
//!   not just the first that verified.
//! - **RFC 7797 `b64`** and the understood-`crit` allow-list, via the
//!   [`crate::jws::SignOptions`] / [`crate::jws::VerifyOptions`] carried
//!   from `jws::compact`.
//!
//! Raw Edwards verifiers support their fully specified identifier and legacy `EdDSA`. Applications requiring one exact name must enforce their
//! protected-header algorithm policy in addition to primitive verification.

use std::borrow::Cow;

use serde::{Deserialize, Serialize};

use crate::base64url;
use crate::error::{JoseError, Result};
use crate::header::JoseHeader;
use crate::jws::compact::{
    prepare_sign_header, signing_input, signing_input_from_segment, validate_header_b64_opts,
    validate_header_opts, PreparedSignHeader,
};
use crate::jws::{SignOptions, VerifyOptions};

// ---------------------------------------------------------------------------
// Data structures
// ---------------------------------------------------------------------------

/// Header members that must only appear in a JWS protected header.
///
/// - `crit` MUST be integrity protected (RFC 7515 §4.1.11).
/// - `b64` MUST be integrity protected (RFC 7797 §3), since it changes how
///   the payload is interpreted.
///
/// JWE-only members such as `zip` and `enc` are refused separately
/// ([`crate::header::JWE_ONLY_MEMBERS`]), as in the protected header. `alg`
/// is covered by the protected/unprotected disjointness rule because the
/// protected [`JoseHeader`] always carries it.
const PROTECTED_ONLY_MEMBERS: &[&str] = &["crit", "b64"];

/// Validate a caller-supplied per-signature unprotected `header` member
/// before signing.
///
/// Unprotected members are not covered by the signature, yet RFC 7515 lets a
/// consumer read header parameters from the union of the protected and
/// unprotected headers. This crate's verifiers read only the protected
/// header, so the checks below exist to keep emitted JWS JSON unambiguous
/// for peers that merge the two:
///
/// 1. the value must be a JSON object (a JOSE Header is one);
/// 2. no member may also appear in the protected header (RFC 7515 §7.2.1
///    requires the two sets of names to be disjoint), which in particular
///    keeps a contradicting `alg` or `kid` out;
/// 3. no [`PROTECTED_ONLY_MEMBERS`] entry;
/// 4. no [`crate::header::JWE_ONLY_MEMBERS`] entry: RFC 7516 §9 identifies
///    a JWE by the presence of `enc`, so a peer merging the headers would
///    see one, and the others describe encryption a JWS never performs;
/// 5. no key-reference member (`jku`, `jwk`, `x5u`, `x5c`) unless
///    [`SignOptions::allow_key_reference_headers`] is set, matching the
///    protected-header policy.
///
/// # Errors
///
/// Returns [`JoseError::InvalidHeader`] naming the offending member.
fn validate_unprotected_header(
    unprotected: Option<&serde_json::Value>,
    protected: &JoseHeader,
    opts: &SignOptions,
) -> Result<()> {
    let Some(unprotected) = unprotected else {
        return Ok(());
    };
    let members = unprotected.as_object().ok_or_else(|| {
        JoseError::InvalidHeader("unprotected header must be a JSON object".into())
    })?;
    let protected_value = serde_json::to_value(protected)?;
    let protected_members = protected_value
        .as_object()
        .expect("JoseHeader serializes to a JSON object");
    for name in members.keys() {
        if protected_members.contains_key(name) {
            return Err(JoseError::InvalidHeader(format!(
                "unprotected header member {name} also appears in the protected header \
                 (RFC 7515 §7.2.1)"
            )));
        }
        if PROTECTED_ONLY_MEMBERS.contains(&name.as_str()) {
            return Err(JoseError::InvalidHeader(format!(
                "{name} must not appear in the unprotected header"
            )));
        }
        if crate::header::JWE_ONLY_MEMBERS.contains(&name.as_str()) {
            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)"
            )));
        }
        if !opts.allow_key_reference_headers
            && crate::header::KEY_REFERENCE_MEMBERS.contains(&name.as_str())
        {
            return Err(JoseError::InvalidHeader(format!(
                "{name} in unprotected header requires allow_key_reference_headers"
            )));
        }
    }
    Ok(())
}

/// Base64url-encode a signature for a JWS JSON `signature` member.
///
/// [`verify_flattened_opts`] and [`verify_general`] refuse a `signature`
/// member over [`crate::MAX_TOKEN_BYTES`], and the signer may be a
/// caller-supplied or HSM-backed [`kryptering::Signer`] whose output length
/// this crate does not control. Checking here keeps "every artifact this
/// crate emits, this crate can verify" true for the signature as well.
fn encode_signature(sig: &[u8]) -> Result<String> {
    let encoded = base64url::encode(sig);
    crate::ensure_emit_size(encoded.len())?;
    Ok(encoded)
}

/// Maximum number of signature entries accepted in a General JWS.
///
/// A General JWS is attacker-controlled input on verify. Keeping this bounded
/// prevents unbounded per-signature header parsing, result allocation, and
/// verifier attempts while remaining well above normal multi-signature use.
pub const MAX_GENERAL_SIGNATURES: usize = 64;

/// Flattened JWS JSON Serialization (RFC 7515 Section 7.2.2).
///
/// Contains a single signature over the payload. The `payload` member is
/// `None` for a detached signature (RFC 7515 Appendix F).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlattenedJws {
    /// Base64url-encoded payload. Omitted (detached) when `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload: Option<String>,
    /// Base64url-encoded protected header.
    pub protected: String,
    /// Optional per-signature unprotected header parameters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub header: Option<serde_json::Value>,
    /// Base64url-encoded signature.
    pub signature: String,
}

/// A single signature entry in General JWS JSON Serialization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JwsSignature {
    /// Base64url-encoded protected header.
    pub protected: String,
    /// Optional unprotected header parameters (JAdES `etsiU` lives here).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub header: Option<serde_json::Value>,
    /// Base64url-encoded signature.
    pub signature: String,
}

/// General JWS JSON Serialization (RFC 7515 Section 7.2.1).
///
/// Contains one or more signatures over a shared payload. The `payload`
/// member is `None` for a detached signature (RFC 7515 Appendix F).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneralJws {
    /// Base64url-encoded payload (shared across all signatures). Omitted
    /// (detached) when `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload: Option<String>,
    /// Array of signature objects.
    pub signatures: Vec<JwsSignature>,
}

/// Outcome of verifying one signature entry in a General JWS.
#[derive(Debug, Clone)]
pub struct SignatureResult {
    /// Index of the signature within the `signatures` array.
    pub index: usize,
    /// Parsed protected header for this signature (`None` if it could not be
    /// decoded — in which case `error` explains why).
    pub protected_header: Option<JoseHeader>,
    /// The unprotected `header` member as carried in the JWS, if any.
    /// Not integrity-protected: never select a key or make a trust decision from it.
    pub unprotected_header: Option<serde_json::Value>,
    /// Whether this signature verified successfully.
    pub verified: bool,
    /// Why verification failed (or the entry was skipped), if applicable.
    pub error: Option<String>,
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

enum PayloadSource<'a> {
    Embedded(&'a str),
    Detached(&'a [u8]),
}

impl PayloadSource<'_> {
    fn decode(&self, b64: bool) -> Result<Vec<u8>> {
        match self {
            Self::Embedded(payload) => {
                if b64 {
                    base64url::decode(payload)
                } else {
                    Ok(payload.as_bytes().to_vec())
                }
            }
            Self::Detached(payload) => Ok(payload.to_vec()),
        }
    }
}

fn ensure_general_signature_count(count: usize) -> Result<()> {
    if count > MAX_GENERAL_SIGNATURES {
        return Err(JoseError::InvalidToken(format!(
            "General JWS signature count {count} exceeds MAX_GENERAL_SIGNATURES ({MAX_GENERAL_SIGNATURES})"
        )));
    }
    Ok(())
}

/// Validate encoded-field sizes and protected/unprotected name disjointness before
/// allocating results, constructing keys, or attempting a signature.
fn preflight_flattened_structure(jws: &FlattenedJws) -> Result<()> {
    crate::jws::compact::ensure_token_size(&jws.protected)?;
    crate::jws::compact::ensure_token_size(&jws.signature)?;
    if let Some(payload) = &jws.payload {
        crate::jws::compact::ensure_token_size(payload)?;
    }
    validate_inbound_header_pair(&jws.protected, jws.header.as_ref())
}

/// General-JWS structural preflight shared by raw-verifier and JWK-aware APIs.
fn preflight_general_structure(jws: &GeneralJws) -> Result<()> {
    ensure_general_signature_count(jws.signatures.len())?;
    if let Some(payload) = &jws.payload {
        crate::jws::compact::ensure_token_size(payload)?;
    }
    for entry in &jws.signatures {
        crate::jws::compact::ensure_token_size(&entry.protected)?;
        crate::jws::compact::ensure_token_size(&entry.signature)?;
        validate_inbound_header_pair(&entry.protected, entry.header.as_ref())?;
    }
    Ok(())
}

/// Enforce RFC 7515 §7.2.1 over the original protected JSON member names.
///
/// Parsing directly into [`crate::member_map::MemberMap`] is intentional: converting to
/// [`JoseHeader`] and serializing it again can erase a present member whose value is
/// `null`, allowing that name to collide with an attacker-controlled unprotected value.
fn validate_inbound_header_pair(
    protected_segment: &str,
    unprotected: Option<&serde_json::Value>,
) -> Result<()> {
    let Some(unprotected) = unprotected else {
        return Ok(());
    };
    let unprotected = unprotected.as_object().ok_or_else(|| {
        JoseError::InvalidHeader("unprotected header must be a JSON object".into())
    })?;
    let protected_bytes = base64url::decode(protected_segment)?;
    let mut protected: crate::member_map::MemberMap = serde_json::from_slice(&protected_bytes)?;
    let protected_names = protected
        .drain_leftovers()
        .into_iter()
        .map(|(name, _)| name)
        .collect::<std::collections::HashSet<_>>();
    for name in unprotected.keys() {
        if protected_names.contains(name) {
            return Err(JoseError::InvalidHeader(format!(
                "unprotected header member {name} also appears in the protected header \
                 (RFC 7515 §7.2.1)"
            )));
        }
    }
    Ok(())
}

fn resolve_payload_for_verify<'a>(
    embedded: Option<&'a str>,
    detached: Option<&'a [u8]>,
    b64: bool,
) -> Result<(Cow<'a, [u8]>, PayloadSource<'a>)> {
    match (embedded, detached) {
        (Some(_), Some(_)) => Err(JoseError::InvalidToken(
            "both an embedded and a detached payload were supplied".into(),
        )),
        (None, None) => Err(JoseError::InvalidToken(
            "JWS has no payload member and no detached payload was supplied".into(),
        )),
        (Some(payload), None) => Ok((
            Cow::Borrowed(payload.as_bytes()),
            PayloadSource::Embedded(payload),
        )),
        (None, Some(payload)) => {
            let segment = if b64 {
                Cow::Owned(base64url::encode(payload).into_bytes())
            } else {
                Cow::Borrowed(payload)
            };
            Ok((segment, PayloadSource::Detached(payload)))
        }
    }
}

// ---------------------------------------------------------------------------
// Flattened JWS operations
// ---------------------------------------------------------------------------

/// Create a Flattened JWS JSON from a signer, payload, and header.
///
/// The supplied `header.alg` is cross-checked against `signer.algorithm()`
/// before signing; mismatches (including `alg: "none"` or an unsupported
/// `crit`) are rejected.
pub fn sign_flattened(
    signer: &dyn kryptering::Signer,
    payload: &[u8],
    header: &JoseHeader,
) -> Result<FlattenedJws> {
    sign_flattened_opts(signer, payload, header, None, &SignOptions::new())
}

/// Create a Flattened JWS JSON with full control over the unprotected
/// header, detached payload, and RFC 7797 / `crit` options.
///
/// - `unprotected`: the per-signature `header` member (JAdES `etsiU`, etc.).
///   Not integrity-protected: never select a key or make a trust decision from it.
/// - `opts.b64 == false`: RFC 7797 unencoded payload; the embedded `payload`
///   member, when present, carries the raw bytes.
pub fn sign_flattened_opts(
    signer: &dyn kryptering::Signer,
    payload: &[u8],
    header: &JoseHeader,
    unprotected: Option<serde_json::Value>,
    opts: &SignOptions,
) -> Result<FlattenedJws> {
    // Attached form: embed the payload member.
    let payload_member = if opts.b64 {
        base64url::encode(payload)
    } else {
        String::from_utf8(payload.to_vec()).map_err(|_| {
            JoseError::InvalidToken("unencoded (b64=false) payload must be valid UTF-8".into())
        })?
    };
    // `verify_flattened` refuses a payload member over MAX_TOKEN_BYTES.
    crate::ensure_emit_size(payload_member.len())?;
    let mut jws = sign_flattened_detached_opts(signer, payload, header, unprotected, opts)?;
    jws.payload = Some(payload_member);
    Ok(jws)
}

/// Create a **detached** Flattened JWS JSON (the `payload` member is
/// omitted). The payload is signed but not carried; the verifier supplies it
/// out-of-band.
pub fn sign_flattened_detached(
    signer: &dyn kryptering::Signer,
    payload: &[u8],
    header: &JoseHeader,
) -> Result<FlattenedJws> {
    sign_flattened_detached_opts(signer, payload, header, None, &SignOptions::new())
}

/// Detached Flattened sign with full options.
pub fn sign_flattened_detached_opts(
    signer: &dyn kryptering::Signer,
    payload: &[u8],
    header: &JoseHeader,
    unprotected: Option<serde_json::Value>,
    opts: &SignOptions,
) -> Result<FlattenedJws> {
    let PreparedSignHeader { b64, protected_b64 } = prepare_sign_header(header, signer, opts)?;
    validate_unprotected_header(unprotected.as_ref(), header, opts)?;
    let input = signing_input(&protected_b64, payload, b64);
    let sig = signer.sign(&input).map_err(JoseError::Crypto)?;
    let signature = encode_signature(&sig)?;
    Ok(FlattenedJws {
        payload: None,
        protected: protected_b64,
        header: unprotected,
        signature,
    })
}

/// Verify a Flattened JWS JSON and return the decoded payload.
///
/// The protected header's `alg` is cross-checked against
/// `verifier.algorithm()`; `alg: "none"` and any unsupported `crit` are
/// rejected before any cryptographic operation. The JWS must carry an
/// embedded payload — use [`verify_flattened_detached`] for the detached
/// case.
pub fn verify_flattened(
    verifier: &dyn kryptering::Verifier,
    jws: &FlattenedJws,
) -> Result<Vec<u8>> {
    verify_flattened_opts(verifier, jws, None, &VerifyOptions::new())
}

/// Verify a **detached** Flattened JWS JSON against an externally supplied
/// payload.
pub fn verify_flattened_detached(
    verifier: &dyn kryptering::Verifier,
    jws: &FlattenedJws,
    detached_payload: &[u8],
) -> Result<Vec<u8>> {
    verify_flattened_opts(verifier, jws, Some(detached_payload), &VerifyOptions::new())
}

/// Verify a Flattened JWS JSON with full control over the detached payload
/// and `crit` options.
pub fn verify_flattened_opts(
    verifier: &dyn kryptering::Verifier,
    jws: &FlattenedJws,
    detached_payload: Option<&[u8]>,
    opts: &VerifyOptions,
) -> Result<Vec<u8>> {
    preflight_flattened_structure(jws)?;
    let b64 = validate_header_opts(&jws.protected, verifier, opts)?;
    let (payload_segment, payload_source) =
        resolve_payload_for_verify(jws.payload.as_deref(), detached_payload, b64)?;
    let input = signing_input_from_segment(&jws.protected, payload_segment.as_ref());
    let sig = base64url::decode(&jws.signature)?;
    let valid = verifier.verify(&input, &sig).map_err(JoseError::Crypto)?;
    if !valid {
        return Err(JoseError::InvalidToken(
            crate::SIGNATURE_VERIFICATION_FAILED.into(),
        ));
    }
    payload_source.decode(b64)
}

// ---------------------------------------------------------------------------
// General JWS operations
// ---------------------------------------------------------------------------

/// One signer entry for a General JWS: a signer, its protected header, and
/// an optional per-signature unprotected `header` member.
pub struct GeneralSigner<'a> {
    /// Cryptographic signer used for this signature entry.
    pub signer: &'a dyn kryptering::Signer,
    /// Protected JOSE header authenticated by this signature.
    pub protected: &'a JoseHeader,
    /// Optional unprotected per-signature header parameters.
    /// Not integrity-protected: never select a key or make a trust decision from it.
    pub unprotected: Option<serde_json::Value>,
    /// Signing and critical-header validation options.
    pub options: SignOptions,
}

impl<'a> GeneralSigner<'a> {
    /// Convenience constructor with default options and no unprotected
    /// header.
    pub fn new(signer: &'a dyn kryptering::Signer, protected: &'a JoseHeader) -> Self {
        Self {
            signer,
            protected,
            unprotected: None,
            options: SignOptions::new(),
        }
    }
}

/// Create a General JWS JSON with multiple signers.
///
/// Each element of `signers` is a `(signer, header)` pair. All signers sign
/// the same payload; their protected headers are serialized independently.
/// No per-signature unprotected header is emitted — use
/// [`sign_general_full`] for that.
pub fn sign_general(
    signers: &[(&dyn kryptering::Signer, &JoseHeader)],
    payload: &[u8],
) -> Result<GeneralJws> {
    let entries: Vec<GeneralSigner<'_>> = signers
        .iter()
        .map(|(s, h)| GeneralSigner::new(*s, h))
        .collect();
    sign_general_full(&entries, payload, true)
}

/// Create a General JWS JSON with per-signature unprotected headers and
/// RFC 7797 / `crit` options, optionally detached.
///
/// `embed_payload == false` produces a detached JWS (the `payload` member is
/// omitted). All entries must agree on the effective `b64` value (they sign
/// over a shared payload, so a mixed encoding would be ambiguous).
pub fn sign_general_full(
    signers: &[GeneralSigner<'_>],
    payload: &[u8],
    embed_payload: bool,
) -> Result<GeneralJws> {
    if signers.is_empty() {
        return Err(JoseError::InvalidToken(
            "at least one signer is required".into(),
        ));
    }
    ensure_general_signature_count(signers.len())?;

    // Determine the shared b64 from the first entry and require agreement.
    let shared_b64 = signers[0].options.b64;
    if signers.iter().any(|e| e.options.b64 != shared_b64) {
        return Err(JoseError::InvalidToken(
            "all signers in a General JWS must agree on the b64 setting".into(),
        ));
    }

    // All signers agree on `b64` (enforced above) and sign over the same
    // payload, so encode the shared payload segment exactly once and reuse it
    // for every signing input — avoids the O(n * payload_size) cost of
    // re-encoding inside `signing_input` per signer. The base64url text (when
    // `b64=true`) doubles as the embedded `payload` member.
    let encoded_payload = if shared_b64 {
        Some(base64url::encode(payload))
    } else {
        None
    };
    // The bytes appended after the protected header in every signing input:
    // base64url text for `b64=true`, raw payload bytes for `b64=false`.
    let payload_segment: &[u8] = match &encoded_payload {
        Some(encoded) => encoded.as_bytes(),
        None => payload,
    };

    // For the attached form, validate up front that the payload can be embedded
    // (b64=false requires UTF-8) so an invalid payload is rejected before any
    // (possibly HSM-backed) signing runs.
    let payload_member = if embed_payload {
        let member = match &encoded_payload {
            Some(encoded) => encoded.clone(),
            None => String::from_utf8(payload.to_vec()).map_err(|_| {
                JoseError::InvalidToken("unencoded (b64=false) payload must be valid UTF-8".into())
            })?,
        };
        Some(member)
    } else {
        None
    };

    if let Some(member) = &payload_member {
        // `verify_general` refuses a payload member over MAX_TOKEN_BYTES.
        crate::ensure_emit_size(member.len())?;
    }

    // Validate and serialize every entry before signing any of them, so an
    // invalid later entry cannot waste (possibly HSM-backed) signatures.
    let mut prepared = Vec::with_capacity(signers.len());
    for entry in signers {
        // Validates each header's alg/crit/key-reference policy; the returned
        // b64 equals `shared_b64` (agreement enforced above), so the
        // precomputed payload segment applies to every entry.
        let PreparedSignHeader { protected_b64, .. } =
            prepare_sign_header(entry.protected, entry.signer, &entry.options)?;
        validate_unprotected_header(entry.unprotected.as_ref(), entry.protected, &entry.options)?;
        prepared.push(protected_b64);
    }

    let mut signatures = Vec::with_capacity(signers.len());
    for (entry, protected_b64) in signers.iter().zip(prepared) {
        let input = signing_input_from_segment(&protected_b64, payload_segment);
        let sig = entry.signer.sign(&input).map_err(JoseError::Crypto)?;
        signatures.push(JwsSignature {
            protected: protected_b64,
            header: entry.unprotected.clone(),
            signature: encode_signature(&sig)?,
        });
    }

    Ok(GeneralJws {
        payload: payload_member,
        signatures,
    })
}

/// Verify at least one signature in a General JWS JSON.
///
/// Iterates through signatures whose protected header's `alg` matches
/// `verifier.algorithm()` (per-entry algorithm binding — J-01/J-02).
/// Returns the decoded payload on the first successful cryptographic
/// verification. For per-signature outcomes, use [`verify_general_all`].
pub fn verify_general(verifier: &dyn kryptering::Verifier, jws: &GeneralJws) -> Result<Vec<u8>> {
    verify_general_opts(verifier, jws, None, &VerifyOptions::new())
}

/// Verify a General JWS, returning the payload on the first valid signature,
/// with control over the detached payload and `crit` options.
pub fn verify_general_opts(
    verifier: &dyn kryptering::Verifier,
    jws: &GeneralJws,
    detached_payload: Option<&[u8]>,
    opts: &VerifyOptions,
) -> Result<Vec<u8>> {
    if jws.signatures.is_empty() {
        return Err(JoseError::InvalidToken("no signatures present".into()));
    }
    // Short-circuit on the first signature that verifies: `verify_general`
    // only needs one valid signature, so there is no reason to run the verifier
    // over the remaining (caller-supplied) entries. Exhaustive per-signature
    // reporting is available via `verify_general_all`.
    let (_results, payload) = verify_general_inner(verifier, jws, detached_payload, opts, true)?;
    payload.ok_or_else(|| JoseError::InvalidToken("no signature verified successfully".into()))
}

/// Verify **every** signature in a General JWS against the given verifier and
/// return a per-signature outcome.
///
/// This is the multi-signer reporting API: a caller (e.g. a JAdES validator)
/// can see, for each signature, whether it verified, the parsed protected
/// header, and the unprotected `header` member. Entries whose algorithm does
/// not match the verifier are reported as `verified: false` with an
/// explanatory `error` rather than silently skipped.
///
/// The returned tuple's second element is `Some(payload)` when **at least one**
/// signature verified (so the caller does not have to base64url-decode it
/// again), and `None` when no signature verified — the API never hands back
/// payload bytes that nothing authenticated. An error is returned only for
/// whole-JWS problems (no signatures, payload resolution failure); individual
/// signature failures are reported in the results vector.
pub fn verify_general_all(
    verifier: &dyn kryptering::Verifier,
    jws: &GeneralJws,
    detached_payload: Option<&[u8]>,
    opts: &VerifyOptions,
) -> Result<(Vec<SignatureResult>, Option<Vec<u8>>)> {
    if jws.signatures.is_empty() {
        return Err(JoseError::InvalidToken("no signatures present".into()));
    }
    verify_general_inner(verifier, jws, detached_payload, opts, false)
}

/// Shared core for the General-JWS verify paths. Attempts each signature,
/// collecting per-entry results, and returns the payload only if at least one
/// signature verified (`None` otherwise).
///
/// When `stop_on_first_valid` is true the loop returns as soon as a signature
/// verifies (used by `verify_general`, which needs only one valid signature);
/// when false every signature is attempted (used by `verify_general_all`).
fn verify_general_inner(
    verifier: &dyn kryptering::Verifier,
    jws: &GeneralJws,
    detached_payload: Option<&[u8]>,
    opts: &VerifyOptions,
    stop_on_first_valid: bool,
) -> Result<(Vec<SignatureResult>, Option<Vec<u8>>)> {
    preflight_general_structure(jws)?;

    let mut shared_b64: Option<bool> = None;
    for entry in &jws.signatures {
        let Ok(b64) = validate_header_b64_opts(&entry.protected, opts) else {
            continue;
        };
        if let Some(expected) = shared_b64 {
            if b64 != expected {
                return Err(JoseError::InvalidToken(
                    "all signatures in a General JWS must agree on the b64 setting".into(),
                ));
            }
        } else {
            shared_b64 = Some(b64);
        }
    }

    // All entries that pass header validation agree on `b64` (enforced above)
    // and the payload member is shared, so prepare the signing-input segment
    // exactly once. Embedded payloads reuse the transmitted segment verbatim;
    // payload bytes are decoded only after at least one signature verifies.
    let shared_payload = match shared_b64 {
        Some(b64) => Some(resolve_payload_for_verify(
            jws.payload.as_deref(),
            detached_payload,
            b64,
        )?),
        None => None,
    };

    let mut results = Vec::with_capacity(jws.signatures.len());
    let mut any_verified = false;

    for (index, entry) in jws.signatures.iter().enumerate() {
        let mut result = SignatureResult {
            index,
            protected_header: None,
            unprotected_header: entry.header.clone(),
            verified: false,
            error: None,
        };

        // Decode the protected header for reporting (best-effort).
        if let Ok(bytes) = base64url::decode(&entry.protected) {
            if let Ok(h) = serde_json::from_slice::<JoseHeader>(&bytes) {
                result.protected_header = Some(h);
            }
        }

        if let Err(e) = validate_header_opts(&entry.protected, verifier, opts) {
            result.error = Some(e.to_string());
            results.push(result);
            continue;
        }

        // A validated entry implies `shared_b64` (and therefore the shared
        // payload segment) was resolved above; the per-entry `b64` equals
        // `shared_b64`, so the precomputed segment applies to every entry.
        let segment = shared_payload
            .as_ref()
            .map(|(segment, _)| segment.as_ref())
            .expect("a validated signature entry implies the shared payload segment was resolved");

        let input = signing_input_from_segment(&entry.protected, segment);
        let sig = match base64url::decode(&entry.signature) {
            Ok(s) => s,
            Err(e) => {
                result.error = Some(format!("signature is not valid base64url: {e}"));
                results.push(result);
                continue;
            }
        };
        match verifier.verify(&input, &sig) {
            Ok(true) => {
                result.verified = true;
                any_verified = true;
            }
            Ok(false) => {
                result.error = Some(crate::SIGNATURE_VERIFICATION_FAILED.into());
            }
            Err(e) => {
                result.error = Some(format!("verifier error: {e}"));
            }
        }
        let verified = result.verified;
        results.push(result);
        if stop_on_first_valid && verified {
            break;
        }
    }

    // Return the payload only when a signature actually verified. A verification
    // API must never hand back payload bytes that nothing authenticated, so a
    // caller cannot accidentally consume unsigned data.
    let resolved_payload = if any_verified {
        match (shared_b64, shared_payload) {
            (Some(b64), Some((_, payload_source))) => Some(payload_source.decode(b64)?),
            _ => None,
        }
    } else {
        None
    };
    Ok((results, resolved_payload))
}

// ---------------------------------------------------------------------------
// JWK-aware convenience APIs (plan L2)
// ---------------------------------------------------------------------------

/// Maximum number of candidate keys the JWK-aware General-JWS verify paths will
/// try per signature.
///
/// Trying keys is not free and not risk-free: each attempt is a signature
/// verification over attacker-chosen bytes. The bound exists so a caller who
/// hands over a JWK Set scraped from a network cannot turn "which key signed
/// this?" into a cost multiplier. Selection *policy* (kid matching, fallback,
/// ordering) is [L3](https://github.com/); this is only the ceiling.
pub const MAX_CANDIDATE_KEYS: usize = 64;

/// Create a Flattened JWS JSON using a JWK directly.
///
/// The signer is derived from the JWK by the same internal rule set that
/// `compact::sign_with_jwk` uses — the same function,
/// [`sign_with_jwk`](crate::jws::compact::sign_with_jwk) uses — so the key
/// metadata rules are not a parallel copy: `jwk.alg` must be set and must match
/// `header.alg`, `use`/`key_ops` are enforced for signing, and the key is
/// converted under the algorithm's strength rules (an RSA key under 2048 bits or
/// a short HMAC key is refused here, not at some later point).
///
/// ```
/// use jose_rs::jwk;
/// use jose_rs::jws::json;
/// use jose_rs::JoseHeader;
///
/// let mut jwk = jwk::generate_ec("P-256")?;
/// jwk.alg = Some("ES256".into());
/// let flattened = json::sign_flattened_with_jwk(&jwk, b"payload", &JoseHeader::new("ES256"))?;
/// let payload = json::verify_flattened_with_jwk(&jwk, &flattened)?;
/// assert_eq!(payload, b"payload");
/// # Ok::<(), jose_rs::JoseError>(())
/// ```
pub fn sign_flattened_with_jwk(
    jwk: &crate::jwk::Jwk,
    payload: &[u8],
    header: &JoseHeader,
) -> Result<FlattenedJws> {
    sign_flattened_with_jwk_opts(jwk, payload, header, None, &SignOptions::new())
}

/// Verify a flattened JWS with a JWK, returning the payload with the header the
/// signature authenticated and the unprotected metadata kept separate.
///
/// [`Authenticated::protected`](crate::Authenticated::protected) is the header that was covered by this signature;
/// [`Authenticated::unprotected`](crate::Authenticated::unprotected) is the per-signature `header` member, verbatim and
/// clearly labelled as not covered. They are not merged: a caller that reads `alg` or
/// `kid` from the merged view cannot tell a forged value from an authenticated one.
pub fn verify_flattened_with_jwk_authenticated(
    jwk: &crate::jwk::Jwk,
    jws: &FlattenedJws,
) -> Result<crate::Authenticated<Vec<u8>>> {
    let payload = verify_flattened_with_jwk(jwk, jws)?;
    let protected = decode_protected(&jws.protected)?;
    let unprotected: Vec<serde_json::Value> = jws.header.clone().into_iter().collect();
    Ok(crate::Authenticated::new(payload, protected, unprotected))
}

/// [`sign_flattened_with_jwk`] with the per-signature unprotected header and/// [`sign_flattened_with_jwk`] with the per-signature unprotected header and
/// RFC 7797 / `crit` options.
pub fn sign_flattened_with_jwk_opts(
    jwk: &crate::jwk::Jwk,
    payload: &[u8],
    header: &JoseHeader,
    unprotected: Option<serde_json::Value>,
    opts: &SignOptions,
) -> Result<FlattenedJws> {
    let signer = crate::jws::compact::signer_from_jwk(jwk, header)?;
    sign_flattened_opts(&signer, payload, header, unprotected, opts)
}

/// Create a **detached** Flattened JWS JSON using a JWK directly.
pub fn sign_flattened_detached_with_jwk(
    jwk: &crate::jwk::Jwk,
    payload: &[u8],
    header: &JoseHeader,
) -> Result<FlattenedJws> {
    sign_flattened_detached_with_jwk_opts(jwk, payload, header, None, &SignOptions::new())
}

/// Detached Flattened sign with a JWK and full options.
pub fn sign_flattened_detached_with_jwk_opts(
    jwk: &crate::jwk::Jwk,
    payload: &[u8],
    header: &JoseHeader,
    unprotected: Option<serde_json::Value>,
    opts: &SignOptions,
) -> Result<FlattenedJws> {
    let signer = crate::jws::compact::signer_from_jwk(jwk, header)?;
    sign_flattened_detached_opts(&signer, payload, header, unprotected, opts)
}

/// Verify a Flattened JWS JSON using a JWK directly.
///
/// The algorithm comes from the JWS's own protected header and the verifier is
/// built by the same internal rule set `compact::verify_with_jwk` uses — one function,
/// [`verify_with_jwk`](crate::jws::compact::verify_with_jwk) uses: a pinned
/// `jwk.alg` must match (including same-curve Edwards aliases); `use`/`key_ops` are enforced
/// for verification, and strength is checked against the *token's* algorithm —
/// so an HS256-sized secret cannot be used for an HS512 token by editing the
/// header, whether or not `alg` is pinned.
pub fn verify_flattened_with_jwk(jwk: &crate::jwk::Jwk, jws: &FlattenedJws) -> Result<Vec<u8>> {
    verify_flattened_with_jwk_opts(jwk, jws, None, &VerifyOptions::new())
}

/// Verify a **detached** Flattened JWS JSON using a JWK directly.
pub fn verify_flattened_detached_with_jwk(
    jwk: &crate::jwk::Jwk,
    jws: &FlattenedJws,
    detached_payload: &[u8],
) -> Result<Vec<u8>> {
    verify_flattened_with_jwk_opts(jwk, jws, Some(detached_payload), &VerifyOptions::new())
}

/// Flattened verify with a JWK, an optional detached payload and `crit` options.
///
/// `detached_payload` is the out-of-band payload; passing `None` requires the JWS
/// to carry the `payload` member. This is the single JWK-aware flattened entry
/// point; the two above are it with defaults.
pub fn verify_flattened_with_jwk_opts(
    jwk: &crate::jwk::Jwk,
    jws: &FlattenedJws,
    detached_payload: Option<&[u8]>,
    opts: &VerifyOptions,
) -> Result<Vec<u8>> {
    preflight_flattened_structure(jws)?;
    let header = decode_protected(&jws.protected)?;
    let verifier = crate::jws::compact::verifier_from_jwk(jwk, &header.alg)?;
    verify_flattened_opts(&verifier, jws, detached_payload, opts)
}

/// One entry of a JWK-aware General JWS signature list.
///
/// Mirrors [`GeneralSigner`] but holds a [`Jwk`](crate::jwk::Jwk) instead of a
/// built signer, so the caller does not have to reimplement operation-aware key
/// conversion (and get its rules subtly wrong) to use the General serialization.
pub struct GeneralJwkSigner<'a> {
    /// Signing key; its `alg` must be set and match `protected.alg`.
    pub jwk: &'a crate::jwk::Jwk,
    /// Protected header authenticated by this signature.
    pub protected: &'a JoseHeader,
    /// Optional unprotected per-signature header parameters.
    /// Not integrity-protected: never select a key or make a trust decision from it.
    pub unprotected: Option<serde_json::Value>,
    /// Signing and critical-header validation options.
    pub options: SignOptions,
}

impl<'a> GeneralJwkSigner<'a> {
    /// Convenience constructor with default options and no unprotected header.
    pub fn new(jwk: &'a crate::jwk::Jwk, protected: &'a JoseHeader) -> Self {
        Self {
            jwk,
            protected,
            unprotected: None,
            options: SignOptions::new(),
        }
    }
}

/// Create a General JWS JSON from `(JWK, protected header)` pairs.
pub fn sign_general_with_jwk_pairs(
    entries: &[(&crate::jwk::Jwk, &JoseHeader)],
    payload: &[u8],
) -> Result<GeneralJws> {
    let full: Vec<GeneralJwkSigner<'_>> = entries
        .iter()
        .map(|(jwk, header)| GeneralJwkSigner::new(jwk, header))
        .collect();
    sign_general_with_jwks(&full, payload, true)
}

/// Create a General JWS JSON from JWK entries, with per-signature unprotected
/// headers, options, and the detached-payload switch.
///
/// Every entry's key rules are checked *before* any signature is produced
/// (`sign_general_full` validates all headers up front), so a bad later entry
/// cannot waste an earlier, possibly HSM-backed, signature.
pub fn sign_general_with_jwks(
    entries: &[GeneralJwkSigner<'_>],
    payload: &[u8],
    embed_payload: bool,
) -> Result<GeneralJws> {
    // Two passes on purpose: every key must clear the rule set before any signing
    // starts, because a key-rule failure halfway through would leave the earlier
    // signatures already spent (and, with an HSM-backed key, already billed).
    let signers: Vec<kryptering::SoftwareSigner> = entries
        .iter()
        .map(|entry| crate::jws::compact::signer_from_jwk(entry.jwk, entry.protected))
        .collect::<Result<Vec<_>>>()?;
    let generals: Vec<GeneralSigner<'_>> = signers
        .iter()
        .zip(entries.iter())
        .map(|(signer, entry)| GeneralSigner {
            signer,
            protected: entry.protected,
            unprotected: entry.unprotected.clone(),
            options: entry.options.clone(),
        })
        .collect();
    sign_general_full(&generals, payload, embed_payload)
}

/// How a multi-key General-JWS verification decides success.
///
/// The choice is deliberately the caller's: "at least one of these keys signed
/// it" and "every signature here is valid" are different security statements, and
/// a library that picks one silently will eventually pick the wrong one for
/// someone.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignaturePolicy {
    /// Success when at least one signature verifies.
    Any,
    /// Success only when every signature in the document verifies.
    All,
}

/// Per-signature outcome of a JWK-aware General JWS verification.
#[derive(Debug, Clone)]
pub struct JwkSignatureResult {
    /// Index within the `signatures` array.
    pub index: usize,
    /// Parsed protected header (`None` when it could not be decoded).
    pub protected_header: Option<JoseHeader>,
    /// The unprotected `header` member as carried. Not integrity-protected.
    pub unprotected_header: Option<serde_json::Value>,
    /// Whether this signature verified.
    pub verified: bool,
    /// Whether this signature was cryptographically attempted at all.
    ///
    /// With [`SignaturePolicy::Any`] the loop stops at the first valid signature, so a later
    /// entry can be `verified: false, attempted: false` — "not attempted", not "failed". Without
    /// this field a short-circuited report would claim a signature was checked and rejected,
    /// which is a different (and wrong) statement about the document.
    pub attempted: bool,
    /// Index into the candidate list of the key that verified it, when one did.
    ///
    /// Reported so a caller can act on *which* key signed (rotation, tenancy,
    /// audit) instead of re-deriving it.
    pub key_index: Option<usize>,
    /// Why it did not verify, if applicable.
    pub error: Option<String>,
}

/// Outcome of a JWK-aware General JWS verification.
#[derive(Debug, Clone)]
pub struct GeneralVerifyReport {
    /// Per-signature outcomes, in document order.
    pub results: Vec<JwkSignatureResult>,
    /// Payload bytes, present only when the policy was satisfied. Never
    /// populated for bytes nothing authenticated.
    pub payload: Option<Vec<u8>>,
}

impl GeneralVerifyReport {
    /// `true` when the policy was satisfied (equivalently, `payload.is_some()`).
    pub fn satisfied(&self) -> bool {
        self.payload.is_some()
    }
}

/// Verify a General JWS against a list of candidate JWKs under an explicit
/// success policy.
///
/// For each signature the candidate keys are tried in list order; the first key
/// that verifies is recorded in [`JwkSignatureResult::key_index`]. Attempts are
/// bounded by [`MAX_CANDIDATE_KEYS`] keys and [`MAX_GENERAL_SIGNATURES`]
/// signatures, because key discovery over attacker-chosen bytes is work an
/// attacker gets to size.
///
/// Keys that cannot even be considered for a signature's algorithm (a pinned
/// `alg` mismatch, a `use: enc` key, an HMAC secret of the wrong size) are
/// recorded as *reasons*, not silently skipped: `results[i].error` explains why
/// nothing matched, which is the difference between a diagnosable outage and a
/// mystery.
///
/// # Errors
///
/// [`JoseError::InvalidToken`] for whole-document problems (no signatures, too
/// many candidates, payload resolution failure). Individual signature failures
/// are reported in `results`, and the error variant for an unsatisfied policy is
/// also `InvalidToken` — inspect `results` to see why.
pub fn verify_general_with_jwks(
    jwks: &[&crate::jwk::Jwk],
    jws: &GeneralJws,
    detached_payload: Option<&[u8]>,
    opts: &VerifyOptions,
    policy: SignaturePolicy,
) -> Result<GeneralVerifyReport> {
    if jws.signatures.is_empty() {
        return Err(JoseError::InvalidToken("no signatures present".into()));
    }
    if jwks.is_empty() {
        return Err(JoseError::Key("no candidate keys supplied".into()));
    }
    if jwks.len() > MAX_CANDIDATE_KEYS {
        return Err(JoseError::InvalidToken(format!(
            "{} candidate keys exceeds the {MAX_CANDIDATE_KEYS} key limit",
            jwks.len()
        )));
    }
    preflight_general_structure(jws)?;

    let mut results: Vec<JwkSignatureResult> = Vec::with_capacity(jws.signatures.len());
    for (index, entry) in jws.signatures.iter().enumerate() {
        let protected_header = match base64url::decode(&entry.protected) {
            Ok(bytes) => serde_json::from_slice::<JoseHeader>(&bytes).ok(),
            Err(_) => None,
        };
        results.push(JwkSignatureResult {
            index,
            protected_header,
            unprotected_header: entry.header.clone(),
            verified: false,
            attempted: false,
            key_index: None,
            error: None,
        });
    }

    // Reasons are kept in two tiers, because "the only thing wrong with this signature is that
    // you tried it with the wrong kind of key" is not the message a caller needs while a real
    // failure is also on the table. `failures` holds complaints from a verifier whose algorithm
    // *did* match the signature — the informative kind. `notes` holds everything else: a key that
    // the algorithm or the key's own metadata excludes, which is what the loop falls back to when
    // nothing better was learned.
    let mut failures: Vec<Option<String>> = vec![None; results.len()];
    let mut notes: Vec<Option<String>> = vec![None; results.len()];

    let mut payload: Option<Vec<u8>> = None;
    let mut any_verified = false;

    // The algorithms present, deduplicated by *spelling*: `EdDSA` and `Ed25519` are distinct
    // wire names. Keep each spelling to construct the appropriate verifier while
    // preserving per-signature reporting; JWK pin matching handles curve aliases.
    let mut present_algs: Vec<String> = Vec::new();
    for entry in &jws.signatures {
        let Ok(header) = decode_protected(&entry.protected) else {
            continue;
        };
        if !present_algs.iter().any(|existing| existing == &header.alg) {
            present_algs.push(header.alg.clone());
        }
    }

    'keys: for (key_index, jwk) in jwks.iter().enumerate() {
        for alg in &present_algs {
            let verifier = match crate::jws::compact::verifier_from_jwk(jwk, alg) {
                Ok(verifier) => verifier,
                Err(err) => {
                    // This key cannot serve this algorithm at all. Record *why* against the
                    // signatures that asked for it: a caller whose JWKS is full of `use: enc`
                    // keys deserves "key not usable for verification" over a generic failure.
                    let reason = err.to_string();
                    for result in &mut results {
                        if result
                            .protected_header
                            .as_ref()
                            .is_some_and(|header| &header.alg == alg)
                            && notes[result.index].is_none()
                        {
                            notes[result.index] = Some(reason.clone());
                        }
                    }
                    continue;
                }
            };

            // `?` on purpose: a whole-document failure (payload encoding, mismatched `b64`
            // between entries) is not a per-key problem, so it applies to every candidate and is
            // reported as itself rather than attributed to whichever key was being tried.
            let (per_signature, maybe_payload) =
                verify_general_all(&verifier, jws, detached_payload, opts)?;

            for single in per_signature {
                let result = &mut results[single.index];
                // Only signatures with this verifier's algorithm count as genuinely attempted;
                // the rest were skipped by the shared verify core, which reports the algorithm
                // mismatch for them.
                let matched = result
                    .protected_header
                    .as_ref()
                    .is_some_and(|header| &header.alg == alg);
                if matched {
                    result.attempted = true;
                }

                if !single.verified {
                    if matched && failures[single.index].is_none() {
                        failures[single.index] = Some(single.error.unwrap_or_default());
                    } else if !matched && notes[single.index].is_none() {
                        notes[single.index] = single.error;
                    }
                    continue;
                }

                any_verified = true;
                if !result.verified {
                    result.verified = true;
                    result.key_index = Some(key_index);
                    result.error = None;
                }
                if payload.is_none() {
                    payload = maybe_payload.clone();
                }
            }

            // `Any`: stop at the first authenticated document. Remaining candidates add nothing
            // and every one of them costs a verification over attacker-chosen bytes.
            if matches!(policy, SignaturePolicy::Any) && any_verified {
                break 'keys;
            }
        }
    }

    // Best available reason per signature, then the policy decision.
    for (index, result) in results.iter_mut().enumerate() {
        if result.verified {
            continue;
        }
        let reason = failures[index]
            .take()
            .or_else(|| notes[index].take())
            .filter(|reason| !reason.is_empty());
        result.error = Some(match (reason, result.attempted) {
            (Some(reason), true) => reason,
            // Both halves matter here: the reason the only applicable attempt failed *and* the
            // fact that no candidate which could have matched was ever reached. Reporting just the
            // first reads as "this signature is bad" when the truth is "we stopped early".
            (Some(reason), false) => format!(
                "{reason}; and no further candidate was tried (the any-signature policy was \
                 already satisfied)"
            ),
            (None, true) => "no candidate key verified this signature".into(),
            (None, false) => "not attempted: the any-signature policy was already satisfied".into(),
        });
    }

    let satisfied = match policy {
        SignaturePolicy::Any => any_verified,
        // `All`: every signature must have verified. A document that only some of its signers
        // signed is not the document this caller asked to accept.
        SignaturePolicy::All => results.iter().all(|result| result.verified),
    };
    if !satisfied {
        return Err(JoseError::InvalidToken(match policy {
            SignaturePolicy::Any => "no candidate key verified any signature".into(),
            SignaturePolicy::All => {
                let failed: Vec<usize> = results
                    .iter()
                    .filter(|result| !result.verified)
                    .map(|result| result.index)
                    .collect();
                format!(
                    "all-signatures policy not satisfied: signature(s) {failed:?} did not verify"
                )
            }
        }));
    }

    Ok(GeneralVerifyReport { results, payload })
}

/// [`verify_general_with_jwks`] with the [`SignaturePolicy::Any`] policy and
/// default verify options.
pub fn verify_general_with_jwk_any(jwks: &[&crate::jwk::Jwk], jws: &GeneralJws) -> Result<Vec<u8>> {
    let report =
        verify_general_with_jwks(jwks, jws, None, &VerifyOptions::new(), SignaturePolicy::Any)?;
    report
        .payload
        .ok_or_else(|| JoseError::InvalidToken("no signature verified".into()))
}

/// [`verify_general_with_jwks`] with the [`SignaturePolicy::All`] policy and
/// default verify options.
pub fn verify_general_with_jwk_all(jwks: &[&crate::jwk::Jwk], jws: &GeneralJws) -> Result<Vec<u8>> {
    let report =
        verify_general_with_jwks(jwks, jws, None, &VerifyOptions::new(), SignaturePolicy::All)?;
    report
        .payload
        .ok_or_else(|| JoseError::InvalidToken("not every signature verified".into()))
}

/// Decode a base64url protected header segment.
fn decode_protected(segment: &str) -> Result<JoseHeader> {
    crate::jws::compact::ensure_token_size(segment)?;
    let bytes = base64url::decode(segment)?;
    serde_json::from_slice(&bytes).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(secret: &[u8]) -> SoftwareKey {
        SoftwareKey::from_symmetric_bytes(kryptering::KeyAlgorithm::Hmac, secret).unwrap()
    }

    fn hmac_signer_with_hash(secret: &[u8], hash: HashAlgorithm) -> SoftwareSigner {
        SoftwareSigner::new(SignatureAlgorithm::Hmac(hash), hmac_key(secret)).unwrap()
    }

    fn hmac_signer(secret: &[u8]) -> SoftwareSigner {
        hmac_signer_with_hash(secret, HashAlgorithm::Sha256)
    }

    fn hmac_verifier_with_hash(secret: &[u8], hash: HashAlgorithm) -> SoftwareVerifier {
        SoftwareVerifier::new(SignatureAlgorithm::Hmac(hash), hmac_key(secret)).unwrap()
    }

    fn hmac_verifier(secret: &[u8]) -> SoftwareVerifier {
        hmac_verifier_with_hash(secret, HashAlgorithm::Sha256)
    }

    fn b64_false_header_for_alg(alg: &str) -> JoseHeader {
        let mut header = JoseHeader::new(alg);
        header.crit = Some(vec!["b64".to_string()]);
        header
            .extra
            .insert("b64".to_string(), serde_json::json!(false));
        header
    }

    fn b64_false_header() -> JoseHeader {
        b64_false_header_for_alg("HS256")
    }

    fn b64_false_options() -> SignOptions {
        SignOptions {
            b64: false,
            understood_crit: Vec::new(),
            allow_key_reference_headers: false,
        }
    }

    const KEY_A: &[u8] = b"my-secret-key-at-least-32-bytes!";
    const KEY_B: &[u8] = b"another-key-that-is-32-bytes-xx!";
    const KEY_C: &[u8] = b"another-key-that-is-at-least-48-bytes-for-hs384!";
    const WRONG_KEY: &[u8] = b"wrong-key-that-is-also-32-bytes!";

    // -----------------------------------------------------------------------
    // Flattened JWS tests
    // -----------------------------------------------------------------------

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

        let jws = sign_flattened(&hmac_signer(KEY_A), payload, &header).unwrap();
        let recovered = verify_flattened(&hmac_verifier(KEY_A), &jws).unwrap();
        assert_eq!(recovered, payload);
    }

    #[test]
    fn flattened_serializes_to_valid_json() {
        let header = JoseHeader::new("HS256");
        let payload = b"json check";

        let jws = sign_flattened(&hmac_signer(KEY_A), payload, &header).unwrap();
        let json_str = serde_json::to_string(&jws).unwrap();

        let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert!(v.get("payload").is_some());
        assert!(v.get("protected").is_some());
        assert!(v.get("signature").is_some());
        assert!(v.get("signatures").is_none());
    }

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

        let jws = sign_flattened(&hmac_signer(KEY_A), payload, &header).unwrap();
        let result = verify_flattened(&hmac_verifier(WRONG_KEY), &jws);
        assert!(result.is_err());
    }

    #[test]
    fn flattened_bad_embedded_payload_is_not_decoded_before_verify() {
        let header = JoseHeader::new("HS256");
        let protected = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let payload = "not valid base64url!".to_string();
        let sig = base64url::encode(b"bad-signature");
        let jws = FlattenedJws {
            payload: Some(payload),
            protected,
            header: None,
            signature: sig,
        };

        let err = verify_flattened(&hmac_verifier(KEY_A), &jws)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("signature verification failed"),
            "unexpected: {err}"
        );
    }

    /// Detached flattened: payload member omitted, supplied at verify time.
    #[test]
    fn flattened_detached_roundtrip() {
        let header = JoseHeader::new("HS256");
        let payload = b"detached payload bytes";

        let jws = sign_flattened_detached(&hmac_signer(KEY_A), payload, &header).unwrap();
        assert!(jws.payload.is_none(), "detached JWS must omit payload");

        // Serialized JSON must not contain a payload member.
        let json_str = serde_json::to_string(&jws).unwrap();
        let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert!(v.get("payload").is_none(), "payload leaked: {json_str}");

        let recovered = verify_flattened_detached(&hmac_verifier(KEY_A), &jws, payload).unwrap();
        assert_eq!(recovered, payload);

        // Wrong detached payload must fail.
        assert!(verify_flattened_detached(&hmac_verifier(KEY_A), &jws, b"wrong").is_err());
    }

    /// A detached JWS verified without supplying the payload is an error.
    #[test]
    fn flattened_detached_requires_payload() {
        let header = JoseHeader::new("HS256");
        let jws = sign_flattened_detached(&hmac_signer(KEY_A), b"p", &header).unwrap();
        let err = verify_flattened(&hmac_verifier(KEY_A), &jws)
            .unwrap_err()
            .to_string();
        assert!(err.contains("no detached payload"), "unexpected: {err}");
    }

    /// Flattened sign with an unprotected header member round-trips and the
    /// member is carried in the JSON but not part of the signing input.
    #[test]
    fn flattened_unprotected_header_is_carried() {
        let header = JoseHeader::new("HS256");
        let unprotected = serde_json::json!({"kid": "unprotected-kid"});
        let jws = sign_flattened_opts(
            &hmac_signer(KEY_A),
            b"p",
            &header,
            Some(unprotected.clone()),
            &SignOptions::new(),
        )
        .unwrap();
        assert_eq!(jws.header.as_ref(), Some(&unprotected));
        // Still verifies (unprotected header is not signed).
        assert!(verify_flattened(&hmac_verifier(KEY_A), &jws).is_ok());
    }

    #[test]
    fn flattened_attached_b64_false_non_utf8_payload_is_rejected_before_signing() {
        let header = b64_false_header();
        let opts = b64_false_options();
        let err = sign_flattened_opts(&PanicSigner, &[0xff], &header, None, &opts)
            .unwrap_err()
            .to_string();
        assert!(err.contains("valid UTF-8"), "unexpected: {err}");
    }

    // -----------------------------------------------------------------------
    // General JWS tests
    // -----------------------------------------------------------------------

    #[test]
    fn general_two_signatures_verify_with_either_key() {
        let header_a = JoseHeader::new("HS256");
        let header_b = JoseHeader::new("HS256");
        let payload = b"multi-sig payload";

        let signer_a = hmac_signer(KEY_A);
        let signer_b = hmac_signer(KEY_B);

        let signers: Vec<(&dyn kryptering::Signer, &JoseHeader)> =
            vec![(&signer_a, &header_a), (&signer_b, &header_b)];

        let jws = sign_general(&signers, payload).unwrap();
        assert_eq!(jws.signatures.len(), 2);

        let recovered_a = verify_general(&hmac_verifier(KEY_A), &jws).unwrap();
        assert_eq!(recovered_a, payload);

        let recovered_b = verify_general(&hmac_verifier(KEY_B), &jws).unwrap();
        assert_eq!(recovered_b, payload);
    }

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

        let signer_a = hmac_signer(KEY_A);
        let signers: Vec<(&dyn kryptering::Signer, &JoseHeader)> = vec![(&signer_a, &header)];

        let jws = sign_general(&signers, payload).unwrap();
        let result = verify_general(&hmac_verifier(WRONG_KEY), &jws);
        assert!(result.is_err());
    }

    #[test]
    fn general_serializes_to_valid_json() {
        let header = JoseHeader::new("HS256");
        let payload = b"json check general";

        let signer = hmac_signer(KEY_A);
        let signers: Vec<(&dyn kryptering::Signer, &JoseHeader)> = vec![(&signer, &header)];

        let jws = sign_general(&signers, payload).unwrap();
        let json_str = serde_json::to_string(&jws).unwrap();

        let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert!(v.get("payload").is_some());
        assert!(v.get("signatures").is_some());
        let sigs = v["signatures"].as_array().unwrap();
        assert_eq!(sigs.len(), 1);
        assert!(sigs[0].get("protected").is_some());
        assert!(sigs[0].get("signature").is_some());
    }

    /// Per-signature results: two signers, verifier holds only KEY_A. The
    /// first (KEY_A) entry reports verified, the second (KEY_B) does not.
    #[test]
    fn general_per_signature_results() {
        let header_a = JoseHeader::new("HS256");
        let header_b = JoseHeader::new("HS256");
        let payload = b"multi-sig results";
        let signer_a = hmac_signer(KEY_A);
        let signer_b = hmac_signer(KEY_B);
        let signers: Vec<(&dyn kryptering::Signer, &JoseHeader)> =
            vec![(&signer_a, &header_a), (&signer_b, &header_b)];
        let jws = sign_general(&signers, payload).unwrap();

        let (results, recovered) =
            verify_general_all(&hmac_verifier(KEY_A), &jws, None, &VerifyOptions::new()).unwrap();
        assert_eq!(results.len(), 2);
        assert!(results[0].verified, "entry 0 (KEY_A) should verify");
        assert!(!results[1].verified, "entry 1 (KEY_B) should not verify");
        assert!(results[1].error.is_some());
        assert_eq!(recovered.as_deref(), Some(&payload[..]));
    }

    /// `verify_general_all` must NOT return payload bytes when no signature
    /// verifies, so a caller cannot accidentally consume unauthenticated data.
    #[test]
    fn general_all_yields_no_payload_when_nothing_verifies() {
        let header = JoseHeader::new("HS256");
        let signer = hmac_signer(KEY_A);
        let signers: Vec<(&dyn kryptering::Signer, &JoseHeader)> = vec![(&signer, &header)];
        let jws = sign_general(&signers, b"top secret").unwrap();

        // Verify with the wrong key: the single signature fails.
        let (results, payload) =
            verify_general_all(&hmac_verifier(KEY_B), &jws, None, &VerifyOptions::new()).unwrap();
        assert!(!results[0].verified);
        assert!(
            payload.is_none(),
            "no payload may be returned when nothing verified"
        );
    }

    #[test]
    fn general_bad_embedded_payload_is_not_decoded_without_verified_signature() {
        let header = JoseHeader::new("HS256");
        let protected = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let jws = GeneralJws {
            payload: Some("not valid base64url!".to_string()),
            signatures: vec![JwsSignature {
                protected,
                header: None,
                signature: base64url::encode(b"bad-signature"),
            }],
        };

        let (results, payload) =
            verify_general_all(&hmac_verifier(KEY_A), &jws, None, &VerifyOptions::new()).unwrap();
        assert_eq!(results.len(), 1);
        assert!(!results[0].verified);
        assert!(payload.is_none());
        assert_eq!(
            results[0].error.as_deref(),
            Some("signature verification failed")
        );
    }

    /// Per-signature unprotected header is reported back in the results.
    #[test]
    fn general_unprotected_header_reported() {
        let header = JoseHeader::new("HS256");
        let signer = hmac_signer(KEY_A);
        let etsi = serde_json::json!({"etsiU": ["sig-timestamp"]});
        let entry = GeneralSigner {
            signer: &signer,
            protected: &header,
            unprotected: Some(etsi.clone()),
            options: SignOptions::new(),
        };
        let jws = sign_general_full(std::slice::from_ref(&entry), b"p", true).unwrap();
        assert_eq!(jws.signatures[0].header.as_ref(), Some(&etsi));

        let (results, _) =
            verify_general_all(&hmac_verifier(KEY_A), &jws, None, &VerifyOptions::new()).unwrap();
        assert_eq!(results[0].unprotected_header.as_ref(), Some(&etsi));
        assert!(results[0].verified);
    }

    /// Detached General JWS: payload omitted, supplied at verify time.
    #[test]
    fn general_detached_roundtrip() {
        let header = JoseHeader::new("HS256");
        let payload = b"detached general payload";
        let signer = hmac_signer(KEY_A);
        let entry = GeneralSigner::new(&signer, &header);
        let jws = sign_general_full(std::slice::from_ref(&entry), payload, false).unwrap();
        assert!(jws.payload.is_none());

        let recovered = verify_general_opts(
            &hmac_verifier(KEY_A),
            &jws,
            Some(payload),
            &VerifyOptions::new(),
        )
        .unwrap();
        assert_eq!(recovered, payload);
    }

    #[test]
    fn general_attached_b64_false_non_utf8_payload_is_rejected_before_signing() {
        let header = b64_false_header();
        let opts = b64_false_options();
        let entry = GeneralSigner {
            signer: &PanicSigner,
            protected: &header,
            unprotected: None,
            options: opts,
        };
        let err = sign_general_full(std::slice::from_ref(&entry), &[0xff], true)
            .unwrap_err()
            .to_string();
        assert!(err.contains("valid UTF-8"), "unexpected: {err}");
    }

    /// J-01 regression: Flattened verify rejects alg-header mismatch.
    #[test]
    fn flattened_alg_header_mismatch_rejected() {
        use kryptering::Signer;
        let mut header = JoseHeader::new("RS256");
        header.kid = Some("attacker".into());
        let protected = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let payload = base64url::encode(b"p");
        let signing_input = format!("{protected}.{payload}");
        let sig = hmac_signer(KEY_A).sign(signing_input.as_bytes()).unwrap();
        let jws = FlattenedJws {
            payload: Some(payload),
            protected,
            header: None,
            signature: base64url::encode(&sig),
        };
        let result = verify_flattened(&hmac_verifier(KEY_A), &jws);
        assert!(result.is_err());
    }

    #[test]
    fn inbound_protected_and_unprotected_names_must_be_disjoint() {
        let flattened = FlattenedJws {
            payload: Some(base64url::encode(b"p")),
            // `kid: null` is present in the original protected object even though a typed
            // JoseHeader would turn it into `None` and omit it if serialized again.
            protected: base64url::encode(br#"{"alg":"HS256","kid":null}"#),
            header: Some(serde_json::json!({"kid": "attacker"})),
            signature: base64url::encode(b"not-reached"),
        };
        let err = verify_flattened(&hmac_verifier(KEY_A), &flattened)
            .unwrap_err()
            .to_string();
        assert!(err.contains("kid") && err.contains("also appears"), "{err}");

        let general = GeneralJws {
            payload: flattened.payload.clone(),
            signatures: vec![JwsSignature {
                protected: flattened.protected,
                header: flattened.header,
                signature: flattened.signature,
            }],
        };
        let err = verify_general(&hmac_verifier(KEY_A), &general)
            .unwrap_err()
            .to_string();
        assert!(err.contains("kid") && err.contains("also appears"), "{err}");
    }

    /// J-03 regression: Flattened verify rejects alg=none.
    #[test]
    fn flattened_alg_none_rejected() {
        let header = JoseHeader::new("none");
        let protected = base64url::encode(&serde_json::to_vec(&header).unwrap());
        let payload = base64url::encode(b"p");
        let jws = FlattenedJws {
            payload: Some(payload),
            protected,
            header: None,
            signature: String::new(),
        };
        let result = verify_flattened(&hmac_verifier(KEY_A), &jws);
        assert!(result.is_err());
    }

    /// J-02 regression: General verify with only mismatched-alg entries fails.
    #[test]
    fn general_all_mismatched_alg_fails() {
        let payload_b64 = base64url::encode(b"p");
        let mut rs256_header = JoseHeader::new("RS256");
        rs256_header.kid = Some("attacker".into());
        let protected = base64url::encode(&serde_json::to_vec(&rs256_header).unwrap());
        let signing_input = format!("{protected}.{payload_b64}");
        use kryptering::Signer;
        let sig = hmac_signer(KEY_A).sign(signing_input.as_bytes()).unwrap();
        let jws = GeneralJws {
            payload: Some(payload_b64),
            signatures: vec![JwsSignature {
                protected,
                header: None,
                signature: base64url::encode(&sig),
            }],
        };
        let result = verify_general(&hmac_verifier(KEY_A), &jws);
        assert!(result.is_err());
    }

    #[test]
    fn general_roundtrip_through_json() {
        let header = JoseHeader::new("HS256");
        let payload = b"roundtrip via json";

        let signer = hmac_signer(KEY_A);
        let signers: Vec<(&dyn kryptering::Signer, &JoseHeader)> = vec![(&signer, &header)];

        let jws = sign_general(&signers, payload).unwrap();
        let json_str = serde_json::to_string(&jws).unwrap();
        let deserialized: GeneralJws = serde_json::from_str(&json_str).unwrap();

        let recovered = verify_general(&hmac_verifier(KEY_A), &deserialized).unwrap();
        assert_eq!(recovered, payload);
    }

    /// MAX_TOKEN_BYTES guard on the JSON verify path: an oversized protected
    /// header (or payload member) is refused before any crypto.
    #[test]
    fn flattened_oversize_payload_rejected() {
        let header = JoseHeader::new("HS256");
        let jws = FlattenedJws {
            payload: Some("a".repeat(crate::MAX_TOKEN_BYTES + 1)),
            protected: base64url::encode(&serde_json::to_vec(&header).unwrap()),
            header: None,
            signature: base64url::encode(b"x"),
        };
        let err = verify_flattened(&hmac_verifier(KEY_A), &jws)
            .unwrap_err()
            .to_string();
        assert!(err.contains("MAX_TOKEN_BYTES"), "unexpected: {err}");
    }

    #[test]
    fn flattened_oversize_signature_rejected() {
        let header = JoseHeader::new("HS256");
        let jws = FlattenedJws {
            payload: Some(base64url::encode(b"p")),
            protected: base64url::encode(&serde_json::to_vec(&header).unwrap()),
            header: None,
            signature: "a".repeat(crate::MAX_TOKEN_BYTES + 1),
        };
        let err = verify_flattened(&hmac_verifier(KEY_A), &jws)
            .unwrap_err()
            .to_string();
        assert!(err.contains("MAX_TOKEN_BYTES"), "unexpected: {err}");
    }

    #[test]
    fn general_oversize_signature_rejected() {
        let header = JoseHeader::new("HS256");
        let jws = GeneralJws {
            payload: Some(base64url::encode(b"p")),
            signatures: vec![JwsSignature {
                protected: base64url::encode(&serde_json::to_vec(&header).unwrap()),
                header: None,
                signature: "a".repeat(crate::MAX_TOKEN_BYTES + 1),
            }],
        };
        let err = verify_general(&hmac_verifier(KEY_A), &jws)
            .unwrap_err()
            .to_string();
        assert!(err.contains("MAX_TOKEN_BYTES"), "unexpected: {err}");
    }

    #[test]
    fn general_sign_rejects_mixed_b64_entries() {
        let payload = b"shared-payload";
        let signer = hmac_signer(KEY_A);

        let header_b64_true = JoseHeader::new("HS256");
        let entry_b64_true = GeneralSigner::new(&signer, &header_b64_true);

        let mut header_b64_false = JoseHeader::new("HS256");
        header_b64_false.crit = Some(vec!["b64".to_string()]);
        header_b64_false
            .extra
            .insert("b64".to_string(), serde_json::json!(false));
        let entry_b64_false = GeneralSigner {
            signer: &signer,
            protected: &header_b64_false,
            unprotected: None,
            options: SignOptions {
                b64: false,
                understood_crit: Vec::new(),
                allow_key_reference_headers: false,
            },
        };

        let jws = sign_general_full(&[entry_b64_true, entry_b64_false], payload, true).unwrap_err();
        assert!(
            jws.to_string().contains("agree on the b64 setting"),
            "unexpected: {jws}"
        );
    }

    #[test]
    fn general_sign_rejects_too_many_signers() {
        let signer = hmac_signer(KEY_A);
        let header = JoseHeader::new("HS256");
        let entries: Vec<_> = (0..=MAX_GENERAL_SIGNATURES)
            .map(|_| GeneralSigner::new(&signer, &header))
            .collect();

        let err = sign_general_full(&entries, b"p", true)
            .unwrap_err()
            .to_string();
        assert!(err.contains("signature count"), "unexpected: {err}");
    }

    #[test]
    fn general_verify_rejects_mixed_b64_entries() {
        let payload = b"shared-payload";
        let signer = hmac_signer(KEY_A);

        let header_b64_true = JoseHeader::new("HS256");
        let b64_true = sign_flattened_detached_opts(
            &signer,
            payload,
            &header_b64_true,
            None,
            &SignOptions::new(),
        )
        .unwrap();

        let mut header_b64_false = JoseHeader::new("HS256");
        header_b64_false.crit = Some(vec!["b64".to_string()]);
        header_b64_false
            .extra
            .insert("b64".to_string(), serde_json::json!(false));
        let b64_false = sign_flattened_detached_opts(
            &signer,
            payload,
            &header_b64_false,
            None,
            &SignOptions {
                b64: false,
                understood_crit: Vec::new(),
                allow_key_reference_headers: false,
            },
        )
        .unwrap();

        let jws = GeneralJws {
            payload: Some(base64url::encode(payload)),
            signatures: vec![
                JwsSignature {
                    protected: b64_true.protected,
                    header: None,
                    signature: b64_true.signature,
                },
                JwsSignature {
                    protected: b64_false.protected,
                    header: None,
                    signature: b64_false.signature,
                },
            ],
        };

        let err = verify_general(&hmac_verifier(KEY_A), &jws)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("agree on the b64 setting"),
            "unexpected: {err}"
        );
    }

    #[test]
    fn general_verify_rejects_mixed_b64_across_algorithms() {
        let payload = b"shared-payload";
        let hs256_signer = hmac_signer(KEY_A);
        let hs384_signer = hmac_signer_with_hash(KEY_C, HashAlgorithm::Sha384);

        let b64_true = sign_flattened_detached_opts(
            &hs256_signer,
            payload,
            &JoseHeader::new("HS256"),
            None,
            &SignOptions::new(),
        )
        .unwrap();

        let b64_false = sign_flattened_detached_opts(
            &hs384_signer,
            payload,
            &b64_false_header_for_alg("HS384"),
            None,
            &SignOptions {
                b64: false,
                understood_crit: Vec::new(),
                allow_key_reference_headers: false,
            },
        )
        .unwrap();

        let jws = GeneralJws {
            payload: Some(base64url::encode(payload)),
            signatures: vec![
                JwsSignature {
                    protected: b64_true.protected,
                    header: None,
                    signature: b64_true.signature,
                },
                JwsSignature {
                    protected: b64_false.protected,
                    header: None,
                    signature: b64_false.signature,
                },
            ],
        };

        let err = verify_general(&hmac_verifier(KEY_A), &jws)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("agree on the b64 setting"),
            "unexpected: {err}"
        );
    }

    #[test]
    fn general_verify_rejects_too_many_signatures() {
        let payload = b"shared-payload";
        let signer = hmac_signer(KEY_A);
        let flattened =
            sign_flattened_detached(&signer, payload, &JoseHeader::new("HS256")).unwrap();
        let signature = JwsSignature {
            protected: flattened.protected,
            header: None,
            signature: flattened.signature,
        };
        let jws = GeneralJws {
            payload: Some(base64url::encode(payload)),
            signatures: vec![signature; MAX_GENERAL_SIGNATURES + 1],
        };

        let err = verify_general(&hmac_verifier(KEY_A), &jws)
            .unwrap_err()
            .to_string();
        assert!(err.contains("signature count"), "unexpected: {err}");
    }
}