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
//! JWS Compact Serialization (RFC 7515 §3.1, §7.1), with detached content
//! (RFC 7515 Appendix F) and the unencoded payload option (RFC 7797 §5.2).
//!
//! A compact JWS is `BASE64URL(UTF8(JWS Protected Header)) '.'
//! BASE64URL(JWS Payload) '.' BASE64URL(JWS Signature)` (RFC 7515 §3.1,
//! §7.1): one signature, and the protected header is the whole JOSE
//! Header. This file owns the serialization's own rules, steps 1–4 of
//! ADR 0048 (which clarifies ADR 0026 §2), and hands everything else to
//! the shared rules in `jws/process.rs`, which `json.rs` uses too:
//!
//! | step | compact rule | error |
//! |---|---|---|
//! | 1 | the input is at most [`VerifyOptions::max_input_len`] octets, a detached payload not counted (ADR 0026 §7); exactly two `.` (RFC 7515 §5.2 step 1); with a detached payload, an empty payload part (Appendix F) | [`Error::InvalidFormat`] |
//! | 2 | strict base64url of the signature (RFC 7515 §2, §5.2 step 7) | [`Error::InvalidBase64`] |
//! | 3 | the protected header: strict base64url (§5.2 step 2), one I-JSON object, duplicate members included (§5.2 step 3; ADR 0041 §1), registered parameter types and `crit` syntax (`Header::from_json`, RFC 7515 §4.1.11) | [`Error::InvalidBase64`]; [`Error::InvalidJson`]; [`Error::InvalidHeader`] |
//! | 4 | strict base64url of the payload part, unless `b64` is `false` or the payload is detached (§5.2 step 6; RFC 7797 §3) | [`Error::InvalidBase64`] |
//! | 5 | `JoseHeader::new`: the whole-header structure rules | [`Error::InvalidHeader`] |
//! | 6a–6c | `allowed_alg`: `crit` understood, `alg` known, `alg` allowed (ADR 0026 §2 steps 5–7) | as in the [module table](crate::jws) |
//! | 6d–6e | `verify_with_key` over the received header encoding: key binding, then the signature (RFC 7515 §5.2 steps 5, 8; ADR 0026 §2 steps 8–9) | as in the [module table](crate::jws) |
//!
//! Verification is split at the key: [`precheck_compact`] runs steps 1–6c
//! once, without a key, and returns a [`CompactPrechecked`];
//! [`finish_compact`] runs steps 6d–6e on it for one key, and may be called
//! again with another. [`verify_compact`] is the two in sequence. The JWT
//! layer reads the protected header and chooses candidate keys in between
//! (ADR 0027 §9, ADR 0029 §1).
//!
//! Step 4 needs the protected header's `b64`, so it runs once that header
//! has parsed and its parameters have their types, and before its
//! structure rules (ADR 0048): a token with an unparsable header, or one
//! whose `alg` is not a string, and a bad payload part is
//! [`Error::InvalidJson`] or [`Error::InvalidHeader`], while one with a
//! parsable header missing `alg` and a bad payload part is
//! [`Error::InvalidBase64`].
//!
//! Signing runs `JoseHeader::new` and `prepare_sign` (steps 5 and 6a–6d of
//! the module table), then the RFC 7797 §5.2 payload rule, then the
//! family.
//!
//! 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").

use core::fmt;

use zeroize::Zeroizing;

use crate::error::{Error, Result};
use crate::header::Header;
use crate::jwa::SigningAlg;
use crate::jwk::Jwk;
use crate::util::{b64url_decode, b64url_encode};

use super::alg::{FAMILIES, Families};
use super::process::{
    JoseHeader, allowed_alg, prepare_sign, signing_input, signing_input_from_part, verify_with_key,
};
use super::{ProtectedHeader, SignOptions, Verified, VerifyOptions};

/// Signs `payload` in the JWS Compact Serialization (RFC 7515 §5.1, §7.1):
/// `BASE64URL(UTF8(JWS Protected Header)) '.' BASE64URL(JWS Payload) '.'
/// BASE64URL(JWS Signature)`.
///
/// - `alg` comes from `protected`, the whole JOSE Header in this
///   serialization (RFC 7515 §7.1).
/// - With [`SignOptions::detached`] the payload part is empty:
///   `header..signature` (RFC 7515 Appendix F).
/// - With `"b64": false` (listed in `crit`), the payload is signed and
///   carried unencoded (RFC 7797 §3, §5.2). Attached, it must then be
///   printable ASCII without `.`; detached, any octets are allowed.
///
/// The signing input uses `protected`'s exact encoding
/// ([`ProtectedHeader::encoded`]), so a header made with
/// [`ProtectedHeader::from_encoded`] is signed as given (RFC 7515 §5.1
/// step 5). The output is ASCII.
///
/// # Errors
///
/// In this order (see the [module docs](crate::jws) for the full table):
///
/// - [`Error::InvalidHeader`]: `alg` missing, `crit` malformed, or `b64`
///   not listed in `crit` (RFC 7515 §4.1.11; RFC 7797 §3, §6).
/// - [`Error::UnknownCritical`]: `crit` lists a name other than `b64`.
/// - [`Error::UnsupportedAlgorithm`]: `alg` unknown, or RS*/PS* (no RSA
///   signing, ADR 0021).
/// - [`Error::AlgorithmNotAllowed`]: `alg` is `none` (RFC 8725 §3.2).
/// - [`Error::KeyAlgorithmMismatch`] / [`Error::InvalidKey`]: key binding
///   (ADR 0026 §2 step 8), including a public-only key.
/// - [`Error::InvalidFormat`]: `b64: false` with an attached payload that
///   contains `.` or octets outside %x20-7E (RFC 7797 §5.2).
/// - [`Error::InvalidKey`] / [`Error::RandomnessUnavailable`] from the
///   algorithm itself.
pub fn sign_compact(
    protected: &ProtectedHeader,
    payload: &[u8],
    key: &Jwk,
    opts: &SignOptions,
) -> Result<String> {
    sign_compact_with(&FAMILIES, protected, payload, key, opts)
}

/// [`sign_compact`] with the signature primitives taken from `families`.
pub(crate) fn sign_compact_with(
    families: &Families,
    protected: &ProtectedHeader,
    payload: &[u8],
    key: &Jwk,
    opts: &SignOptions,
) -> Result<String> {
    // Step 4 (RFC 7515 §7.1: the protected header is the whole JOSE
    // Header), then steps 5-8 (ADR 0026 §2).
    let header = JoseHeader::new(Some(protected.header().clone()), None)?;
    let ready = prepare_sign(&header, key)?;
    let b64 = header.b64();
    // RFC 7797 §5.2, ADR 0026 §4: an attached unencoded payload is a part
    // of the serialization, so it may hold no '.' and only %x20-7E.
    if !b64 && !opts.detached && !payload.iter().all(|&b| is_unencoded_octet(b)) {
        return Err(Error::InvalidFormat(
            "b64:false compact payload must be printable ASCII without '.'",
        ));
    }
    // The payload as the signing input and the serialization carry it:
    // BASE64URL(JWS Payload), encoded once and wiped on drop (ADR 0049 §4),
    // or with `b64: false` the octets themselves (RFC 7797 §3, §5.2).
    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-6, over the header's exact encoding.
    let input = signing_input_from_part(protected.encoded(), payload_part);
    let signature = b64url_encode(&ready.sign(families, &input)?);

    // RFC 7515 §5.1 step 8, §7.1; Appendix F leaves the payload part empty.
    let carried = if opts.detached { &[][..] } else { payload_part };
    let mut jws =
        String::with_capacity(protected.encoded().len() + carried.len() + signature.len() + 2);
    jws.push_str(protected.encoded());
    jws.push('.');
    // Base64url, or checked above to be printable ASCII: each octet is one
    // `char`.
    jws.extend(carried.iter().copied().map(char::from));
    jws.push('.');
    jws.push_str(&signature);
    Ok(jws)
}

/// An octet an attached `b64:false` compact payload may contain: %x20-7E
/// except '.' (RFC 7797 §5.2; ADR 0026 §1, §4).
fn is_unencoded_octet(octet: u8) -> bool {
    matches!(octet, 0x20..=0x7e) && octet != b'.'
}

/// Verifies a JWS in the Compact Serialization (RFC 7515 §5.2, §7.1)
/// with `key`, accepting only the algorithms `opts` allows.
///
/// - Exactly three parts, separated by two `.` (RFC 7515 §5.2 step 1).
/// - With [`VerifyOptions::detached_payload`], the payload part must be
///   empty and the supplied octets are verified (RFC 7515 Appendix F).
///   Without it, an empty payload part is an empty payload.
/// - With `"b64": false`, the payload part's octets are the payload
///   (RFC 7797 §3).
///
/// On success, [`Verified::signature_index`] is `0` and
/// [`Verified::unprotected`] is `None`.
///
/// # Errors
///
/// The first failing step of ADR 0048 (clarifying ADR 0026 §2) decides
/// (see the [module docs](crate::jws)):
///
/// - Step 1, [`Error::InvalidFormat`]: longer than
///   [`VerifyOptions::max_input_len`] (a detached payload not counted),
///   not three parts, or a payload part present against the detached mode.
/// - Step 2, [`Error::InvalidBase64`]: the signature part is not strict
///   base64url (padding, `+`, `/` or whitespace, RFC 7515 §2).
/// - Step 3, the protected header: [`Error::InvalidBase64`] as for step 2,
///   [`Error::InvalidJson`] (including a duplicate header member,
///   ADR 0041 §1), or [`Error::InvalidHeader`] for a registered parameter
///   of the wrong type or a malformed `crit`.
/// - Step 4, [`Error::InvalidBase64`]: the payload part, checked once the
///   protected header has parsed, since its `b64` decides whether the
///   part is base64url at all (RFC 7797 §3).
/// - Step 5, [`Error::InvalidHeader`]: the whole-header structure rules
///   (`alg` missing, `crit` naming an absent parameter, `b64` rules).
/// - Step 6a, [`Error::UnknownCritical`].
/// - Step 6b, [`Error::UnsupportedAlgorithm`].
/// - Step 6c, [`Error::AlgorithmNotAllowed`], always for `none`.
/// - Step 6d, [`Error::KeyAlgorithmMismatch`] or [`Error::InvalidKey`].
/// - Step 6e, [`Error::InvalidSignature`].
pub fn verify_compact(jws: &str, key: &Jwk, opts: &VerifyOptions<'_>) -> Result<Verified> {
    verify_compact_with(&FAMILIES, jws, key, opts)
}

/// [`verify_compact`] with the signature primitives taken from `families`:
/// [`precheck_compact`], then [`finish_compact`] with `key`.
pub(crate) fn verify_compact_with(
    families: &Families,
    jws: &str,
    key: &Jwk,
    opts: &VerifyOptions<'_>,
) -> Result<Verified> {
    let pre = precheck_compact(jws, opts)?;
    finish_compact(families, &pre, key)
}

/// A compact JWS that passed ADR 0026 §2 steps 1–7, in the order ADR 0048
/// clarifies, and is ready for steps 8–9 with one or more candidate keys
/// ([`finish_compact`]). Only [`precheck_compact`] builds one.
///
/// It holds the parsed JWS Protected Header, the allowed `alg`, the JWS
/// Signing Input over the received encodings (RFC 7515 §5.2 step 8), the
/// decoded JWS Signature, and the payload: decoded and wiped on drop
/// (ADR 0049 §4), or borrowed from the token (`b64: false`, RFC 7797 §3)
/// or from the detached payload (RFC 7515 Appendix F). Nothing is parsed
/// again when it is finished, however many times.
///
/// Its `Debug` prints the `alg`, the header through [`Header`]'s redacting
/// `Debug`, and the payload and signature lengths, never their octets.
pub(crate) struct CompactPrechecked<'t> {
    alg: SigningAlg,
    protected: Header,
    signing_input: Zeroizing<Vec<u8>>,
    signature: Vec<u8>,
    payload: PrecheckedPayload<'t>,
}

/// The JWS Payload a [`CompactPrechecked`] holds until it verifies.
enum PrecheckedPayload<'t> {
    /// Base64url-decoded from the payload part (RFC 7515 §5.2 step 6); it
    /// may be secret, so it is wiped on drop (ADR 0049 §4).
    Decoded(Zeroizing<Vec<u8>>),
    /// The payload octets as the caller holds them: the payload part when
    /// `b64` is `false` (RFC 7797 §3), or the detached payload
    /// (RFC 7515 Appendix F). Not copied before verification.
    Borrowed(&'t [u8]),
}

impl PrecheckedPayload<'_> {
    fn as_bytes(&self) -> &[u8] {
        match self {
            Self::Decoded(decoded) => decoded,
            Self::Borrowed(octets) => octets,
        }
    }
}

impl CompactPrechecked<'_> {
    /// The JWS Protected Header, which is the whole JOSE Header in this
    /// serialization (RFC 7515 §7.1). It has passed every header rule of
    /// ADR 0026 §2 steps 4–5 (I-JSON, types and structure; `crit`
    /// understood), and is read-only: the signature covers its received encoding, not this
    /// value. `typ`, `cty`, `kid` and `crit` are read from here
    /// (ADR 0049 §2).
    pub(crate) fn header(&self) -> &Header {
        &self.protected
    }

    /// The header's `alg`, known and in the caller's allow-list
    /// (ADR 0026 §2 steps 6–7; RFC 8725 §3.1). Never `none`.
    pub(crate) fn alg(&self) -> &SigningAlg {
        &self.alg
    }
}

impl fmt::Debug for CompactPrechecked<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CompactPrechecked")
            .field("alg", &self.alg)
            .field("protected", &self.protected)
            .field("payload_len", &self.payload.as_bytes().len())
            .field("signature_len", &self.signature.len())
            .finish_non_exhaustive()
    }
}

/// Runs ADR 0026 §2 steps 1–7 on a compact JWS (RFC 7515 §5.2 steps 1–7,
/// §7.1), in the order ADR 0048 clarifies, without a key: everything
/// [`verify_compact`] checks before key binding. The JWT layer reads the
/// protected header and chooses candidate keys in between (ADR 0027 §9,
/// ADR 0029 §1), then calls [`finish_compact`] per candidate.
///
/// No signature is computed or checked here, and no key is touched.
///
/// # Errors
///
/// Exactly [`verify_compact`]'s steps 1–6c, with the same codes:
/// [`Error::InvalidFormat`], [`Error::InvalidBase64`],
/// [`Error::InvalidJson`], [`Error::InvalidHeader`],
/// [`Error::UnknownCritical`], [`Error::UnsupportedAlgorithm`],
/// [`Error::AlgorithmNotAllowed`].
pub(crate) fn precheck_compact<'t>(
    jws: &'t str,
    opts: &VerifyOptions<'t>,
) -> Result<CompactPrechecked<'t>> {
    // Step 1 (ADR 0048; the limit is ADR 0026 §7): the serialized JWS
    // only, not a detached payload, before any parsing.
    if jws.len() > opts.max_input_len {
        return Err(Error::InvalidFormat("compact JWS exceeds max_input_len"));
    }
    // Step 1, the shape (RFC 7515 §5.2 step 1, §7.1; Appendix F).
    let (protected_b64, payload_part, signature_b64) = split(jws)?;
    if opts.detached_payload.is_some() && !payload_part.is_empty() {
        return Err(Error::InvalidFormat(
            "compact payload part must be empty with a detached payload",
        ));
    }
    // Steps 3 and 2, base64url (RFC 7515 §5.2 steps 2 and 7): the
    // protected header and the signature. Both fail as InvalidBase64, so
    // their order is not observable.
    let protected_json = Zeroizing::new(b64url_decode(protected_b64)?);
    let signature = b64url_decode(signature_b64)?;
    // Step 3, I-JSON (RFC 7515 §5.2 step 3; a duplicate member is
    // InvalidJson, ADR 0041 §1), then the parameter types and `crit`
    // syntax (InvalidHeader, ADR 0048).
    let protected = Header::from_json(&protected_json)?;
    // Step 4, the payload part (RFC 7515 §5.2 step 6). Whether it is
    // base64url at all is the protected header's `b64` (RFC 7797 §3), so
    // it runs once that header has parsed, and before its structure rules.
    let b64 = protected.b64 != Some(false);
    // The decoded payload may be secret: wiped on drop (ADR 0049 §4).
    // Otherwise it is the caller's octets, borrowed.
    let payload = match opts.detached_payload {
        Some(detached) => PrecheckedPayload::Borrowed(detached),
        None if b64 => PrecheckedPayload::Decoded(Zeroizing::new(b64url_decode(payload_part)?)),
        None => PrecheckedPayload::Borrowed(payload_part.as_bytes()),
    };
    // Step 5, header structure (RFC 7515 §5.2 step 4, §7.1: the protected
    // header is the whole JOSE Header).
    let header = JoseHeader::new(Some(protected), None)?;
    // ADR 0026 §2 steps 5-7 (module table steps 6a-6c): crit understood,
    // alg known, alg allowed. No key yet.
    let alg = allowed_alg(&header, opts)?;
    // The JWS Signing Input (RFC 7515 §5.2 steps 5 and 8), over the
    // received encoding, built once for every candidate key. Attached, the
    // payload part is already in its signing-input form, BASE64URL(JWS
    // Payload) or the unencoded octets (RFC 7797 §3), and strict decoding
    // makes the received text the only encoding of the payload, so it is
    // used as received. Detached, it is computed from the supplied octets
    // (RFC 7515 Appendix F).
    let signing_input = match opts.detached_payload {
        Some(detached) => signing_input(protected_b64, detached, header.b64()),
        None => signing_input_from_part(protected_b64, payload_part.as_bytes()),
    };
    Ok(CompactPrechecked {
        alg,
        // RFC 7515 §7.1: the JOSE Header is the protected header.
        protected: header.into_union(),
        signing_input,
        signature,
        payload,
    })
}

/// Runs ADR 0026 §2 steps 8–9 on a [`CompactPrechecked`] with `key`: key
/// binding, then the signature check through `families` (RFC 7515 §5.2
/// step 8). It may be called with several keys in turn on the same
/// precheck; each call is independent.
///
/// Only when the signature verifies is the payload copied out, into
/// [`Verified::payload`], which is wiped on drop (ADR 0049 §4). The
/// result is the one [`verify_compact`] gives for the same token, options
/// and key: [`Verified::signature_index`] is `0` and
/// [`Verified::unprotected`] is `None`.
///
/// # Errors
///
/// [`verify_compact`]'s step 6d, [`Error::KeyAlgorithmMismatch`] or
/// [`Error::InvalidKey`], then step 6e, [`Error::InvalidSignature`] (or
/// [`Error::InvalidKey`] for a key only the primitive can reject).
pub(crate) fn finish_compact(
    families: &Families,
    pre: &CompactPrechecked<'_>,
    key: &Jwk,
) -> Result<Verified> {
    verify_with_key(families, pre.alg(), key, &pre.signing_input, &pre.signature)?;
    Ok(Verified {
        alg: pre.alg().clone(),
        protected: Some(pre.header().clone()),
        unprotected: None,
        payload: Zeroizing::new(pre.payload.as_bytes().to_vec()),
        signature_index: 0,
    })
}

/// Splits a compact JWS into its three parts (RFC 7515 §5.2 step 1: "exactly
/// two delimiting period characters"; §7.1).
///
/// # Errors
///
/// [`Error::InvalidFormat`] for any other number of parts (ADR 0026 §1).
fn split(jws: &str) -> Result<(&str, &str, &str)> {
    let mut parts = jws.split('.');
    match (parts.next(), parts.next(), parts.next(), parts.next()) {
        (Some(protected), Some(payload), Some(signature), None) => {
            Ok((protected, payload, signature))
        }
        _ => Err(Error::InvalidFormat("compact JWS must have three parts")),
    }
}

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

    use SigningAlg as A;

    const HS256: &str = r#"{"alg":"HS256"}"#;
    const HS256_B64_FALSE: &str = r#"{"alg":"HS256","b64":false,"crit":["b64"]}"#;
    const ALLOW_HS256: &[SigningAlg] = &[A::HS256];

    /// A compact JWS over `payload` with `header_json` as its protected
    /// header and the fake signature for `alg`, built by hand (RFC 7515
    /// §7.1, App. F; RFC 7797 §3, §5.2) so verify is tested apart from sign.
    fn forge(alg: &SigningAlg, header_json: &str, payload: &[u8], detached: bool) -> String {
        let b64 = !header_json.contains(r#""b64":false"#);
        let protected = b64url_encode(header_json.as_bytes());
        let sig = fake_signature(alg, &signing_input(&protected, payload, b64));
        let payload_part = match (detached, b64) {
            (true, _) => String::new(),
            (false, true) => b64url_encode(payload),
            (false, false) => String::from_utf8(payload.to_vec()).unwrap(),
        };
        format!("{protected}.{payload_part}.{}", b64url_encode(&sig))
    }

    fn hs_key() -> Jwk {
        keys::oct(32, "")
    }

    fn verify_with(jws: &str, opts: &VerifyOptions<'_>) -> Result<Verified> {
        verify_compact_with(&FAKE, jws, &hs_key(), opts)
    }

    fn verify(jws: &str) -> Result<Verified> {
        verify_with(jws, &VerifyOptions::new(ALLOW_HS256).unwrap())
    }

    fn verify_code(jws: &str) -> &'static str {
        verify(jws).map_or_else(|e| e.code(), |_| "ok")
    }

    fn parts(jws: &str) -> [String; 3] {
        let p: Vec<&str> = jws.split('.').collect();
        [p[0].to_owned(), p[1].to_owned(), p[2].to_owned()]
    }

    #[test]
    fn verifies_a_forged_token() {
        let jws = forge(&A::HS256, HS256, b"hello", false);
        let v = verify(&jws).unwrap();
        assert_eq!(v.alg, A::HS256);
        assert_eq!(
            v.protected,
            Some(Header::from_json(HS256.as_bytes()).unwrap())
        );
        assert_eq!(v.unprotected, None);
        assert_eq!(*v.payload, b"hello");
        assert_eq!(v.signature_index, 0);
    }

    #[test]
    fn exactly_three_parts() {
        // RFC 7515 §5.2 step 1, §7.1; ADR 0026 §1, §2 step 2.
        let [p, l, s] = parts(&forge(&A::HS256, HS256, b"hello", false));
        for jws in [
            String::new(),
            p.clone(),
            format!("{p}.{l}"),
            format!("{p}.{l}.{s}.{s}"),
            format!("{p}.{l}.{s}."),
            format!(".{p}.{l}.{s}"),
            "...".to_owned(),
        ] {
            assert_eq!(verify_code(&jws), "InvalidFormat", "{jws}");
        }
    }

    #[test]
    fn input_over_max_input_len() {
        // ADR 0026 §7, §2 step 1: measured on the serialized JWS.
        let jws = forge(&A::HS256, HS256, b"hello", false);
        let opts = VerifyOptions::new(ALLOW_HS256).unwrap();
        assert!(verify_with(&jws, &opts.max_input_len(jws.len())).is_ok());
        assert_eq!(
            verify_with(&jws, &opts.max_input_len(jws.len() - 1)).map_err(|e| e.code()),
            Err("InvalidFormat")
        );
        // The limit is checked before the shape.
        assert_eq!(
            verify_with("a.b", &opts.max_input_len(1)),
            Err(Error::InvalidFormat("compact JWS exceeds max_input_len"))
        );
    }

    #[test]
    fn strict_base64url_in_every_part() {
        // RFC 7515 §2, §5.2 steps 2, 6 and 7: no padding, no '+' or '/',
        // no whitespace or line breaks (ADR 0026 §2 step 3).
        let jws = forge(&A::HS256, HS256, b"hello world", false);
        let [p, l, s] = parts(&jws);
        let mutations: [fn(&str) -> String; 7] = [
            |x| format!("{x}="),
            |x| format!("{x}=="),
            |x| format!("+{}", &x[1..]),
            |x| format!("/{}", &x[1..]),
            |x| format!("{} {}", &x[..2], &x[2..]),
            |x| format!("{}\n{}", &x[..2], &x[2..]),
            |x| format!("{}\r\n{}", &x[..2], &x[2..]),
        ];
        for m in mutations {
            for jws in [
                format!("{}.{l}.{s}", m(&p)),
                format!("{p}.{}.{s}", m(&l)),
                format!("{p}.{l}.{}", m(&s)),
            ] {
                assert_eq!(verify(&jws), Err(Error::InvalidBase64), "{jws:?}");
            }
        }
    }

    #[test]
    fn a_non_canonical_payload_part_never_reaches_the_signature() {
        // Verify signs the received payload part as is, which equals
        // re-encoding the payload only because decoding is canonical
        // (RFC 4648 §3.5): "QR" would also read as 0x41, but is rejected,
        // even when signed exactly as received.
        let protected = b64url_encode(HS256.as_bytes());
        let sig = fake_signature(&A::HS256, format!("{protected}.QR").as_bytes());
        let jws = format!("{protected}.QR.{}", b64url_encode(&sig));
        assert_eq!(verify(&jws), Err(Error::InvalidBase64));
        let canonical = forge(&A::HS256, HS256, &[0x41], false);
        assert_eq!(parts(&canonical)[1], "QQ");
        assert_eq!(*verify(&canonical).unwrap().payload, [0x41]);
    }

    #[test]
    fn protected_header_must_be_one_json_object() {
        // RFC 7515 §5.2 step 3: UTF-8, a completely valid JSON object, so
        // trailing garbage after it is InvalidJson (ADR 0026 §2 step 4).
        for header in [
            &br#"{"alg":"HS256"}x"#[..],
            br#"{"alg":"HS256"}{}"#,
            br#"{"alg":"HS256"},"#,
            br#"["HS256"]"#,
            br#""HS256""#,
            b"",
            b"{\"alg\":\"HS256\",\"x\":\"\xff\"}",
        ] {
            let jws = format!("{}.aGk.", b64url_encode(header));
            assert_eq!(verify_code(&jws), "InvalidJson", "{header:?}");
        }
    }

    #[test]
    fn duplicate_header_member_is_invalid_json() {
        // ADR 0041 §1, amending ADR 0026 §2 step 4.
        for header in [
            r#"{"alg":"HS256","alg":"HS256"}"#,
            r#"{"alg":"HS256","alg":"none"}"#,
            r#"{"alg":"HS256","b64":false,"crit":["b64"],"b64":false}"#,
            r#"{"alg":"HS256","x":1,"x":2}"#,
        ] {
            let jws = forge(&A::HS256, header, b"hi", false);
            assert_eq!(verify_code(&jws), "InvalidJson", "{header}");
        }
    }

    #[test]
    fn header_structure_rules_apply() {
        // ADR 0026 §2 step 4, through process::JoseHeader::new.
        for header in [
            r#"{"typ":"JWT"}"#,
            r#"{"alg":"HS256","b64":false}"#,
            r#"{"alg":"HS256","b64":true}"#,
            r#"{"alg":"HS256","crit":["x-a"]}"#,
            r#"{"alg":1}"#,
        ] {
            let jws = forge(&A::HS256, header, b"hi", false);
            assert_eq!(verify_code(&jws), "InvalidHeader", "{header}");
        }
    }

    #[test]
    fn detached_payload_requires_an_empty_payload_part() {
        // RFC 7515 Appendix F; ADR 0026 §1.
        let attached = forge(&A::HS256, HS256, b"hello", false);
        let opts = VerifyOptions::new(ALLOW_HS256)
            .unwrap()
            .detached_payload(b"hello");
        assert_eq!(
            verify_with(&attached, &opts).map_err(|e| e.code()),
            Err("InvalidFormat")
        );
        // The empty part: the supplied octets are verified.
        let detached = forge(&A::HS256, HS256, b"hello", true);
        assert!(detached.contains(".."));
        let v = verify_with(&detached, &opts).unwrap();
        assert_eq!(*v.payload, b"hello");
        let wrong = VerifyOptions::new(ALLOW_HS256)
            .unwrap()
            .detached_payload(b"hellO");
        assert_eq!(verify_with(&detached, &wrong), Err(Error::InvalidSignature));
    }

    #[test]
    fn empty_payload_part_without_detached_is_an_empty_payload() {
        // RFC 7515 §7.1: BASE64URL of the empty octet sequence is "".
        let empty = forge(&A::HS256, HS256, b"", false);
        let v = verify(&empty).unwrap();
        assert_eq!(*v.payload, b"");
        // A detached token's signature is over its real payload, not "".
        let detached = forge(&A::HS256, HS256, b"hello", true);
        assert_eq!(verify(&detached), Err(Error::InvalidSignature));
        // Detached mode with an empty supplied payload is the same token.
        let opts = VerifyOptions::new(ALLOW_HS256)
            .unwrap()
            .detached_payload(b"");
        assert_eq!(*verify_with(&empty, &opts).unwrap().payload, b"");
    }

    #[test]
    fn b64_false_payload_part_is_the_raw_octets() {
        // RFC 7797 §3, §5.2: no base64url decoding of the payload part.
        for payload in [
            &b"$02"[..],
            b"QQ",
            b"hello world",
            b" ~!",
            "\u{e9}".as_bytes(),
            b"",
        ] {
            let jws = forge(&A::HS256, HS256_B64_FALSE, payload, false);
            let v = verify(&jws).unwrap();
            assert_eq!(*v.payload, payload, "{jws}");
            assert_eq!(v.protected.unwrap().b64, Some(false));
        }
        // The same octets read as base64url would give another signing
        // input: "QQ" is not 0x41 here.
        let jws = forge(&A::HS256, HS256_B64_FALSE, b"QQ", false);
        assert_eq!(*verify(&jws).unwrap().payload, b"QQ");
    }

    #[test]
    fn b64_false_detached_rfc7797_section_4_2() {
        // RFC 7797 §4.2's header and payload "$.02", detached, with the
        // fake signature in place of the RFC's HMAC.
        let protected = "eyJhbGciOiJIUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19";
        let input = format!("{protected}.$.02");
        let sig = b64url_encode(&fake_signature(&A::HS256, input.as_bytes()));
        let jws = format!("{protected}..{sig}");
        let opts = VerifyOptions::new(ALLOW_HS256)
            .unwrap()
            .detached_payload(b"$.02");
        let v = verify_with(&jws, &opts).unwrap();
        assert_eq!(*v.payload, b"$.02");
        assert_eq!(v.alg, A::HS256);
        // The RFC's own token, with its real HMAC: well-formed through step
        // 8, rejected by the fake family at step 9.
        let rfc = format!("{protected}..A5dxf2s96_n5FLueVuW1Z_vh161FwXZC4YLPff6dmDY");
        assert_eq!(verify_with(&rfc, &opts), Err(Error::InvalidSignature));
    }

    #[test]
    fn rfc7515_a1_token_parses_and_keeps_the_crlf_header() {
        // RFC 7515 Appendix A.1: the header octets contain CRLF, so the
        // signing input must use the received encoding verbatim.
        let protected = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9";
        let payload_part = "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ";
        let rfc = format!("{protected}.{payload_part}.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk");
        assert_eq!(verify(&rfc), Err(Error::InvalidSignature));
        assert_eq!(
            verify_compact_with(
                &REJECTING,
                &rfc,
                &hs_key(),
                &VerifyOptions::new(ALLOW_HS256).unwrap()
            ),
            Err(Error::InvalidSignature)
        );
        let input = format!("{protected}.{payload_part}");
        let sig = b64url_encode(&fake_signature(&A::HS256, input.as_bytes()));
        let v = verify(&format!("{input}.{sig}")).unwrap();
        assert_eq!(v.protected.unwrap().typ.as_deref(), Some("JWT"));
        assert_eq!(
            *v.payload,
            b"{\"iss\":\"joe\",\r\n \"exp\":1300819380,\r\n \"http://example.com/is_root\":true}"
        );
    }

    /// RFC 7515 Appendix A.5: the Unsecured JWS, `{"alg":"none"}`.
    const A5_NONE: &str = "eyJhbGciOiJub25lIn0.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.";

    #[test]
    fn rfc7515_a5_none_is_never_allowed() {
        // RFC 8725 §3.1, ADR 0026 §2 step 7: whatever the list and key, and
        // whether or not the real families are used.
        let all: Vec<SigningAlg> = SigningAlg::KNOWN
            .iter()
            .filter(|a| **a != A::None)
            .cloned()
            .collect();
        let lists: [&[SigningAlg]; 3] = [ALLOW_HS256, &[A::RS256, A::ES256], &all];
        let keys = [hs_key(), keys::rsa(2048), keys::p256(""), keys::ed25519("")];
        let forged_sig = format!(
            "{}{}",
            A5_NONE,
            b64url_encode(&fake_signature(
                &A::None,
                A5_NONE.trim_end_matches('.').as_bytes()
            ))
        );
        for allowed in lists {
            let opts = VerifyOptions::new(allowed).unwrap();
            for key in &keys {
                for jws in [A5_NONE, forged_sig.as_str()] {
                    assert_eq!(
                        verify_compact(jws, key, &opts),
                        Err(Error::AlgorithmNotAllowed)
                    );
                    assert_eq!(
                        verify_compact_with(&FAKE, jws, key, &opts),
                        Err(Error::AlgorithmNotAllowed)
                    );
                }
            }
        }
    }

    #[test]
    fn steps_5_to_9_come_from_the_shared_rules() {
        let opts = VerifyOptions::new(ALLOW_HS256).unwrap();
        let code = |header: &str, key: &Jwk| {
            let jws = forge(&A::HS256, header, b"hi", false);
            verify_compact_with(&FAKE, &jws, key, &opts).map_or_else(|e| e.code(), |_| "ok")
        };
        let hs = hs_key();
        assert_eq!(
            code(r#"{"alg":"HS256","crit":["x-a"],"x-a":1}"#, &hs),
            "UnknownCritical"
        );
        assert_eq!(code(r#"{"alg":"HS1"}"#, &hs), "UnsupportedAlgorithm");
        assert_eq!(code(r#"{"alg":"HS384"}"#, &hs), "AlgorithmNotAllowed");
        assert_eq!(code(HS256, &keys::rsa(2048)), "KeyAlgorithmMismatch");
        assert_eq!(code(HS256, &keys::oct(31, "")), "InvalidKey");
        assert_eq!(code(HS256, &hs), "ok");
    }

    #[test]
    fn tampering_is_an_invalid_signature() {
        let jws = forge(&A::HS256, HS256, b"hello", false);
        let [p, _, s] = parts(&jws);
        let other_payload = format!("{p}.{}.{s}", b64url_encode(b"hellO"));
        let other_header = format!(
            "{}.{}.{s}",
            b64url_encode(br#"{"alg":"HS256","kid":"x"}"#),
            b64url_encode(b"hello")
        );
        let mut sig = crate::util::b64url_decode(&s).unwrap();
        sig[0] ^= 1;
        let other_sig = format!("{p}.{}.{}", b64url_encode(b"hello"), b64url_encode(&sig));
        let short_sig = format!("{p}.{}.", b64url_encode(b"hello"));
        for t in [other_payload, other_header, other_sig, short_sig] {
            assert_eq!(verify(&t), Err(Error::InvalidSignature), "{t}");
        }
        // REJECTING's verify fails a genuine signature too.
        assert_eq!(
            verify_compact_with(
                &REJECTING,
                &jws,
                &hs_key(),
                &VerifyOptions::new(ALLOW_HS256).unwrap()
            ),
            Err(Error::InvalidSignature)
        );
    }

    #[test]
    fn precedence_of_steps_1_to_4() {
        // ADR 0026 §2: the first failing step decides.
        let jws = forge(&A::HS256, HS256, b"hello", false);
        let [p, l, s] = parts(&jws);
        let bad_json = b64url_encode(br#"{"alg":"HS256""#);
        // Shape (2) before base64 (3).
        assert_eq!(verify_code(&format!("{p}=.{l}.{s}.x")), "InvalidFormat");
        // Detached mismatch (2) before base64 (3) and JSON (4).
        let opts = VerifyOptions::new(ALLOW_HS256)
            .unwrap()
            .detached_payload(b"hello");
        assert_eq!(
            verify_with(&format!("{bad_json}.{l}.{s}="), &opts).map_err(|e| e.code()),
            Err("InvalidFormat")
        );
        // The signature's base64 (3) before the header JSON (4).
        assert_eq!(
            verify_code(&format!("{bad_json}.{l}.{s}=")),
            "InvalidBase64"
        );
        // The payload part's base64 needs the header's b64 (RFC 7797 §3),
        // so an unparsable header (4) is reported before it.
        assert_eq!(verify_code(&format!("{bad_json}.{l}=.{s}")), "InvalidJson");
        // A parsable header: the payload's base64 (3) before the header
        // structure (4) and every later step.
        let no_alg = b64url_encode(br#"{"typ":"JWT"}"#);
        assert_eq!(verify_code(&format!("{no_alg}.{l}=.{s}")), "InvalidBase64");
        // Header structure (4) before crit (5) and the allow-list (7).
        let none_bad_crit = b64url_encode(br#"{"alg":"none","crit":["x-a"]}"#);
        assert_eq!(
            verify_code(&format!("{none_bad_crit}.{l}.{s}")),
            "InvalidHeader"
        );
    }

    // ---- Signing ----

    fn protected(json: &str) -> ProtectedHeader {
        ProtectedHeader::from_encoded(&b64url_encode(json.as_bytes())).unwrap()
    }

    fn sign(header_json: &str, payload: &[u8], detached: bool) -> Result<String> {
        let opts = SignOptions::new().detached(detached);
        sign_compact_with(&FAKE, &protected(header_json), payload, &hs_key(), &opts)
    }

    fn sign_code(header_json: &str, payload: &[u8], detached: bool) -> &'static str {
        sign(header_json, payload, detached).map_or_else(|e| e.code(), |_| "ok")
    }

    #[test]
    fn sign_emits_three_parts() {
        // RFC 7515 §5.1, §7.1: BASE64URL(header) '.' BASE64URL(payload) '.'
        // BASE64URL(signature), over the header's exact encoding.
        let jws = sign(HS256, b"hello", false).unwrap();
        assert_eq!(jws, forge(&A::HS256, HS256, b"hello", false));
        let [p, l, s] = parts(&jws);
        assert_eq!(p, b64url_encode(HS256.as_bytes()));
        assert_eq!(l, "aGVsbG8");
        let input = format!("{p}.{l}");
        assert_eq!(
            s,
            b64url_encode(&fake_signature(&A::HS256, input.as_bytes()))
        );
        // An empty payload has an empty part (RFC 7515 §7.1).
        assert_eq!(parts(&sign(HS256, b"", false).unwrap())[1], "");
    }

    #[test]
    fn sign_keeps_the_rfc7515_a1_header_encoding() {
        // RFC 7515 Appendix A.1: a header made by from_encoded is signed
        // with its CRLF octets, not re-serialized.
        let a1 = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9";
        let payload =
            b"{\"iss\":\"joe\",\r\n \"exp\":1300819380,\r\n \"http://example.com/is_root\":true}";
        let header = ProtectedHeader::from_encoded(a1).unwrap();
        let jws =
            sign_compact_with(&FAKE, &header, payload, &hs_key(), &SignOptions::new()).unwrap();
        let input = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ";
        let sig = b64url_encode(&fake_signature(&A::HS256, input.as_bytes()));
        assert_eq!(jws, format!("{input}.{sig}"));
    }

    #[test]
    fn sign_detached_emits_an_empty_payload_part() {
        // RFC 7515 Appendix F: header..signature, signed over the payload.
        let jws = sign(HS256, b"hello", true).unwrap();
        assert_eq!(jws, forge(&A::HS256, HS256, b"hello", true));
        let [p, l, _] = parts(&jws);
        assert_eq!(l, "");
        assert!(jws.starts_with(&format!("{p}..")));
        let opts = VerifyOptions::new(ALLOW_HS256)
            .unwrap()
            .detached_payload(b"hello");
        assert_eq!(*verify_with(&jws, &opts).unwrap().payload, b"hello");
    }

    #[test]
    fn sign_b64_false_attached_payload_rules() {
        // RFC 7797 §5.2, ADR 0026 §4: no '.', only %x20-7E.
        for payload in [
            &b"$.02"[..],
            b".",
            b"a\nb",
            b"\t",
            b"\x1f",
            b"\x7f",
            b"\x80",
            "\u{e9}".as_bytes(),
            b"\x00",
        ] {
            assert_eq!(
                sign_code(HS256_B64_FALSE, payload, false),
                "InvalidFormat",
                "{payload:?}"
            );
        }
        // The edges of the range are fine, and are carried unencoded.
        for payload in [&b"$02"[..], b" ", b"~", b" !~-_", b""] {
            let jws = sign(HS256_B64_FALSE, payload, false).unwrap();
            assert_eq!(jws, forge(&A::HS256, HS256_B64_FALSE, payload, false));
            assert_eq!(parts(&jws)[1].as_bytes(), payload);
            assert_eq!(*verify(&jws).unwrap().payload, payload);
        }
    }

    #[test]
    fn sign_b64_false_detached_rfc7797_section_4_2() {
        // RFC 7797 §4.2: "$.02" detached is allowed (§5.2 restricts only
        // attached payloads); any octets are, when detached.
        let header = ProtectedHeader::from_encoded(
            "eyJhbGciOiJIUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19",
        )
        .unwrap();
        let opts = SignOptions::new().detached(true);
        let jws = sign_compact_with(&FAKE, &header, b"$.02", &hs_key(), &opts).unwrap();
        let input = "eyJhbGciOiJIUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19.$.02";
        let sig = b64url_encode(&fake_signature(&A::HS256, input.as_bytes()));
        assert_eq!(
            jws,
            format!("eyJhbGciOiJIUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19..{sig}")
        );
        assert_eq!(sign_code(HS256_B64_FALSE, b"\x00\xff.\n", true), "ok");
    }

    #[test]
    fn sign_b64_must_be_critical() {
        // RFC 7797 §6, ADR 0026 §4: b64 not listed in crit is InvalidHeader,
        // whatever its value, attached or detached.
        for header in [
            r#"{"alg":"HS256","b64":false}"#,
            r#"{"alg":"HS256","b64":true}"#,
            r#"{"alg":"HS256","b64":false,"crit":["x-a"],"x-a":1}"#,
        ] {
            for detached in [false, true] {
                assert_eq!(
                    sign_code(header, b"$02", detached),
                    "InvalidHeader",
                    "{header}"
                );
            }
        }
        // Header rules come before the payload rules: no InvalidFormat for
        // "$.02" while b64 is not critical.
        assert_eq!(
            sign_code(r#"{"alg":"HS256","b64":false}"#, b"$.02", false),
            "InvalidHeader"
        );
        // b64: true listed in crit is the ordinary encoding (RFC 7797 §7
        // discourages it, but it is valid).
        let t = r#"{"alg":"HS256","b64":true,"crit":["b64"]}"#;
        assert_eq!(parts(&sign(t, b"$.02", false).unwrap())[1], "JC4wMg");
    }

    #[test]
    fn sign_policy_errors() {
        // ADR 0026 §2 steps 4-8 through process::prepare_sign.
        assert_eq!(sign_code(r#"{"typ":"JWT"}"#, b"x", false), "InvalidHeader");
        assert_eq!(
            sign_code(r#"{"alg":"HS256","crit":["x-a"],"x-a":1}"#, b"x", false),
            "UnknownCritical"
        );
        assert_eq!(
            sign_code(r#"{"alg":"HS1"}"#, b"x", false),
            "UnsupportedAlgorithm"
        );
        // RFC 8725 §3.2: never produce `none`.
        assert_eq!(
            sign_code(r#"{"alg":"none"}"#, b"x", false),
            "AlgorithmNotAllowed"
        );
        // ADR 0021: no RSA signing.
        assert_eq!(
            sign_code(r#"{"alg":"RS256"}"#, b"x", false),
            "UnsupportedAlgorithm"
        );
        assert_eq!(sign_code(r#"{"alg":"HS512"}"#, b"x", false), "InvalidKey");
        let opts = SignOptions::new();
        let es = protected(r#"{"alg":"ES256"}"#);
        assert_eq!(
            sign_compact_with(&FAKE, &es, b"x", &keys::p256(""), &opts),
            Err(Error::KeyAlgorithmMismatch)
        );
        assert_eq!(
            sign_compact_with(&FAKE, &es, b"x", &hs_key(), &opts),
            Err(Error::KeyAlgorithmMismatch)
        );
    }

    #[test]
    fn sign_verify_round_trip() {
        // Sign, then verify, through the shared rules with the fake family.
        let cases = [
            (
                A::HS256,
                r#"{"alg":"HS256","kid":"k1"}"#,
                keys::oct(32, ""),
                keys::oct(32, ""),
            ),
            (
                A::HS512,
                r#"{"alg":"HS512"}"#,
                keys::oct(64, ""),
                keys::oct(64, ""),
            ),
            (
                A::ES256,
                r#"{"alg":"ES256","typ":"JWT"}"#,
                keys::p256_private(""),
                keys::p256(""),
            ),
            (
                A::EdDSA,
                r#"{"alg":"EdDSA"}"#,
                keys::ed25519_private(""),
                keys::ed25519(""),
            ),
            (
                A::Ed25519,
                r#"{"alg":"Ed25519"}"#,
                keys::ed25519_private(""),
                keys::ed25519(""),
            ),
        ];
        for (alg, header_json, private, public) in cases {
            let allowed = [alg.clone()];
            for (payload, detached, b64_false) in [
                (&b"hello"[..], false, false),
                (b"", false, false),
                (b"\x00\xff binary", false, false),
                (b"\x00\xff binary", true, false),
                (b"$02", false, true),
                (b"$.02", true, true),
            ] {
                let json = if b64_false {
                    header_json.replacen('}', r#","b64":false,"crit":["b64"]}"#, 1)
                } else {
                    header_json.to_owned()
                };
                let header = protected(&json);
                let opts = SignOptions::new().detached(detached);
                let jws = sign_compact_with(&FAKE, &header, payload, &private, &opts).unwrap();
                let mut vopts = VerifyOptions::new(&allowed).unwrap();
                if detached {
                    vopts = vopts.detached_payload(payload);
                }
                let v = verify_compact_with(&FAKE, &jws, &public, &vopts).unwrap();
                assert_eq!(v.alg, alg);
                assert_eq!(v.protected.as_ref(), Some(header.header()));
                assert_eq!(v.unprotected, None);
                assert_eq!(*v.payload, payload);
                assert_eq!(v.signature_index, 0);
            }
        }
    }

    // ---- Edge cases ----

    #[test]
    fn max_input_len_does_not_count_the_detached_payload() {
        // ADR 0026 §7: the limit is on the serialized JWS.
        let payload = vec![b'a'; 4096];
        let jws = forge(&A::HS256, HS256, &payload, true);
        let opts = VerifyOptions::new(ALLOW_HS256)
            .unwrap()
            .detached_payload(&payload)
            .max_input_len(jws.len());
        assert_eq!(*verify_with(&jws, &opts).unwrap().payload, payload);
    }

    #[test]
    fn the_received_header_encoding_is_signed() {
        // RFC 7515 §5.2 step 8 recomputes the input from the received
        // parts: the same JSON with other octets is another signing input.
        let jws = forge(&A::HS256, HS256, b"hello", false);
        let [_, l, s] = parts(&jws);
        let respaced = b64url_encode(br#"{ "alg":"HS256"}"#);
        assert_eq!(
            verify(&format!("{respaced}.{l}.{s}")),
            Err(Error::InvalidSignature)
        );
        // Changing b64 changes the input, even for the same payload part.
        let b64_false = forge(&A::HS256, HS256_B64_FALSE, b"aGVsbG8", false);
        let [p, _, _] = parts(&b64_false);
        assert_eq!(
            verify(&format!("{p}.{l}.{s}")),
            Err(Error::InvalidSignature)
        );
    }

    #[test]
    fn b64_of_the_wrong_type_is_invalid_header() {
        // RFC 7797 §3: b64 is a boolean.
        for header in [
            r#"{"alg":"HS256","b64":"false","crit":["b64"]}"#,
            r#"{"alg":"HS256","b64":0,"crit":["b64"]}"#,
        ] {
            let jws = format!("{}.$02.", b64url_encode(header.as_bytes()));
            assert_eq!(verify_code(&jws), "InvalidHeader", "{header}");
        }
    }

    #[test]
    fn errors_carry_no_input() {
        // ADR 0007: error text never contains token, payload or header
        // octets.
        const MARKER: &str = "MARKERxyz";
        let marker_b64 = b64url_encode(MARKER.as_bytes());
        let header_b64 = b64url_encode(format!(r#"{{"alg":"HS256","x":"{MARKER}"}}"#).as_bytes());
        let detached = VerifyOptions::new(ALLOW_HS256)
            .unwrap()
            .detached_payload(MARKER.as_bytes());
        let cases = [
            (format!("{MARKER}.{MARKER}"), None),
            (format!("{MARKER}.{MARKER}.{MARKER}"), None),
            (format!("{header_b64}.{marker_b64}.{MARKER}="), None),
            (format!("{marker_b64}.{marker_b64}."), None),
            (format!("{header_b64}.{marker_b64}."), None),
            (format!("{header_b64}.{marker_b64}."), Some(detached)),
        ];
        for (jws, opts) in cases {
            let opts = opts.unwrap_or_else(|| VerifyOptions::new(ALLOW_HS256).unwrap());
            let err = verify_with(&jws, &opts).unwrap_err();
            for text in [err.to_string(), format!("{err:?}")] {
                assert!(!text.contains(MARKER), "{text}");
                assert!(!text.contains(&marker_b64), "{text}");
            }
        }
        let err = sign(HS256_B64_FALSE, format!("{MARKER}.\n").as_bytes(), false).unwrap_err();
        assert!(!err.to_string().contains(MARKER));
    }

    // ---- The split: precheck_compact (steps 1-7), finish_compact (8-9) ----

    use crate::test_counters::{jws_family_signs as signs, jws_family_verifies as verifies};

    /// [`FAKE`], counting every call into the family (ADR 0026 §2 step 9,
    /// and `sign`, which verification must never reach).
    const COUNTING: Families = Families {
        sign: |alg, key, input| {
            signs::tick();
            (FAKE.sign)(alg, key, input)
        },
        verify: |alg, key, input, signature| {
            verifies::tick();
            (FAKE.verify)(alg, key, input, signature)
        },
    };

    /// Runs `f`, returning its result and the number of family `sign` and
    /// `verify` calls it made on this thread.
    fn family_calls<R>(f: impl FnOnce() -> R) -> (R, u64, u64) {
        let ((result, verify_calls), sign_calls) = signs::count(|| verifies::count(f));
        (result, sign_calls, verify_calls)
    }

    /// An `oct` key of 32 octets other than [`hs_key`]'s.
    fn other_hs_key() -> Jwk {
        keys::jwk(&format!(
            r#"{{"kty":"oct","k":"{}"}}"#,
            b64url_encode(&[0x33; 32])
        ))
    }

    /// One token per failure class of ADR 0026 §2 / ADR 0048 steps 1-7,
    /// with the options it fails under and its expected code.
    fn step_1_to_7_failures() -> Vec<(String, VerifyOptions<'static>, &'static str)> {
        let jws = forge(&A::HS256, HS256, b"hello", false);
        let [p, l, s] = parts(&jws);
        let opts = VerifyOptions::new(ALLOW_HS256).unwrap();
        let header = |json: &str| forge(&A::HS256, json, b"hi", false);
        let no_alg = b64url_encode(br#"{"typ":"JWT"}"#);
        let bad_json = b64url_encode(br#"{"alg":"HS256""#);
        let detached = opts.detached_payload(b"hello");
        vec![
            // Step 1: the limit, the shape, the detached mode.
            (
                jws.clone(),
                opts.max_input_len(jws.len() - 1),
                "InvalidFormat",
            ),
            ("a.b".to_owned(), opts, "InvalidFormat"),
            (format!("{jws}.{s}"), opts, "InvalidFormat"),
            (jws.clone(), detached, "InvalidFormat"),
            // Step 2: the signature's base64url.
            (format!("{p}.{l}.{s}="), opts, "InvalidBase64"),
            // Step 3: the protected header's base64url, JSON, types, crit.
            (format!("{p}=.{l}.{s}"), opts, "InvalidBase64"),
            (format!("{bad_json}.{l}.{s}"), opts, "InvalidJson"),
            (
                header(r#"{"alg":"HS256","alg":"HS256"}"#),
                opts,
                "InvalidJson",
            ),
            (header(r#"{"alg":1}"#), opts, "InvalidHeader"),
            (
                header(r#"{"alg":"HS256","crit":[]}"#),
                opts,
                "InvalidHeader",
            ),
            (
                format!(
                    "{}.$02.",
                    b64url_encode(br#"{"alg":"HS256","b64":0,"crit":["b64"]}"#)
                ),
                opts,
                "InvalidHeader",
            ),
            // Step 4: the payload's base64url.
            (format!("{p}.{l}=.{s}"), opts, "InvalidBase64"),
            (format!("{no_alg}.{l}=.{s}"), opts, "InvalidBase64"),
            // Step 5 (ADR 0048): the whole-header structure.
            (header(r#"{"typ":"JWT"}"#), opts, "InvalidHeader"),
            (
                header(r#"{"alg":"HS256","b64":false}"#),
                opts,
                "InvalidHeader",
            ),
            (
                header(r#"{"alg":"HS256","crit":["x-a"]}"#),
                opts,
                "InvalidHeader",
            ),
            // ADR 0026 §2 steps 5-7.
            (
                header(r#"{"alg":"HS256","crit":["x-a"],"x-a":1}"#),
                opts,
                "UnknownCritical",
            ),
            (header(r#"{"alg":"HS1"}"#), opts, "UnsupportedAlgorithm"),
            (header(r#"{"alg":"HS384"}"#), opts, "AlgorithmNotAllowed"),
            (A5_NONE.to_owned(), opts, "AlgorithmNotAllowed"),
        ]
    }

    #[test]
    fn precheck_gives_verify_compacts_error_for_each_step_1_to_7() {
        // The first failing step decides (ADR 0026 §2, ADR 0048), whether
        // it runs alone or inside verify_compact, whatever the key.
        let candidate_keys = [hs_key(), keys::p384(), keys::p256(""), keys::ed25519("")];
        for (jws, opts, code) in step_1_to_7_failures() {
            let (pre, sign_calls, verify_calls) = family_calls(|| precheck_compact(&jws, &opts));
            let err = pre.map(drop).unwrap_err();
            assert_eq!(err.code(), code, "{jws}");
            assert_eq!((sign_calls, verify_calls), (0, 0), "{jws}");
            for key in &candidate_keys {
                assert_eq!(verify_compact(&jws, key, &opts), Err(err.clone()), "{jws}");
                assert_eq!(
                    verify_compact_with(&COUNTING, &jws, key, &opts),
                    Err(err.clone()),
                    "{jws}"
                );
            }
        }
    }

    #[test]
    fn step_8_and_9_failures_pass_precheck_and_fail_in_finish() {
        // ADR 0026 §2 steps 8-9 need a key, so precheck_compact accepts the
        // token and finish_compact gives verify_compact's code.
        let opts = VerifyOptions::new(ALLOW_HS256).unwrap();
        let good = forge(&A::HS256, HS256, b"hello", false);
        let [p, _, s] = parts(&good);
        let tampered = format!("{p}.{}.{s}", b64url_encode(b"hellO"));
        let detached = forge(&A::HS256, HS256, b"hello", true);
        let wrong_detached = opts.detached_payload(b"hellO");
        let cases: [(&str, VerifyOptions<'_>, Jwk, &str, u64); 8] = [
            // Step 8: key binding, before any signature check.
            (&good, opts, keys::ed25519(""), "KeyAlgorithmMismatch", 0),
            (&good, opts, keys::p256(""), "KeyAlgorithmMismatch", 0),
            (
                &good,
                opts,
                keys::oct(32, r#","alg":"HS512""#),
                "KeyAlgorithmMismatch",
                0,
            ),
            (
                &good,
                opts,
                keys::oct(32, r#","use":"enc""#),
                "KeyAlgorithmMismatch",
                0,
            ),
            (
                &good,
                opts,
                keys::oct(32, r#","key_ops":["sign"]"#),
                "KeyAlgorithmMismatch",
                0,
            ),
            (&good, opts, keys::oct(31, ""), "InvalidKey", 0),
            // Step 9: the signature.
            (&tampered, opts, hs_key(), "InvalidSignature", 1),
            (&detached, wrong_detached, hs_key(), "InvalidSignature", 1),
        ];
        for (jws, opts, key, code, expected_verifies) in cases {
            let (pre, _, verify_calls) = family_calls(|| precheck_compact(jws, &opts));
            assert_eq!(verify_calls, 0);
            let pre = pre.unwrap();
            let (finished, sign_calls, verify_calls) =
                family_calls(|| finish_compact(&COUNTING, &pre, &key));
            let err = finished.unwrap_err();
            assert_eq!(err.code(), code, "{jws} {code}");
            assert_eq!((sign_calls, verify_calls), (0, expected_verifies), "{code}");
            assert_eq!(verify_compact_with(&COUNTING, jws, &key, &opts), Err(err));
        }
    }

    #[test]
    fn finish_matches_verify_compact_on_success() {
        // Every attached, detached and b64:false shape: the same Verified.
        let b64_false = forge(&A::HS256, HS256_B64_FALSE, b"$02", false);
        let rfc7797_detached = forge(&A::HS256, HS256_B64_FALSE, b"$.02", true);
        let attached = forge(
            &A::HS256,
            r#"{"alg":"HS256","typ":"JWT","kid":"k1"}"#,
            b"hi",
            false,
        );
        let detached = forge(&A::HS256, HS256, b"\x00\xff", true);
        let empty = forge(&A::HS256, HS256, b"", false);
        let opts = VerifyOptions::new(ALLOW_HS256).unwrap();
        for (jws, opts) in [
            (&attached, opts),
            (&empty, opts),
            (&b64_false, opts),
            (&detached, opts.detached_payload(b"\x00\xff")),
            (&rfc7797_detached, opts.detached_payload(b"$.02")),
        ] {
            let pre = precheck_compact(jws, &opts).unwrap();
            let (v, sign_calls, verify_calls) =
                family_calls(|| finish_compact(&COUNTING, &pre, &hs_key()));
            assert_eq!((sign_calls, verify_calls), (0, 1));
            assert_eq!(
                v,
                verify_compact_with(&FAKE, jws, &hs_key(), &opts),
                "{jws}"
            );
        }
    }

    #[test]
    fn one_precheck_finishes_against_several_keys() {
        // ADR 0027 §9, ADR 0029 §1: steps 1-7 once, then steps 8-9 per
        // candidate, here with the real HMAC (RFC 7518 §3.2).
        let right = hs_key();
        let header = protected(r#"{"alg":"HS256","typ":"JWT","kid":"k1"}"#);
        let jws = sign_compact(&header, b"payload", &right, &SignOptions::new()).unwrap();
        let opts = VerifyOptions::new(&[A::HS256, A::ES256]).unwrap();
        let pre = precheck_compact(&jws, &opts).unwrap();
        // What the JWT layer reads between steps 7 and 8 (ADR 0049 §2:
        // only from the protected header).
        assert_eq!(pre.alg(), &A::HS256);
        assert_eq!(pre.header(), header.header());
        assert_eq!(pre.header().kid.as_deref(), Some("k1"));
        assert_eq!(pre.header().typ.as_deref(), Some("JWT"));
        let expected = verify_compact(&jws, &right, &opts).unwrap();
        assert_eq!(
            finish_compact(&FAMILIES, &pre, &keys::p256("")),
            Err(Error::KeyAlgorithmMismatch)
        );
        assert_eq!(
            finish_compact(&FAMILIES, &pre, &other_hs_key()),
            Err(Error::InvalidSignature)
        );
        assert_eq!(
            finish_compact(&FAMILIES, &pre, &right),
            Ok(expected.clone())
        );
        // Finishing again, and after another failure, changes nothing.
        assert_eq!(
            finish_compact(&FAMILIES, &pre, &other_hs_key()),
            Err(Error::InvalidSignature)
        );
        assert_eq!(finish_compact(&FAMILIES, &pre, &right), Ok(expected));
    }

    #[test]
    fn precheck_holds_the_payload_wiped_or_borrowed() {
        // ADR 0049 §4: a decoded payload and the signing input are
        // `Zeroizing` inside the precheck; a b64:false or detached payload
        // is borrowed from the caller, never copied before verification.
        let opts = VerifyOptions::new(ALLOW_HS256).unwrap();
        let jws = forge(&A::HS256, HS256, b"secret", false);
        let pre = precheck_compact(&jws, &opts).unwrap();
        let _: &Zeroizing<Vec<u8>> = &pre.signing_input;
        match &pre.payload {
            PrecheckedPayload::Decoded(decoded) => {
                let decoded: &Zeroizing<Vec<u8>> = decoded;
                assert_eq!(**decoded, b"secret");
            }
            PrecheckedPayload::Borrowed(_) => panic!("a b64 payload must be decoded"),
        }
        let unencoded = forge(&A::HS256, HS256_B64_FALSE, b"$02", false);
        let pre = precheck_compact(&unencoded, &opts).unwrap();
        let [_, part, _] = parts(&unencoded);
        assert!(
            matches!(pre.payload, PrecheckedPayload::Borrowed(b) if b == part.as_bytes()
                && unencoded.as_bytes().as_ptr_range().contains(&b.as_ptr()))
        );
        let content = b"detached".to_vec();
        let detached = forge(&A::HS256, HS256, &content, true);
        let with_content = opts.detached_payload(&content);
        let pre = precheck_compact(&detached, &with_content).unwrap();
        assert!(
            matches!(pre.payload, PrecheckedPayload::Borrowed(b) if core::ptr::eq(b, &content[..]))
        );
        // The copy into Verified is the only one, and it is wiped too.
        let v = finish_compact(&FAKE, &pre, &hs_key()).unwrap();
        let _: &Zeroizing<Vec<u8>> = &v.payload;
        assert_eq!(*v.payload, content);
    }

    #[test]
    fn precheck_debug_prints_no_payload_or_signature_bytes() {
        // ADR 0049 §4, ADR 0007: lengths only; headers through Header's
        // redacting Debug.
        const MARKER: &[u8] = b"MARKERxyz-payload";
        let opts = VerifyOptions::new(ALLOW_HS256).unwrap();
        let attached = forge(&A::HS256, HS256, MARKER, false);
        let unencoded = forge(&A::HS256, HS256_B64_FALSE, MARKER, false);
        let detached = forge(&A::HS256, HS256, MARKER, true);
        for (jws, opts) in [
            (&attached, opts),
            (&unencoded, opts),
            (&detached, opts.detached_payload(MARKER)),
        ] {
            let pre = precheck_compact(jws, &opts).unwrap();
            let text = format!("{pre:?}");
            let [_, _, s] = parts(jws);
            let signature = crate::util::b64url_decode(&s).unwrap();
            for secret in [
                "MARKER".to_owned(),
                b64url_encode(MARKER),
                format!("{MARKER:?}"),
                s.clone(),
                format!("{:?}", &signature[..4])
                    .trim_end_matches(']')
                    .to_owned(),
            ] {
                assert!(!text.contains(&secret), "{text} contains {secret}");
            }
            assert!(text.contains("payload_len: 17"), "{text}");
            assert!(text.contains("signature_len: 32"), "{text}");
            assert!(text.contains("HS256"), "{text}");
        }
    }

    #[test]
    fn public_functions_use_the_real_families() {
        // Only outcomes decided before any family runs, so these hold
        // whatever T06-T09 implement.
        let opts = VerifyOptions::new(ALLOW_HS256).unwrap();
        assert_eq!(
            verify_compact("a.b", &hs_key(), &opts).map_err(|e| e.code()),
            Err("InvalidFormat")
        );
        let sign_opts = SignOptions::new();
        assert_eq!(
            sign_compact(&protected(r#"{"alg":"none"}"#), b"x", &hs_key(), &sign_opts),
            Err(Error::AlgorithmNotAllowed)
        );
        assert_eq!(
            sign_compact(
                &protected(r#"{"alg":"RS256"}"#),
                b"x",
                &keys::rsa(2048),
                &sign_opts
            ),
            Err(Error::UnsupportedAlgorithm)
        );
        assert_eq!(
            sign_compact(&protected(HS256_B64_FALSE), b"$.02", &hs_key(), &sign_opts)
                .map_err(|e| e.code()),
            Err("InvalidFormat")
        );
    }
}