polyjose 0.1.1

Pure-Rust JOSE: JWA, JWK, JWS, JWE and JWT per the RFCs, with no OpenSSL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
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
//! JWS JSON Serialization, flattened and general (RFC 7515 §7.2), with
//! detached content (RFC 7515 Appendix F), the unencoded payload option
//! (RFC 7797 §5.3) and the multiple-signature policy of ADR 0026 §3.
//!
//! The public functions call their `*_with` twins with the real
//! [`FAMILIES`]; tests call the twins with a fake table (see `jws/alg.rs`,
//! "The test seam").
//!
//! # Verification, step by step (ADR 0048, ADR 0026 §3)
//!
//! The steps are ADR 0048's (see the [module table](crate::jws)).
//! [`verify_json`] owns steps 1–4; steps 5 and 6 are the shared chain of
//! `process.rs`. Each step runs over **every**
//! signature before the next step starts, so a JWS that is wrong in
//! several places fails identically whatever the order of its signatures:
//!
//! 1. the input length → `InvalidFormat`; JSON syntax and duplicate
//!    members anywhere in the document → `InvalidJson`; the RFC 7515
//!    §7.2.1/§7.2.2 shape and, once known, the signature count
//!    → `InvalidFormat`;
//! 2. and 3., in this order, each over every signature:
//!    - base64url of each `protected` and `signature` (RFC 7515 §5.2
//!      steps 2, 7) → `InvalidBase64`;
//!    - each protected header is a JSON object (RFC 7515 §5.2 step 3;
//!      duplicates included, ADR 0041 §1) → `InvalidJson`;
//!    - every registered parameter of the protected **and** the
//!      unprotected header has its type, and `crit` its syntax
//!      (`Header::from_object`, RFC 7515 §4.1.11; ADR 0049 §3 for the
//!      unprotected one) → `InvalidHeader`;
//! 4. the payload, base64url-decoded unless the protected headers' `b64`
//!    is `false` (RFC 7515 §5.2 step 6, RFC 7797 §3) → `InvalidBase64`.
//!    It waits until here because only the headers say whether it is
//!    encoded, and runs before the structure rules, as in `compact.rs`
//!    (ADR 0048). If the protected headers disagree on `b64` there is no
//!    single encoding, so this is skipped and step 5's disagreement check
//!    decides;
//! 5. each signature's header structure (`JoseHeader::new`, RFC 7515
//!    §5.2 step 4, §4.1.11), then `b64` agreement across signatures
//!    (`common_b64`, RFC 7797 §3) → `InvalidHeader`;
//! 6. per signature, in array order, until one verifies
//!    (`verify_signature`: ADR 0026 §2 steps 5–9, RFC 7515 §5.2 step 8);
//!    if none does, the furthest-progressed error (`furthest`,
//!    ADR 0026 §3).

use zeroize::Zeroizing;

use crate::error::{Error, Result};
use crate::header::Header;
use crate::json::{self, Limits, Object, Value};
use crate::jwk::Jwk;
use crate::util::{b64url_decode, b64url_encode};

use super::alg::{FAMILIES, Families};
use super::process::{
    JoseHeader, common_b64, furthest, prepare_sign, signing_input_from_part, verify_signature,
};
use super::{ProtectedHeader, SignOptions, Signer, Verified, VerifyOptions};

/// The members of one signature object (RFC 7515 §7.2.1), which the
/// flattened syntax puts at the top level instead of `signatures`
/// (RFC 7515 §7.2.2).
const SIGNATURE_MEMBERS: [&str; 3] = ["protected", "header", "signature"];

/// Signs `payload` in the flattened JWS JSON Serialization
/// (RFC 7515 §7.2.2): one signature, with its `protected`, `header` and
/// `signature` members at the top level.
///
/// The JOSE Header is the union of the signer's protected and unprotected
/// headers, which must be disjoint (RFC 7515 §5.2 step 4). With no
/// protected header the signing input starts with an empty string
/// (RFC 7515 §5.1). With [`SignOptions::detached`] the `payload` member is
/// omitted (RFC 7515 Appendix F); with `"b64": false` it is the payload
/// itself as a JSON string (RFC 7797 §5.3).
///
/// The output is compact, deterministic JSON.
///
/// # Errors
///
/// As [`sign_general`] with one signer.
pub fn sign_flattened(signer: &Signer<'_>, payload: &[u8], opts: &SignOptions) -> Result<String> {
    sign_flattened_with(&FAMILIES, signer, payload, opts)
}

/// [`sign_flattened`] with the signature primitives taken from `families`.
pub(crate) fn sign_flattened_with(
    families: &Families,
    signer: &Signer<'_>,
    payload: &[u8],
    opts: &SignOptions,
) -> Result<String> {
    let (payload, mut signed) = sign_all(families, core::slice::from_ref(signer), payload, opts)?;
    let mut jws = Object::new();
    if let Some(payload) = payload {
        jws.insert("payload", payload);
    }
    // One signer, one entry.
    if let Some(entry) = signed.pop() {
        entry.write_to(&mut jws);
    }
    Ok(jws.to_json())
}

/// Signs `payload` in the general JWS JSON Serialization
/// (RFC 7515 §7.2.1): one entry in `signatures` per signer, in order.
///
/// Each signer's JOSE Header is the union of its protected and unprotected
/// headers (RFC 7515 §5.2 step 4). Every signer must give the same `b64`
/// value (RFC 7797 §3). Detached content and `b64: false` behave as in
/// [`sign_flattened`].
///
/// # Errors
///
/// For each signer, in order, the first failing check decides:
///
/// - [`Error::InvalidFormat`]: `signers` is empty (RFC 7515 §7.2.1).
/// - [`Error::InvalidHeader`]: the two headers share a name, `alg` is
///   missing, `crit` is malformed or not in the protected header, `b64` is
///   not in the protected header or not listed in `crit`, or the signers
///   disagree on `b64` (RFC 7515 §4.1.11, §5.2 step 4; RFC 7797 §3, §6).
/// - [`Error::UnknownCritical`], [`Error::UnsupportedAlgorithm`] (also for
///   RS*/PS*, ADR 0021), [`Error::AlgorithmNotAllowed`] (`none`),
///   [`Error::KeyAlgorithmMismatch`] or [`Error::InvalidKey`], as for
///   [`sign_compact`](super::sign_compact).
/// - [`Error::InvalidFormat`]: `b64: false` with a payload that is not
///   UTF-8, so it cannot be a JSON string (RFC 7797 §5.3).
/// - [`Error::InvalidKey`] / [`Error::RandomnessUnavailable`] from the
///   algorithm itself.
pub fn sign_general(signers: &[Signer<'_>], payload: &[u8], opts: &SignOptions) -> Result<String> {
    sign_general_with(&FAMILIES, signers, payload, opts)
}

/// [`sign_general`] with the signature primitives taken from `families`.
pub(crate) fn sign_general_with(
    families: &Families,
    signers: &[Signer<'_>],
    payload: &[u8],
    opts: &SignOptions,
) -> Result<String> {
    let (payload, signed) = sign_all(families, signers, payload, opts)?;
    let mut jws = Object::new();
    if let Some(payload) = payload {
        jws.insert("payload", payload);
    }
    let signatures: Vec<Value> = signed
        .into_iter()
        .map(|entry| {
            let mut object = Object::new();
            entry.write_to(&mut object);
            Value::from(object)
        })
        .collect();
    jws.insert("signatures", signatures);
    Ok(jws.to_json())
}

/// One computed signature's members (RFC 7515 §7.2.1).
struct SignedEntry<'s> {
    /// `protected`: the encoding as made or given (RFC 7515 §5.1 step 3).
    protected: Option<&'s str>,
    /// `header`, absent when the JWS Unprotected Header is empty
    /// (RFC 7515 §7.2.1: "MUST be absent").
    header: Option<Object>,
    /// `signature`: BASE64URL(JWS Signature) (RFC 7515 §5.1 step 7).
    signature: String,
}

impl SignedEntry<'_> {
    /// Appends the members in RFC 7515 §7.2.1 order: `protected`,
    /// `header`, `signature`.
    fn write_to(self, object: &mut Object) {
        if let Some(protected) = self.protected {
            object.insert("protected", protected);
        }
        if let Some(header) = self.header {
            object.insert("header", header);
        }
        object.insert("signature", self.signature);
    }
}

/// Computes every signature of a JSON JWS (RFC 7515 §5.1), returning the
/// `payload` member (absent when detached) and one entry per signer.
///
/// Like verification, each step runs over every signer before the next:
/// the header structure of every signer (ADR 0026 §2 step 4, RFC 7515
/// §5.2 step 4) and `b64` agreement (RFC 7797 §3); then steps 5–8 per
/// signer, in order (`prepare_sign`); then the payload rule of RFC 7797
/// §5.3; then the signatures themselves.
fn sign_all<'s>(
    families: &Families,
    signers: &'s [Signer<'_>],
    payload: &[u8],
    opts: &SignOptions,
) -> Result<(Option<Value>, Vec<SignedEntry<'s>>)> {
    if signers.is_empty() {
        return Err(Error::InvalidFormat(
            "a general JWS needs at least one signer",
        ));
    }
    // Step 4 for every signer, then one `b64` for the whole JWS.
    let mut headers = Vec::with_capacity(signers.len());
    let mut unprotected_members = Vec::with_capacity(signers.len());
    for signer in signers {
        let members = signer
            .unprotected
            .as_ref()
            .map(Header::to_object)
            .transpose()?
            .filter(|members| !members.is_empty());
        let protected = signer.protected.as_ref().map(|p| p.header().clone());
        headers.push(JoseHeader::new(protected, signer.unprotected.clone())?);
        unprotected_members.push(members);
    }
    let b64 = common_b64(&headers)?;
    // Steps 5-8, per signer.
    let ready = headers
        .iter()
        .zip(signers)
        .map(|(header, signer)| prepare_sign(header, signer.key))
        .collect::<Result<Vec<_>>>()?;
    // RFC 7797 §5.3: with `b64: false` the payload member is the payload
    // itself, a JSON string, so it must be UTF-8. Detached content is not
    // carried (RFC 7515 Appendix F), so any octets will do.
    let unencoded = if !opts.detached && !b64 {
        Some(core::str::from_utf8(payload).map_err(|_| {
            Error::InvalidFormat("a b64:false payload must be UTF-8 in the JSON Serialization")
        })?)
    } else {
        None
    };
    // The payload as every signing input carries it (RFC 7515 §5.1 step 5,
    // RFC 7797 §3): BASE64URL(JWS Payload), encoded once for all signers
    // and wiped on drop (ADR 0049 §4), or the octets themselves.
    let encoded = b64.then(|| Zeroizing::new(b64url_encode(payload)));
    let payload_part = encoded.as_ref().map_or(payload, |e| e.as_bytes());
    // RFC 7515 §5.1 steps 5-7, signer by signer.
    let mut entries = Vec::with_capacity(signers.len());
    for ((signer, ready), header) in signers.iter().zip(&ready).zip(unprotected_members) {
        let protected = signer.protected.as_ref().map(ProtectedHeader::encoded);
        let input = signing_input_from_part(protected.unwrap_or(""), payload_part);
        let signature = b64url_encode(&ready.sign(families, &input)?);
        entries.push(SignedEntry {
            protected,
            header,
            signature,
        });
    }
    // The `payload` member (RFC 7515 §7.2.1), reusing the encoding; a
    // `Value` string is wiped on drop too.
    let payload_member = match (opts.detached, encoded, unencoded) {
        (true, _, _) => None,
        (false, Some(encoded), _) => Some(Value::String(encoded)),
        // `b64: false` and attached: `unencoded` was set, and checked, above.
        (false, None, text) => Some(Value::from(text.unwrap_or_default())),
    };
    Ok((payload_member, entries))
}

/// Verifies a JWS in the JSON Serialization, flattened (RFC 7515 §7.2.2)
/// or general (RFC 7515 §7.2.1), with `key`, accepting only the
/// algorithms `opts` allows.
///
/// RFC 7515 §5.2 leaves the multiple-signature policy to the application;
/// polyjose's is ADR 0026 §3:
///
/// - Steps 1–5 of ADR 0048 (shape and limits, base64url, header
///   decoding, payload, header structure) run over **every** signature
///   first, and all signatures must agree on `b64`. Any failure rejects
///   the whole JWS.
/// - Step 6 (ADR 0026 §2 steps 5–9) then runs per signature, in array
///   order, and stops at the first that verifies.
///   [`Verified::signature_index`] says which.
/// - If none verifies, the error is that of the signature that got
///   furthest: [`Error::InvalidSignature`] > [`Error::InvalidKey`] >
///   [`Error::KeyAlgorithmMismatch`] > [`Error::AlgorithmNotAllowed`] >
///   [`Error::UnsupportedAlgorithm`] > [`Error::UnknownCritical`], ties
///   to the lowest index.
///
/// With [`VerifyOptions::detached_payload`] the JWS must have no `payload`
/// member (RFC 7515 Appendix F); without it, `payload` is required
/// (RFC 7515 §7.2.1). Unknown top-level members are ignored
/// (RFC 7515 §7.2.1).
///
/// # Errors
///
/// - [`Error::InvalidFormat`]: over [`VerifyOptions::max_input_len`] or
///   [`VerifyOptions::max_signatures`]; not the §7.2 shape (`signature`
///   missing or not a string, `signatures` empty or mixed with top-level
///   signature members, `protected` the empty string, `header` not an
///   object); `payload` present or absent against the detached mode.
/// - [`Error::InvalidJson`]: JSON syntax, or a duplicate member anywhere,
///   including inside a header (ADR 0041 §1).
/// - [`Error::InvalidBase64`], [`Error::InvalidHeader`], in the order of
///   ADR 0048 (see the [module docs](crate::jws)), then the per-signature
///   errors ranked as above (ADR 0026 §3).
pub fn verify_json(jws: &str, key: &Jwk, opts: &VerifyOptions<'_>) -> Result<Verified> {
    verify_json_with(&FAMILIES, jws, key, opts)
}

/// [`verify_json`] with the signature primitives taken from `families`.
pub(crate) fn verify_json_with(
    families: &Families,
    jws: &str,
    key: &Jwk,
    opts: &VerifyOptions<'_>,
) -> Result<Verified> {
    // Step 1 (ADR 0048).
    let Parsed {
        payload,
        signatures,
    } = parse(jws, opts)?;

    // Steps 2 and 3, base64url (RFC 7515 §5.2 steps 7 and 2), every
    // signature.
    let decoded = signatures
        .iter()
        .map(|raw| {
            let protected = raw
                .protected
                .as_deref()
                .map(|p| b64url_decode(p).map(Zeroizing::new))
                .transpose()?;
            Ok((protected, b64url_decode(&raw.signature)?))
        })
        .collect::<Result<Vec<_>>>()?;

    // Step 3, I-JSON (RFC 7515 §5.2 step 3; duplicates are InvalidJson,
    // ADR 0041 §1), every protected header.
    let protected_objects = decoded
        .iter()
        .map(|(protected, _)| protected.as_ref().map(|p| protected_object(p)).transpose())
        .collect::<Result<Vec<_>>>()?;

    // Step 3, parameter types and `crit` syntax (Header::from_object →
    // InvalidHeader), every header of every signature: the unprotected
    // one too (ADR 0049 §3).
    let mut typed = Vec::with_capacity(signatures.len());
    let mut signed = Vec::with_capacity(signatures.len());
    for ((raw, protected), (_, signature)) in
        signatures.into_iter().zip(protected_objects).zip(decoded)
    {
        let protected = protected.map(Header::from_object).transpose()?;
        let unprotected = raw.header.map(Header::from_object).transpose()?;
        typed.push((protected, unprotected));
        signed.push((raw.protected, signature));
    }

    // Step 4, the payload (RFC 7515 §5.2 step 6): whether it is
    // base64url at all is the protected headers' `b64` (RFC 7797 §3), so it
    // runs now, before the structure rules, as in compact.rs. If the
    // protected headers disagree there is no one encoding to check; the
    // disagreement is reported below instead (InvalidHeader).
    let encodings: Vec<bool> = typed
        .iter()
        .map(|(protected, _)| protected.as_ref().and_then(|h| h.b64) != Some(false))
        .collect();
    let content = match encodings.split_first() {
        Some((&b64, rest)) if rest.iter().all(|&other| other == b64) => {
            Some(Content::new(payload, b64)?)
        }
        _ => None,
    };

    // Step 5, header structure (RFC 7515 §5.2 step 4), every signature,
    // then `b64` agreement across them (RFC 7797 §3, ADR 0026 §3).
    let headers = typed
        .into_iter()
        .map(|(protected, unprotected)| JoseHeader::new(protected, unprotected))
        .collect::<Result<Vec<_>>>()?;
    let b64 = common_b64(&headers)?;
    // `JoseHeader::new` keeps `b64` out of unprotected headers, so each
    // union's `b64` is its protected header's, and `common_b64` passing
    // means `encodings` agreed and the payload was decoded with that same
    // `b64`. Fail closed regardless.
    let Some(content) = content.filter(|c| c.encoded.is_some() == b64) else {
        return Err(Error::InvalidHeader("b64 differs between signatures"));
    };

    // Step 6 (ADR 0026 §2 steps 5-9), per signature in array order, first
    // success wins (ADR 0026 §3).
    let mut errors = Vec::with_capacity(headers.len());
    for (signature_index, (header, (protected_b64, signature))) in
        headers.into_iter().zip(signed).enumerate()
    {
        let input = signing_input_from_part(protected_b64.as_deref().unwrap_or(""), content.part());
        match verify_signature(families, &header, key, opts, &input, &signature) {
            Ok(alg) => {
                let (protected, unprotected) = header.into_parts();
                return Ok(Verified {
                    alg,
                    protected,
                    unprotected,
                    payload: content.into_payload(),
                    signature_index,
                });
            }
            Err(e) => errors.push(e),
        }
    }
    // Step 1 guarantees at least one signature, so `furthest` is `Some`;
    // fail closed regardless.
    Err(furthest(errors).unwrap_or(Error::InvalidSignature))
}

/// A JSON JWS after step 1: its payload and its signature objects.
struct Parsed<'a> {
    payload: Payload<'a>,
    signatures: Vec<RawSignature>,
}

/// Where the JWS Payload comes from.
enum Payload<'a> {
    /// The `payload` member as received: BASE64URL(JWS Payload), or with
    /// `b64: false` the payload itself (RFC 7515 §7.2.1, RFC 7797 §5.3).
    Attached(Zeroizing<String>),
    /// [`VerifyOptions::detached_payload`] (RFC 7515 Appendix F).
    Detached(&'a [u8]),
}

/// The JWS Payload after step 4, with its form in the signing input
/// (RFC 7515 §5.1 step 5, RFC 7797 §3). Everything here may be secret, so
/// it is wiped on drop (ADR 0049 §4).
struct Content<'a> {
    /// The JWS Payload octets.
    octets: Octets<'a>,
    /// BASE64URL(JWS Payload) when `b64` is true: the received `payload`
    /// member, or the detached content encoded once. `None` when `b64` is
    /// false, where the signing input carries the octets themselves.
    encoded: Option<Zeroizing<String>>,
}

/// Where the JWS Payload octets live.
enum Octets<'a> {
    /// Decoded from, or moved out of, the `payload` member.
    Owned(Zeroizing<Vec<u8>>),
    /// [`VerifyOptions::detached_payload`], copied only once verified.
    Detached(&'a [u8]),
}

impl<'a> Content<'a> {
    /// Step 3 for the payload (RFC 7515 §5.2 step 6): base64url-decodes an
    /// attached payload when `b64` is true, else takes its text as the
    /// octets (RFC 7797 §3, §5.3).
    ///
    /// The received text is kept as BASE64URL(JWS Payload) rather than
    /// re-encoded: [`b64url_decode`] accepts only the canonical encoding
    /// (RFC 4648 §3.5), so the two are the same.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidBase64`] if `b64` is true and the `payload` member
    /// is not strict base64url (RFC 7515 §2).
    fn new(payload: Payload<'a>, b64: bool) -> Result<Self> {
        Ok(match payload {
            Payload::Attached(text) if b64 => Self {
                octets: Octets::Owned(Zeroizing::new(b64url_decode(&text)?)),
                encoded: Some(text),
            },
            // The string's buffer becomes the octets, without a copy.
            Payload::Attached(mut text) => Self {
                octets: Octets::Owned(Zeroizing::new(core::mem::take(&mut *text).into_bytes())),
                encoded: None,
            },
            Payload::Detached(octets) => Self {
                octets: Octets::Detached(octets),
                encoded: b64.then(|| Zeroizing::new(b64url_encode(octets))),
            },
        })
    }

    /// The payload as the signing input carries it: BASE64URL(JWS Payload)
    /// or, with `b64: false`, the octets (RFC 7515 §5.1 step 5, RFC 7797 §3).
    fn part(&self) -> &[u8] {
        match &self.encoded {
            Some(encoded) => encoded.as_bytes(),
            None => self.octets(),
        }
    }

    /// The JWS Payload octets.
    fn octets(&self) -> &[u8] {
        match &self.octets {
            Octets::Owned(octets) => octets,
            Octets::Detached(octets) => octets,
        }
    }

    /// The JWS Payload for [`Verified::payload`], copying detached content.
    fn into_payload(self) -> Zeroizing<Vec<u8>> {
        match self.octets {
            Octets::Owned(octets) => octets,
            Octets::Detached(octets) => Zeroizing::new(octets.to_vec()),
        }
    }
}

/// One signature object's members after step 1 (RFC 7515 §7.2.1).
struct RawSignature {
    /// `protected`, still encoded: the signing input uses it verbatim
    /// (RFC 7515 §5.2 step 8). Never the empty string.
    protected: Option<String>,
    /// `header`, the JWS Unprotected Header, still untyped.
    header: Option<Object>,
    /// `signature`, still encoded.
    signature: String,
}

/// Step 1 of ADR 0048 (steps 1 and 2 of ADR 0026 §2): the size limits
/// and the RFC 7515 §7.2 shape. Unknown members are ignored at every level
/// (RFC 7515 §7.2.1).
fn parse<'a>(jws: &str, opts: &VerifyOptions<'a>) -> Result<Parsed<'a>> {
    // The input length, before parsing (ADR 0026 §7). The JSON layer's
    // own input limit follows the caller's, so a larger configured limit
    // holds.
    if jws.len() > opts.max_input_len {
        return Err(Error::InvalidFormat("JWS is longer than max_input_len"));
    }
    let mut limits = Limits::DEFAULT;
    limits.max_input_len = opts.max_input_len;
    // JSON syntax and duplicate members, anywhere in the document
    // (RFC 7515 §5.2 step 4, RFC 7493 §2.3) → InvalidJson.
    let mut top = json::parse_with_limits(jws.as_bytes(), &limits)?
        .into_object()
        .ok_or(Error::InvalidFormat(
            "JWS JSON Serialization must be an object",
        ))?;

    let payload = match (top.remove("payload"), opts.detached_payload) {
        (Some(_), Some(_)) => {
            return Err(Error::InvalidFormat(
                "payload member present with a detached payload",
            ));
        }
        (None, None) => return Err(Error::InvalidFormat("payload member missing")),
        (Some(value), None) => Payload::Attached(
            string(value).ok_or(Error::InvalidFormat("payload must be a string"))?,
        ),
        (None, Some(octets)) => Payload::Detached(octets),
    };

    let signatures = match top.remove("signatures") {
        // General (RFC 7515 §7.2.1).
        Some(signatures) => {
            if SIGNATURE_MEMBERS.iter().any(|name| top.contains(name)) {
                return Err(Error::InvalidFormat(
                    "signatures mixed with top-level signature members",
                ));
            }
            let Value::Array(entries) = signatures else {
                return Err(Error::InvalidFormat("signatures must be an array"));
            };
            if entries.is_empty() {
                return Err(Error::InvalidFormat("signatures must not be empty"));
            }
            // The signature-count limit (ADR 0026 §7), once known.
            if entries.len() > opts.max_signatures {
                return Err(Error::InvalidFormat("more signatures than max_signatures"));
            }
            entries
                .into_iter()
                .map(|entry| {
                    entry
                        .into_object()
                        .ok_or(Error::InvalidFormat("each signature must be an object"))
                        .and_then(raw_signature)
                })
                .collect::<Result<Vec<_>>>()?
        }
        // Flattened (RFC 7515 §7.2.2): the rest of the top level is the
        // one signature object.
        None => vec![raw_signature(top)?],
    };
    Ok(Parsed {
        payload,
        signatures,
    })
}

/// The members of one signature object (RFC 7515 §7.2.1), checked for
/// shape only.
fn raw_signature(mut object: Object) -> Result<RawSignature> {
    // "protected" MUST be absent when the protected header is empty, so
    // the empty string is malformed (ADR 0026 §1).
    let protected = match object.remove("protected") {
        None => None,
        Some(value) => match value.as_str() {
            Some("") => return Err(Error::InvalidFormat("protected must not be empty")),
            Some(encoded) => Some(encoded.to_owned()),
            None => return Err(Error::InvalidFormat("protected must be a string")),
        },
    };
    // "header" is "an unencoded JSON object, rather than as a string".
    let header = object
        .remove("header")
        .map(|value| {
            value
                .into_object()
                .ok_or(Error::InvalidFormat("header must be a JSON object"))
        })
        .transpose()?;
    // "The "signature" member MUST be present".
    let signature = object
        .remove("signature")
        .as_ref()
        .and_then(Value::as_str)
        .map(str::to_owned)
        .ok_or(Error::InvalidFormat(
            "signature must be present and a string",
        ))?;
    Ok(RawSignature {
        protected,
        header,
        signature,
    })
}

/// A JSON string member's value, wiped on drop like the `Value` it came
/// from.
fn string(value: Value) -> Option<Zeroizing<String>> {
    match value {
        Value::String(s) => Some(s),
        _ => None,
    }
}

/// A decoded protected header parsed as an I-JSON object (RFC 7515 §5.2
/// step 3), before its parameters are typed.
fn protected_object(octets: &[u8]) -> Result<Object> {
    json::parse(octets)?
        .into_object()
        .ok_or(Error::InvalidJson("protected header must be a JSON object"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::header::Header;
    use crate::jwa::SigningAlg;
    use crate::jws::ProtectedHeader;
    use crate::jws::alg::fake::{FAKE, REJECTING, fake_signature};
    use crate::jws::alg::test_keys as keys;
    use crate::util::b64url_encode;

    /// RFC 7797 §4's payload `$.02` and its base64url encoding.
    const PAYLOAD: &[u8] = b"$.02";
    const PAYLOAD_B64: &str = "JC4wMg";
    const HS256: &[SigningAlg] = &[SigningAlg::HS256];
    const P_HS256: &str = r#"{"alg":"HS256"}"#;
    /// RFC 7797 §4.2's protected header, `b64: false`.
    const P_B64_FALSE: &str = r#"{"alg":"HS256","b64":false,"crit":["b64"]}"#;

    /// A 64-octet `oct` key: HS256, HS384 and HS512 all accept it. The
    /// fake families ignore it after key binding.
    fn key() -> Jwk {
        keys::oct(64, "")
    }

    fn enc(json: &str) -> String {
        b64url_encode(json.as_bytes())
    }

    /// The base64url fake signature of `protected_b64 '.' payload_part`.
    fn sig(alg: SigningAlg, protected_b64: &str, payload_part: &str) -> String {
        let input = format!("{protected_b64}.{payload_part}");
        b64url_encode(&fake_signature(&alg, input.as_bytes()))
    }

    /// The members of one signature object (no braces), with `signature`
    /// given verbatim.
    fn members_signed(protected: Option<&str>, header: Option<&str>, signature: &str) -> String {
        let mut parts = Vec::new();
        if let Some(p) = protected {
            parts.push(format!(r#""protected":"{}""#, enc(p)));
        }
        if let Some(h) = header {
            parts.push(format!(r#""header":{h}"#));
        }
        parts.push(format!(r#""signature":"{signature}""#));
        parts.join(",")
    }

    /// The members of one signature object (no braces), validly signed
    /// under `alg` over [`PAYLOAD_B64`].
    fn members(protected: Option<&str>, header: Option<&str>, alg: SigningAlg) -> String {
        let p = protected.map(enc).unwrap_or_default();
        members_signed(protected, header, &sig(alg, &p, PAYLOAD_B64))
    }

    fn flattened(members: &str) -> String {
        format!(r#"{{"payload":"{PAYLOAD_B64}",{members}}}"#)
    }

    fn general(entries: &[String]) -> String {
        let entries: Vec<String> = entries.iter().map(|m| format!("{{{m}}}")).collect();
        format!(
            r#"{{"payload":"{PAYLOAD_B64}","signatures":[{}]}}"#,
            entries.join(",")
        )
    }

    fn verify_opts(jws: &str, opts: &VerifyOptions<'_>) -> Result<Verified> {
        verify_json_with(&FAKE, jws, &key(), opts)
    }

    fn verify_allowing(jws: &str, allowed: &[SigningAlg]) -> Result<Verified> {
        verify_opts(jws, &VerifyOptions::new(allowed).unwrap())
    }

    fn verify(jws: &str) -> Result<Verified> {
        verify_allowing(jws, HS256)
    }

    fn code(r: Result<Verified>) -> &'static str {
        r.err().map_or("ok", |e| e.code())
    }

    fn hs256() -> Header {
        Header::from_json(P_HS256.as_bytes()).unwrap()
    }

    fn kid(kid: &str) -> Header {
        let mut h = Header::new();
        h.kid = Some(kid.into());
        h
    }

    // ---- Shape (RFC 7515 §7.2.1, §7.2.2; ADR 0026 §1, §2 steps 1-3) ----

    #[test]
    fn flattened_and_general_verify() {
        let m = members(Some(P_HS256), Some(r#"{"kid":"k1"}"#), SigningAlg::HS256);
        for jws in [flattened(&m), general(std::slice::from_ref(&m))] {
            let v = verify(&jws).unwrap();
            assert_eq!(v.alg, SigningAlg::HS256);
            assert_eq!(*v.payload, PAYLOAD);
            assert_eq!(v.signature_index, 0);
            assert_eq!(v.protected, Some(hs256()));
            assert_eq!(v.unprotected, Some(kid("k1")));
        }
    }

    #[test]
    fn signatures_with_top_level_signature_members_is_invalid_format() {
        // RFC 7515 §7.2.2: the flattened members replace `signatures`;
        // ADR 0026 §1: mixing them is a shape error.
        let entry = members(Some(P_HS256), None, SigningAlg::HS256);
        for extra in [
            r#""signature":"AAAA""#,
            r#""protected":"e30""#,
            r#""header":{"kid":"k"}"#,
        ] {
            let jws =
                format!(r#"{{"payload":"{PAYLOAD_B64}",{extra},"signatures":[{{{entry}}}]}}"#);
            assert_eq!(code(verify(&jws)), "InvalidFormat", "{extra}");
        }
    }

    #[test]
    fn signatures_must_be_a_non_empty_array_of_objects() {
        // RFC 7515 §7.2.1: "an array of JSON objects"; ADR 0026 §1.
        for signatures in ["[]", "{}", r#""x""#, "null", "[1]", r#"[[]]"#] {
            let jws = format!(r#"{{"payload":"{PAYLOAD_B64}","signatures":{signatures}}}"#);
            assert_eq!(code(verify(&jws)), "InvalidFormat", "{signatures}");
        }
    }

    #[test]
    fn signature_missing_or_not_a_string_is_invalid_format() {
        // RFC 7515 §7.2.1: "The "signature" member MUST be present".
        let p = format!(r#""protected":"{}""#, enc(P_HS256));
        let cases = [
            p.clone(),
            format!(r#"{p},"signature":1"#),
            format!(r#"{p},"signature":null"#),
            format!(r#"{p},"signature":["AAAA"]"#),
        ];
        for m in &cases {
            assert_eq!(code(verify(&flattened(m))), "InvalidFormat", "{m}");
            assert_eq!(
                code(verify(&general(std::slice::from_ref(m)))),
                "InvalidFormat",
                "{m}"
            );
        }
        // Neither `signature` nor `signatures`.
        assert_eq!(
            code(verify(&format!(r#"{{"payload":"{PAYLOAD_B64}"}}"#))),
            "InvalidFormat"
        );
    }

    #[test]
    fn empty_or_non_string_protected_is_invalid_format() {
        // RFC 7515 §7.2.1: `protected` MUST be absent when the protected
        // header is empty, so "" is malformed (ADR 0026 §1).
        let header = r#""header":{"alg":"HS256"}"#;
        let signature = sig(SigningAlg::HS256, "", PAYLOAD_B64);
        for protected in [r#""""#, "1", "{}", "null"] {
            let m = format!(r#""protected":{protected},{header},"signature":"{signature}""#);
            assert_eq!(code(verify(&flattened(&m))), "InvalidFormat", "{protected}");
            assert_eq!(
                code(verify(&general(std::slice::from_ref(&m)))),
                "InvalidFormat",
                "{protected}"
            );
        }
    }

    #[test]
    fn header_not_an_object_is_invalid_format() {
        // RFC 7515 §7.2.1: `header` is "an unencoded JSON object".
        for header in [r#""e30""#, "[]", "null", "1", "true"] {
            let m = members_signed(
                Some(P_HS256),
                Some(header),
                &sig(SigningAlg::HS256, &enc(P_HS256), PAYLOAD_B64),
            );
            assert_eq!(code(verify(&flattened(&m))), "InvalidFormat", "{header}");
            assert_eq!(code(verify(&general(&[m]))), "InvalidFormat", "{header}");
        }
    }

    #[test]
    fn duplicate_member_anywhere_is_invalid_json() {
        // RFC 7515 §5.2 step 4 and RFC 7493 §2.3 via the JSON layer;
        // ADR 0041 §1 for headers.
        let good = members(Some(P_HS256), None, SigningAlg::HS256);
        let cases = [
            // Top level.
            format!(r#"{{"payload":"{PAYLOAD_B64}","payload":"{PAYLOAD_B64}",{good}}}"#),
            format!(r#"{{"payload":"{PAYLOAD_B64}","x":1,"x":2,{good}}}"#),
            // A flattened signature member.
            flattened(&format!(r#"{good},"signature":"AAAA""#)),
            // A general signature object.
            general(&[format!(r#"{good},"protected":"e30""#)]),
            // Inside the unprotected header, also nested.
            flattened(&members(
                Some(P_HS256),
                Some(r#"{"kid":"a","kid":"b"}"#),
                SigningAlg::HS256,
            )),
            general(&[members(
                Some(P_HS256),
                Some(r#"{"jwk":{"kty":"oct","kty":"RSA"}}"#),
                SigningAlg::HS256,
            )]),
            // Inside the protected header, even spelled differently.
            flattened(&members(
                Some(r#"{"alg":"HS256","alg":"HS256"}"#),
                None,
                SigningAlg::HS256,
            )),
        ];
        for jws in &cases {
            assert_eq!(code(verify(jws)), "InvalidJson", "{jws}");
        }
    }

    #[test]
    fn unknown_members_are_ignored() {
        // RFC 7515 §7.2.1: members not understood MUST be ignored.
        let m = members(Some(P_HS256), None, SigningAlg::HS256);
        let flat = format!(r#"{{"x":{{"y":[1]}},"payload":"{PAYLOAD_B64}",{m},"z":null}}"#);
        let gen_ =
            format!(r#"{{"x":1,"payload":"{PAYLOAD_B64}","signatures":[{{"x":"y",{m}}}],"z":[]}}"#);
        for jws in [flat, gen_] {
            assert_eq!(*verify(&jws).unwrap().payload, PAYLOAD, "{jws}");
        }
    }

    #[test]
    fn more_than_max_signatures_is_invalid_format() {
        // ADR 0026 §7: default 16, configurable.
        let m = members(Some(P_HS256), None, SigningAlg::HS256);
        let allowed = HS256;
        let three = general(&vec![m.clone(); 3]);
        let opts = VerifyOptions::new(allowed).unwrap();
        assert_eq!(
            code(verify_opts(&three, &opts.max_signatures(2))),
            "InvalidFormat"
        );
        assert_eq!(code(verify_opts(&three, &opts.max_signatures(3))), "ok");
        assert_eq!(code(verify(&general(&vec![m.clone(); 16]))), "ok");
        assert_eq!(code(verify(&general(&vec![m; 17]))), "InvalidFormat");
    }

    #[test]
    fn input_over_max_input_len_is_invalid_format() {
        // ADR 0026 §7, step 1: checked before parsing.
        let jws = flattened(&members(Some(P_HS256), None, SigningAlg::HS256));
        let opts = VerifyOptions::new(HS256).unwrap();
        assert_eq!(
            code(verify_opts(&jws, &opts.max_input_len(jws.len() - 1))),
            "InvalidFormat"
        );
        assert_eq!(
            code(verify_opts(&jws, &opts.max_input_len(jws.len()))),
            "ok"
        );
        // Not JSON at all, but too long: the limit comes first.
        assert_eq!(
            code(verify_opts("{{{{", &opts.max_input_len(3))),
            "InvalidFormat"
        );
        // A limit above the JSON layer's default 1 MiB is honoured.
        let filler = "a".repeat(VerifyOptions::DEFAULT_MAX_INPUT_LEN);
        let big = format!(
            r#"{{"x":"{filler}","payload":"{PAYLOAD_B64}",{}}}"#,
            members(Some(P_HS256), None, SigningAlg::HS256)
        );
        assert_eq!(code(verify(&big)), "InvalidFormat");
        assert_eq!(
            code(verify_opts(&big, &opts.max_input_len(big.len()))),
            "ok"
        );
    }

    #[test]
    fn not_a_json_object_is_invalid_json_or_invalid_format() {
        for (jws, expected) in [
            ("", "InvalidJson"),
            ("{", "InvalidJson"),
            ("eyJhbGciOiJIUzI1NiJ9.JC4wMg.AAAA", "InvalidJson"),
            ("[]", "InvalidFormat"),
            (r#""x""#, "InvalidFormat"),
            ("null", "InvalidFormat"),
        ] {
            assert_eq!(code(verify(jws)), expected, "{jws}");
        }
    }

    #[test]
    fn payload_not_a_string_is_invalid_format() {
        // RFC 7515 §7.2.1: `payload` is BASE64URL(JWS Payload), a string.
        let m = members(Some(P_HS256), None, SigningAlg::HS256);
        for payload in ["1", "null", "{}", r#"["JC4wMg"]"#] {
            let jws = format!(r#"{{"payload":{payload},{m}}}"#);
            assert_eq!(code(verify(&jws)), "InvalidFormat", "{payload}");
        }
    }

    #[test]
    fn no_protected_header_signs_dot_payload() {
        // RFC 7515 §5.1 step 5 with an empty protected header; RFC 7520
        // §4.7's form: `header` only, signing input "." || b64(payload).
        let signature = b64url_encode(&fake_signature(&SigningAlg::HS256, b".JC4wMg"));
        let m = members_signed(None, Some(r#"{"alg":"HS256","kid":"k"}"#), &signature);
        for jws in [flattened(&m), general(std::slice::from_ref(&m))] {
            let v = verify(&jws).unwrap();
            assert_eq!(v.protected, None);
            assert_eq!(
                v.unprotected.as_ref().and_then(|h| h.kid.as_deref()),
                Some("k")
            );
            assert_eq!(*v.payload, PAYLOAD);
        }
        // Signed as if the protected header were "e30" ({}): not the same.
        let wrong = members_signed(
            None,
            Some(r#"{"alg":"HS256"}"#),
            &sig(SigningAlg::HS256, "e30", PAYLOAD_B64),
        );
        assert_eq!(code(verify(&flattened(&wrong))), "InvalidSignature");
    }

    #[test]
    fn bad_base64url_is_invalid_base64() {
        // RFC 7515 §5.2 steps 2, 6, 7; ADR 0026 §2 step 3.
        let p = enc(P_HS256);
        let s = sig(SigningAlg::HS256, &p, PAYLOAD_B64);
        for m in [
            format!(r#""protected":"{p}=","signature":"{s}""#),
            format!(r#""protected":"{p}","signature":"{s}=""#),
            format!(r#""protected":"{p}","signature":"A""#),
            format!(r#""protected":"e+0","signature":"{s}""#),
        ] {
            assert_eq!(code(verify(&flattened(&m))), "InvalidBase64", "{m}");
        }
        let jws = format!(r#"{{"payload":"JC4wMg=","protected":"{p}","signature":"{s}"}}"#);
        assert_eq!(code(verify(&jws)), "InvalidBase64");
    }

    // ---- Header rules across objects (RFC 7515 §5.2 step 4, §4.1.11;
    // RFC 7797 §3) ----

    #[test]
    fn header_rules_are_invalid_header() {
        let cases = [
            // A name in both the protected and the unprotected header.
            members(
                Some(r#"{"alg":"HS256","kid":"a"}"#),
                Some(r#"{"kid":"b"}"#),
                SigningAlg::HS256,
            ),
            members(Some(P_HS256), Some(r#"{"alg":"HS256"}"#), SigningAlg::HS256),
            // `crit` in the unprotected header.
            members(
                Some(P_HS256),
                Some(r#"{"crit":["exp"],"exp":1}"#),
                SigningAlg::HS256,
            ),
            // `b64` in the unprotected header.
            members(Some(P_HS256), Some(r#"{"b64":true}"#), SigningAlg::HS256),
            // A registered parameter of the wrong type, in either header.
            members(Some(P_HS256), Some(r#"{"kid":1}"#), SigningAlg::HS256),
            members(Some(r#"{"alg":"HS256","kid":1}"#), None, SigningAlg::HS256),
            // No `alg` in the union, or no header at all.
            members(None, Some(r#"{"kid":"k"}"#), SigningAlg::HS256),
            members(None, None, SigningAlg::HS256),
        ];
        for m in &cases {
            assert_eq!(code(verify(&flattened(m))), "InvalidHeader", "{m}");
            assert_eq!(
                code(verify(&general(std::slice::from_ref(m)))),
                "InvalidHeader",
                "{m}"
            );
        }
        // The protected header must be a JSON object (ADR 0026 §2 step 4).
        let m = members(Some("[1]"), None, SigningAlg::HS256);
        assert_eq!(code(verify(&flattened(&m))), "InvalidJson");
    }

    #[test]
    fn b64_must_agree_across_signatures() {
        // RFC 7797 §3: every signature must use the same `b64` value; a
        // disagreement rejects the whole JWS (ADR 0026 §3), even though
        // signature 1 verifies on its own.
        let p_false = enc(P_B64_FALSE);
        let unencoded = members_signed(
            Some(P_B64_FALSE),
            None,
            &sig(SigningAlg::HS256, &p_false, PAYLOAD_B64),
        );
        let encoded = members(Some(P_HS256), None, SigningAlg::HS256);
        for entries in [
            [unencoded.clone(), encoded.clone()],
            [encoded.clone(), unencoded.clone()],
        ] {
            assert_eq!(code(verify(&general(&entries))), "InvalidHeader");
        }
        // Absent and `true` are the same value (RFC 7797 §3).
        let explicit_true = r#"{"alg":"HS256","b64":true,"crit":["b64"]}"#;
        let jws = general(&[
            members(Some(explicit_true), None, SigningAlg::HS256),
            encoded,
        ]);
        assert_eq!(code(verify(&jws)), "ok");
    }

    #[test]
    fn b64_false_payload_is_the_json_string() {
        // RFC 7797 §3, §5.3: the signing input ends in the payload octets,
        // and the JSON Serialization carries them as a string.
        let p = enc(P_B64_FALSE);
        let payload = "a \"quoted\" $.02\n";
        let signature = sig(SigningAlg::HS256, &p, payload);
        let jws = format!(
            r#"{{"payload":"a \"quoted\" $.02\n","protected":"{p}","signature":"{signature}"}}"#
        );
        let v = verify(&jws).unwrap();
        assert_eq!(*v.payload, payload.as_bytes());
        // Not base64url-decoded: "JC4wMg" stays six octets.
        let s = sig(SigningAlg::HS256, &p, PAYLOAD_B64);
        let jws = format!(r#"{{"payload":"{PAYLOAD_B64}","protected":"{p}","signature":"{s}"}}"#);
        assert_eq!(*verify(&jws).unwrap().payload, PAYLOAD_B64.as_bytes());
    }

    #[test]
    fn earlier_steps_win_across_signatures() {
        // ADR 0026 §2-§3: steps 1-4 run over every signature first, step
        // by step, so a later signature's earlier-step error wins.
        let good = members(Some(P_HS256), None, SigningAlg::HS256);
        let overlap = members(Some(P_HS256), Some(r#"{"alg":"HS256"}"#), SigningAlg::HS256);
        let not_json = members(Some("{"), None, SigningAlg::HS256);
        let bad_b64 = members_signed(Some(P_HS256), None, "A");
        let no_sig = format!(r#""protected":"{}""#, enc(P_HS256));
        for (entries, expected) in [
            (vec![overlap.clone(), not_json.clone()], "InvalidJson"),
            (vec![not_json.clone(), bad_b64.clone()], "InvalidBase64"),
            (vec![bad_b64, no_sig], "InvalidFormat"),
            (vec![good.clone(), overlap], "InvalidHeader"),
            (vec![good, not_json], "InvalidJson"),
        ] {
            assert_eq!(code(verify(&general(&entries))), expected, "{entries:?}");
        }
    }

    #[test]
    fn payload_base64_runs_after_header_parsing_before_header_structure() {
        // ADR 0048 steps 3-5, as in compact.rs: the payload's encoding
        // depends on `b64`, so it is decoded (step 4) once every header has
        // parsed and its parameters have their types (step 3; the
        // unprotected header's too, ADR 0049 §3), and before the structure
        // rules (step 5).
        let bad_payload = |entries: &[String]| {
            general(entries).replacen(
                &format!(r#""payload":"{PAYLOAD_B64}""#),
                r#""payload":"JC4wMg=""#,
                1,
            )
        };
        let good = members(Some(P_HS256), None, SigningAlg::HS256);
        let no_alg = members(Some(r#"{"kid":"k"}"#), None, SigningAlg::HS256);
        let overlap = members(Some(P_HS256), Some(r#"{"alg":"HS256"}"#), SigningAlg::HS256);
        let unknown_crit = members(
            Some(r#"{"alg":"HS256","crit":["exp"],"exp":1}"#),
            None,
            SigningAlg::HS256,
        );
        let not_json = members(Some("{"), None, SigningAlg::HS256);
        let mistyped = members(
            Some(r#"{"alg":"HS256","b64":"no"}"#),
            None,
            SigningAlg::HS256,
        );
        let mistyped_unprotected = members(Some(P_HS256), Some(r#"{"kid":1}"#), SigningAlg::HS256);
        for (entries, expected) in [
            (vec![good.clone()], "InvalidBase64"),
            (vec![good.clone(), no_alg], "InvalidBase64"),
            (vec![overlap, good.clone()], "InvalidBase64"),
            (vec![unknown_crit], "InvalidBase64"),
            (vec![good.clone(), not_json], "InvalidJson"),
            (vec![good.clone(), mistyped], "InvalidHeader"),
            (vec![mistyped_unprotected, good], "InvalidHeader"),
        ] {
            assert_eq!(
                code(verify(&bad_payload(&entries))),
                expected,
                "{entries:?}"
            );
        }
    }

    #[test]
    fn unprotected_header_types_are_checked_before_the_payload_encoding() {
        // ADR 0049 §3, amending ADR 0048 step 3: registered parameters of
        // the `header` member (RFC 7515 §7.2.1) get their types checked
        // with the protected header's, before the payload's base64url
        // (step 4). `kid` must be a string (RFC 7515 §4.1.4).
        let with_bad_payload = |jws: String| {
            jws.replacen(
                &format!(r#""payload":"{PAYLOAD_B64}""#),
                r#""payload":"JC4wMg=""#,
                1,
            )
        };
        for (header, expected) in [
            (r#"{"kid":1}"#, "InvalidHeader"),
            // Control: a well-typed `kid` reaches the payload check.
            (r#"{"kid":"k1"}"#, "InvalidBase64"),
        ] {
            let m = members(Some(P_HS256), Some(header), SigningAlg::HS256);
            for jws in [flattened(&m), general(std::slice::from_ref(&m))] {
                let jws = with_bad_payload(jws);
                assert_eq!(code(verify(&jws)), expected, "{jws}");
            }
        }
    }

    #[test]
    fn b64_disagreement_wins_over_the_payload_encoding() {
        // When the protected headers disagree on `b64` (RFC 7797 §3) there
        // is no single payload encoding to check, so the disagreement
        // (InvalidHeader) is reported, never InvalidBase64.
        let p_false = enc(P_B64_FALSE);
        let unencoded = members_signed(
            Some(P_B64_FALSE),
            None,
            &sig(SigningAlg::HS256, &p_false, "$.02"),
        );
        let encoded = members(Some(P_HS256), None, SigningAlg::HS256);
        for entries in [[unencoded.clone(), encoded.clone()], [encoded, unencoded]] {
            let jws = general(&entries).replacen(PAYLOAD_B64, "$.02", 1);
            assert_eq!(code(verify(&jws)), "InvalidHeader");
        }
        // `b64` in the unprotected header does not decide the encoding:
        // the payload is checked as base64url, then the placement fails.
        let misplaced = members(Some(P_HS256), Some(r#"{"b64":false}"#), SigningAlg::HS256);
        let jws = flattened(&misplaced).replacen(PAYLOAD_B64, "$.02", 1);
        assert_eq!(code(verify(&jws)), "InvalidBase64");
        assert_eq!(code(verify(&flattened(&misplaced))), "InvalidHeader");
    }

    #[test]
    fn content_signs_the_received_payload_text() {
        // RFC 7515 §5.2 step 8 over BASE64URL(JWS Payload): the received
        // member, not a re-encoding; RFC 7797 §3 for the octets; the
        // detached content encoded once (RFC 7515 Appendix F).
        let text = || Payload::Attached(Zeroizing::new(PAYLOAD_B64.to_owned()));
        let encoded = Content::new(text(), true).unwrap();
        assert_eq!(encoded.part(), PAYLOAD_B64.as_bytes());
        assert_eq!(*encoded.into_payload(), PAYLOAD);
        let unencoded = Content::new(text(), false).unwrap();
        assert_eq!(unencoded.part(), PAYLOAD_B64.as_bytes());
        assert_eq!(*unencoded.into_payload(), PAYLOAD_B64.as_bytes());
        let detached = Content::new(Payload::Detached(PAYLOAD), true).unwrap();
        assert_eq!(detached.part(), PAYLOAD_B64.as_bytes());
        assert_eq!(*detached.into_payload(), PAYLOAD);
        let raw = Content::new(Payload::Detached(PAYLOAD), false).unwrap();
        assert_eq!(raw.part(), PAYLOAD);
        // Only the canonical encoding is accepted (RFC 4648 §3.5), so the
        // received text is the one encoding of the payload: "QR" is not
        // read as 0x41.
        let qr = Payload::Attached(Zeroizing::new("QR".to_owned()));
        assert_eq!(
            Content::new(qr, true).map(|_| ()),
            Err(Error::InvalidBase64)
        );
    }

    // ---- Detached content (RFC 7515 Appendix F) ----

    #[test]
    fn detached_payload_must_match_the_payload_member() {
        let m = members(Some(P_HS256), None, SigningAlg::HS256);
        let opts = VerifyOptions::new(HS256).unwrap();
        // Detached, but `payload` is present.
        assert_eq!(
            code(verify_opts(&flattened(&m), &opts.detached_payload(PAYLOAD))),
            "InvalidFormat"
        );
        // Attached, but `payload` is missing (RFC 7515 §7.2.1: MUST be present).
        let detached = format!("{{{m}}}");
        let general_detached = format!(r#"{{"signatures":[{{{m}}}]}}"#);
        for jws in [&detached, &general_detached] {
            assert_eq!(code(verify_opts(jws, &opts)), "InvalidFormat");
            let v = verify_opts(jws, &opts.detached_payload(PAYLOAD)).unwrap();
            assert_eq!(*v.payload, PAYLOAD);
        }
        // The signature covers the detached payload.
        assert_eq!(
            code(verify_opts(&detached, &opts.detached_payload(b"$.03"))),
            "InvalidSignature"
        );
        // b64 false and detached: the raw octets, which need not be UTF-8.
        let p = enc(P_B64_FALSE);
        let raw = [0xff, b'.', 0x00];
        let mut input = format!("{p}.").into_bytes();
        input.extend_from_slice(&raw);
        let s = b64url_encode(&fake_signature(&SigningAlg::HS256, &input));
        let jws = format!(r#"{{"protected":"{p}","signature":"{s}"}}"#);
        let v = verify_opts(&jws, &opts.detached_payload(&raw)).unwrap();
        assert_eq!(*v.payload, raw);
    }

    // ---- Multiple signatures (ADR 0026 §3) ----

    #[test]
    fn first_success_wins() {
        let bad = members_signed(
            Some(P_HS256),
            Some(r#"{"kid":"k0"}"#),
            &sig(SigningAlg::HS256, &enc(P_HS256), "other"),
        );
        let k1 = members(Some(P_HS256), Some(r#"{"kid":"k1"}"#), SigningAlg::HS256);
        let k2 = members(
            None,
            Some(r#"{"alg":"HS256","kid":"k2"}"#),
            SigningAlg::HS256,
        );
        let v = verify(&general(&[bad, k1, k2])).unwrap();
        assert_eq!(v.signature_index, 1);
        assert_eq!(v.protected, Some(hs256()));
        assert_eq!(v.unprotected, Some(kid("k1")));

        // Selection by the allow-list: only signature 2 uses HS384.
        let k2_384 = members(
            None,
            Some(r#"{"alg":"HS384","kid":"k2"}"#),
            SigningAlg::HS384,
        );
        let ok = members(Some(P_HS256), None, SigningAlg::HS256);
        let v = verify_allowing(&general(&[ok.clone(), ok, k2_384]), &[SigningAlg::HS384]).unwrap();
        assert_eq!(v.signature_index, 2);
        assert_eq!(v.alg, SigningAlg::HS384);
        assert_eq!(v.protected, None);
        assert_eq!(v.unprotected.and_then(|h| h.kid), Some("k2".into()));
    }

    #[test]
    fn a_malformed_signature_object_rejects_the_whole_jws() {
        // ADR 0026 §3: steps 1-4 over every signature first, even when an
        // earlier one verifies.
        let good = members(Some(P_HS256), None, SigningAlg::HS256);
        let p = enc(P_HS256);
        let s = sig(SigningAlg::HS256, &p, PAYLOAD_B64);
        for (bad, expected) in [
            (format!(r#""protected":"{p}""#), "InvalidFormat"),
            (
                format!(r#""protected":"","signature":"{s}""#),
                "InvalidFormat",
            ),
            (
                format!(r#""protected":"{p}","header":"x","signature":"{s}""#),
                "InvalidFormat",
            ),
            (
                format!(r#""protected":"{p}","signature":"{s}=""#),
                "InvalidBase64",
            ),
            (
                members(Some(r#"{"alg":"HS256""#), None, SigningAlg::HS256),
                "InvalidJson",
            ),
            (
                members(Some(P_HS256), Some(r#"{"alg":"HS256"}"#), SigningAlg::HS256),
                "InvalidHeader",
            ),
            (
                members(
                    Some(P_HS256),
                    Some(r#"{"crit":["b64"]}"#),
                    SigningAlg::HS256,
                ),
                "InvalidHeader",
            ),
        ] {
            let jws = general(&[good.clone(), bad.clone()]);
            assert_eq!(code(verify(&jws)), expected, "{bad}");
        }
    }

    #[test]
    fn none_verifies_reports_the_furthest_error() {
        // ADR 0026 §3: InvalidSignature > InvalidKey > KeyAlgorithmMismatch
        // > AlgorithmNotAllowed > UnsupportedAlgorithm > UnknownCritical.
        let p = enc(P_HS256);
        let invalid_signature =
            members_signed(Some(P_HS256), None, &sig(SigningAlg::HS256, &p, "other"));
        let not_allowed = members(Some(r#"{"alg":"HS384"}"#), None, SigningAlg::HS384);
        let unknown_crit = members(
            Some(r#"{"alg":"HS256","crit":["exp"],"exp":1}"#),
            None,
            SigningAlg::HS256,
        );
        let unsupported = members(Some(r#"{"alg":"HS1"}"#), None, SigningAlg::HS256);
        let mismatch = members(Some(r#"{"alg":"ES256"}"#), None, SigningAlg::ES256);
        let allowed = [SigningAlg::HS256, SigningAlg::ES256];
        for (entries, expected) in [
            (
                vec![invalid_signature.clone(), not_allowed.clone()],
                "InvalidSignature",
            ),
            (
                vec![not_allowed.clone(), invalid_signature.clone()],
                "InvalidSignature",
            ),
            (
                vec![unknown_crit.clone(), unknown_crit.clone()],
                "UnknownCritical",
            ),
            (
                vec![unknown_crit.clone(), unsupported.clone()],
                "UnsupportedAlgorithm",
            ),
            (
                vec![unsupported, not_allowed.clone()],
                "AlgorithmNotAllowed",
            ),
            (
                vec![not_allowed, mismatch.clone(), unknown_crit],
                "KeyAlgorithmMismatch",
            ),
            (vec![mismatch, invalid_signature], "InvalidSignature"),
        ] {
            assert_eq!(
                code(verify_allowing(&general(&entries), &allowed)),
                expected,
                "{entries:?}"
            );
        }
    }

    #[test]
    fn rejecting_family_fails_every_signature() {
        let m = members(Some(P_HS256), None, SigningAlg::HS256);
        let jws = general(&[m.clone(), m]);
        let opts = VerifyOptions::new(HS256).unwrap();
        assert_eq!(
            verify_json_with(&REJECTING, &jws, &key(), &opts),
            Err(Error::InvalidSignature)
        );
    }

    #[test]
    fn public_verify_json_checks_the_shape_first() {
        // The real families are not reached for a malformed JWS.
        let opts = VerifyOptions::new(HS256).unwrap();
        assert_eq!(
            verify_json("[]", &key(), &opts)
                .map(drop)
                .unwrap_err()
                .code(),
            "InvalidFormat"
        );
    }

    // ---- Signing (RFC 7515 §5.1, §7.2) ----

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

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

    fn sign_code(r: Result<String>) -> &'static str {
        r.err().map_or("ok", |e| e.code())
    }

    fn attached() -> SignOptions {
        SignOptions::new()
    }

    #[test]
    fn sign_flattened_output_is_exact_and_verifies() {
        // RFC 7515 §7.2.2: payload, protected, header, signature at the
        // top level; compact, deterministic JSON.
        let k = key();
        let signer = Signer::new(&k)
            .protected(protected(P_HS256))
            .unprotected(kid("k1"));
        let jws = sign_flattened_with(&FAKE, &signer, PAYLOAD, &attached()).unwrap();
        let p = enc(P_HS256);
        let s = sig(SigningAlg::HS256, &p, PAYLOAD_B64);
        assert_eq!(
            jws,
            format!(
                r#"{{"payload":"{PAYLOAD_B64}","protected":"{p}","header":{{"kid":"k1"}},"signature":"{s}"}}"#
            )
        );
        assert_eq!(
            sign_flattened_with(&FAKE, &signer, PAYLOAD, &attached()).unwrap(),
            jws
        );
        let v = verify(&jws).unwrap();
        assert_eq!((v.payload.as_slice(), v.signature_index), (PAYLOAD, 0));
        assert_eq!(v.protected, Some(hs256()));
        assert_eq!(v.unprotected, Some(kid("k1")));
    }

    #[test]
    fn sign_flattened_keeps_the_protected_encoding() {
        // RFC 7515 §5.1 step 3: the signature covers the encoded octets,
        // here RFC 7515 A.1's header with its CRLF.
        let a1 = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9";
        let k = key();
        let signer = Signer::new(&k).protected(ProtectedHeader::from_encoded(a1).unwrap());
        let jws = sign_flattened_with(&FAKE, &signer, PAYLOAD, &attached()).unwrap();
        let s = sig(SigningAlg::HS256, a1, PAYLOAD_B64);
        assert_eq!(
            jws,
            format!(r#"{{"payload":"{PAYLOAD_B64}","protected":"{a1}","signature":"{s}"}}"#)
        );
        assert_eq!(*verify(&jws).unwrap().payload, PAYLOAD);
    }

    #[test]
    fn sign_general_mixes_header_kinds_and_round_trips() {
        // RFC 7515 §7.2.1: `protected` only, `header` only, and both.
        let k = key();
        let signers = [
            Signer::new(&k).protected(protected(P_HS256)),
            Signer::new(&k).unprotected(header(r#"{"alg":"HS384","kid":"u"}"#)),
            Signer::new(&k)
                .protected(protected(r#"{"alg":"HS512"}"#))
                .unprotected(kid("b")),
        ];
        let jws = sign_general_with(&FAKE, &signers, PAYLOAD, &attached()).unwrap();
        let p0 = enc(P_HS256);
        let p2 = enc(r#"{"alg":"HS512"}"#);
        let s0 = sig(SigningAlg::HS256, &p0, PAYLOAD_B64);
        let s1 = sig(SigningAlg::HS384, "", PAYLOAD_B64);
        let s2 = sig(SigningAlg::HS512, &p2, PAYLOAD_B64);
        assert_eq!(
            jws,
            format!(
                r#"{{"payload":"{PAYLOAD_B64}","signatures":[{{"protected":"{p0}","signature":"{s0}"}},{{"header":{{"alg":"HS384","kid":"u"}},"signature":"{s1}"}},{{"protected":"{p2}","header":{{"kid":"b"}},"signature":"{s2}"}}]}}"#
            )
        );
        for (index, alg) in [SigningAlg::HS256, SigningAlg::HS384, SigningAlg::HS512]
            .into_iter()
            .enumerate()
        {
            let v = verify_allowing(&jws, std::slice::from_ref(&alg)).unwrap();
            assert_eq!(v.signature_index, index);
            assert_eq!(v.alg, alg);
            assert_eq!(*v.payload, PAYLOAD);
            assert_eq!(v.protected.is_some(), index != 1);
            assert_eq!(v.unprotected.is_some(), index != 0);
        }
    }

    #[test]
    fn empty_unprotected_header_is_omitted() {
        // RFC 7515 §7.2.1: `header` MUST be absent when the JWS
        // Unprotected Header is empty.
        let k = key();
        let signer = Signer::new(&k)
            .protected(protected(P_HS256))
            .unprotected(Header::new());
        let flat = sign_flattened_with(&FAKE, &signer, PAYLOAD, &attached()).unwrap();
        let gen_ = sign_general_with(&FAKE, &[signer], PAYLOAD, &attached()).unwrap();
        for jws in [flat, gen_] {
            assert!(!jws.contains("header"), "{jws}");
            assert_eq!(verify(&jws).unwrap().unprotected, None);
        }
    }

    #[test]
    fn sign_detached_omits_the_payload_member() {
        // RFC 7515 Appendix F: the signature still covers the payload.
        let k = key();
        let signer = Signer::new(&k).protected(protected(P_HS256));
        let detached = SignOptions::new().detached(true);
        let flat = sign_flattened_with(&FAKE, &signer, PAYLOAD, &detached).unwrap();
        let p = enc(P_HS256);
        let s = sig(SigningAlg::HS256, &p, PAYLOAD_B64);
        assert_eq!(flat, format!(r#"{{"protected":"{p}","signature":"{s}"}}"#));
        let gen_ = sign_general_with(&FAKE, &[signer], PAYLOAD, &detached).unwrap();
        assert_eq!(
            gen_,
            format!(r#"{{"signatures":[{{"protected":"{p}","signature":"{s}"}}]}}"#)
        );
        let opts = VerifyOptions::new(HS256).unwrap().detached_payload(PAYLOAD);
        for jws in [flat, gen_] {
            assert_eq!(*verify_opts(&jws, &opts).unwrap().payload, PAYLOAD);
        }
    }

    #[test]
    fn sign_b64_false_carries_the_payload_as_a_json_string() {
        // RFC 7797 §5.3: the unencoded payload is a JSON string, escaped
        // by the serializer; the signing input has its octets (§3).
        let k = key();
        let ph = protected(P_B64_FALSE);
        let p = ph.encoded().to_owned();
        let signer = Signer::new(&k).protected(ph);
        let payload = "a \"quoted\" $.02\n";
        let flat = sign_flattened_with(&FAKE, &signer, payload.as_bytes(), &attached()).unwrap();
        let s = sig(SigningAlg::HS256, &p, payload);
        assert_eq!(
            flat,
            format!(r#"{{"payload":"a \"quoted\" $.02\n","protected":"{p}","signature":"{s}"}}"#)
        );
        let gen_ = sign_general_with(
            &FAKE,
            &[signer.clone(), signer.clone()],
            payload.as_bytes(),
            &attached(),
        )
        .unwrap();
        for jws in [flat, gen_] {
            assert_eq!(*verify(&jws).unwrap().payload, payload.as_bytes());
        }

        // Octets that are not UTF-8 cannot be a JSON string.
        let raw = [b'a', 0xff];
        assert_eq!(
            sign_code(sign_flattened_with(&FAKE, &signer, &raw, &attached())),
            "InvalidFormat"
        );
        assert_eq!(
            sign_code(sign_general_with(
                &FAKE,
                std::slice::from_ref(&signer),
                &raw,
                &attached()
            )),
            "InvalidFormat"
        );
        // Detached, they are never carried, so any octets sign.
        let detached = SignOptions::new().detached(true);
        let jws = sign_flattened_with(&FAKE, &signer, &raw, &detached).unwrap();
        let opts = VerifyOptions::new(HS256).unwrap().detached_payload(&raw);
        assert_eq!(*verify_opts(&jws, &opts).unwrap().payload, raw);
        // b64 true: any octets, base64url-encoded.
        let plain = Signer::new(&k).protected(protected(P_HS256));
        let jws = sign_flattened_with(&FAKE, &plain, &raw, &attached()).unwrap();
        assert_eq!(*verify(&jws).unwrap().payload, raw);
    }

    #[test]
    fn sign_general_with_no_signers_is_invalid_format() {
        // RFC 7515 §7.2.1: `signatures` holds one or more objects.
        assert_eq!(
            sign_code(sign_general_with(&FAKE, &[], PAYLOAD, &attached())),
            "InvalidFormat"
        );
    }

    #[test]
    fn sign_applies_the_header_and_key_rules() {
        // ADR 0026 §2 steps 4-8 on sign, through process.rs.
        let k = key();
        let public = keys::p256("");
        let short = keys::oct(16, "");
        let p = |json| Some(protected(json));
        let u = |json| Some(header(json));
        let cases: [(Option<ProtectedHeader>, Option<Header>, &Jwk, &str); 11] = [
            (
                p(r#"{"alg":"HS256","kid":"a"}"#),
                u(r#"{"kid":"b"}"#),
                &k,
                "InvalidHeader",
            ),
            (None, None, &k, "InvalidHeader"),
            (None, u(r#"{"kid":"k"}"#), &k, "InvalidHeader"),
            (
                p(P_HS256),
                u(r#"{"crit":["exp"],"exp":1}"#),
                &k,
                "InvalidHeader",
            ),
            (
                p(r#"{"alg":"HS256","b64":false}"#),
                None,
                &k,
                "InvalidHeader",
            ),
            (
                p(r#"{"alg":"HS256","crit":["exp"],"exp":1}"#),
                None,
                &k,
                "UnknownCritical",
            ),
            (p(r#"{"alg":"HS1"}"#), None, &k, "UnsupportedAlgorithm"),
            (p(r#"{"alg":"none"}"#), None, &k, "AlgorithmNotAllowed"),
            (None, u(r#"{"alg":"RS256"}"#), &k, "UnsupportedAlgorithm"),
            (
                p(r#"{"alg":"ES256"}"#),
                None,
                &public,
                "KeyAlgorithmMismatch",
            ),
            (p(P_HS256), None, &short, "InvalidKey"),
        ];
        for (protected, unprotected, key, expected) in cases {
            let mut signer = Signer::new(key);
            signer.protected = protected;
            signer.unprotected = unprotected;
            assert_eq!(
                sign_code(sign_flattened_with(&FAKE, &signer, PAYLOAD, &attached())),
                expected,
                "{signer:?}"
            );
            assert_eq!(
                sign_code(sign_general_with(&FAKE, &[signer], PAYLOAD, &attached())),
                expected
            );
        }
    }

    #[test]
    fn sign_general_checks_every_signer_step_by_step() {
        let k = key();
        let ok = Signer::new(&k).protected(protected(P_HS256));
        let none = Signer::new(&k).protected(protected(r#"{"alg":"none"}"#));
        let overlap = Signer::new(&k)
            .protected(protected(P_HS256))
            .unprotected(header(r#"{"alg":"HS256"}"#));
        let unencoded = Signer::new(&k).protected(protected(P_B64_FALSE));
        let unencoded_unknown = Signer::new(&k).protected(protected(
            r#"{"alg":"HS256","b64":false,"crit":["b64","exp"],"exp":1}"#,
        ));
        let unknown =
            Signer::new(&k).protected(protected(r#"{"alg":"HS256","crit":["exp"],"exp":1}"#));
        let raw: &[u8] = &[0xff];
        for (signers, payload, expected) in [
            // Step 4 runs over every signer before steps 5-8.
            (vec![none.clone(), overlap], PAYLOAD, "InvalidHeader"),
            // RFC 7797 §3: one `b64` value for the whole JWS.
            (
                vec![ok.clone(), unencoded.clone()],
                PAYLOAD,
                "InvalidHeader",
            ),
            (
                vec![unencoded.clone(), ok.clone()],
                PAYLOAD,
                "InvalidHeader",
            ),
            // Steps 5-8 per signer, in order.
            (
                vec![none.clone(), unknown.clone()],
                PAYLOAD,
                "AlgorithmNotAllowed",
            ),
            (vec![unknown, none], PAYLOAD, "UnknownCritical"),
            // Then the payload rule (RFC 7797 §5.3).
            (
                vec![unencoded.clone(), unencoded_unknown],
                raw,
                "UnknownCritical",
            ),
            (vec![unencoded.clone(), unencoded], raw, "InvalidFormat"),
            (vec![ok.clone(), ok], raw, "ok"),
        ] {
            assert_eq!(
                sign_code(sign_general_with(&FAKE, &signers, payload, &attached())),
                expected,
                "{signers:?}"
            );
        }
    }

    #[test]
    fn public_sign_functions_check_headers_before_the_family() {
        let k = key();
        assert_eq!(
            sign_code(sign_general(&[], PAYLOAD, &attached())),
            "InvalidFormat"
        );
        let no_alg = Signer::new(&k).unprotected(kid("k"));
        assert_eq!(
            sign_code(sign_flattened(&no_alg, PAYLOAD, &attached())),
            "InvalidHeader"
        );
    }
}