navajo 0.0.4

cryptographic APIs
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
use core::{array::TryFromSliceError, time::Duration};

use alloc::{
    boxed::Box,
    fmt::{self, Debug, Display},
    format,
    string::{String, ToString},
};

#[cfg(feature = "std")]
pub use std::error::Error;

#[cfg(not(feature = "std"))]
pub trait Error: Debug + Display {}

#[cfg(not(feature = "std"))]
impl<T> Error for T where T: Display + Debug {}

use crate::jose::{NumericDate, StringOrStrings};

#[derive(Debug)]
pub struct RandomError(pub rand_core::Error);

impl RandomError {
    pub fn new(inner: rand_core::Error) -> Self {
        Self(inner)
    }
    pub fn inner(&self) -> &rand_core::Error {
        &self.0
    }
    pub fn take_inner(self) -> rand_core::Error {
        self.0
    }
}
#[cfg(feature = "std")]
impl Error for RandomError {}

impl core::fmt::Display for RandomError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "error generating random bytes\n\ncaused by: {}", self.0)
    }
}

impl From<RandomError> for rand_core::Error {
    fn from(err: RandomError) -> Self {
        err.0
    }
}

impl From<rand_core::Error> for RandomError {
    fn from(err: rand_core::Error) -> Self {
        Self(err)
    }
}

#[derive(Debug, Clone, Copy)]
pub struct KeyDisabledError(pub u32);
impl Display for KeyDisabledError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "key is disabled: {}", self.0)
    }
}

#[derive(Debug, Clone)]
pub enum KeyNotFoundError {
    Key(u32),
    PubId(String),
}
#[cfg(feature = "std")]
impl Error for KeyNotFoundError {}
impl From<u32> for KeyNotFoundError {
    fn from(key: u32) -> Self {
        Self::Key(key)
    }
}
impl KeyNotFoundError {
    fn id_string(&self) -> String {
        match self {
            KeyNotFoundError::Key(id) => id.to_string(),
            KeyNotFoundError::PubId(id) => id.to_string(),
        }
    }
}
impl fmt::Display for KeyNotFoundError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "missing key: {}", self.id_string())
    }
}

#[derive(Clone, Debug)]
pub struct UnspecifiedError;

#[cfg(feature = "std")]
impl Error for UnspecifiedError {}

#[cfg(feature = "ring")]
impl From<ring::error::Unspecified> for UnspecifiedError {
    fn from(_: ring::error::Unspecified) -> Self {
        Self
    }
}

impl fmt::Display for UnspecifiedError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "unspecified error")
    }
}

#[derive(Clone, Debug)]
pub struct SegmentLimitExceededError;
impl core::fmt::Display for SegmentLimitExceededError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "counter limit exceeded")
    }
}

#[cfg(feature = "std")]
impl Error for SegmentLimitExceededError {}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum EncryptDeterministicallyError {
    Unspecified,
    EmptyPlaintext,
    PlaintextTooLong,
}

#[cfg(feature = "std")]
impl Error for EncryptDeterministicallyError {}
impl Display for EncryptDeterministicallyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unspecified => fmt::Display::fmt(&UnspecifiedError, f),
            Self::EmptyPlaintext => write!(f, "plaintext is empty"),
            Self::PlaintextTooLong => write!(f, "plaintext is too long"),
        }
    }
}
impl From<UnspecifiedError> for EncryptDeterministicallyError {
    fn from(_: UnspecifiedError) -> Self {
        Self::Unspecified
    }
}

#[derive(Clone, Debug)]
pub enum EncryptError {
    Unspecified,
    SegmentLimitExceeded,
    EmptyPlaintext,
}

#[cfg(feature = "std")]
impl Error for EncryptError {}

impl fmt::Display for EncryptError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unspecified => fmt::Display::fmt(&UnspecifiedError, f),
            Self::SegmentLimitExceeded => fmt::Display::fmt(&SegmentLimitExceededError, f),
            Self::EmptyPlaintext => write!(f, "plaintext is empty"),
        }
    }
}

impl From<aes_gcm::Error> for EncryptError {
    fn from(_: aes_gcm::Error) -> Self {
        Self::Unspecified
    }
}

impl From<SegmentLimitExceededError> for EncryptError {
    fn from(_: SegmentLimitExceededError) -> Self {
        Self::SegmentLimitExceeded
    }
}

#[cfg(feature = "std")]
impl From<EncryptError> for std::io::Error {
    fn from(e: EncryptError) -> Self {
        Self::new(std::io::ErrorKind::Other, e)
    }
}

impl From<UnspecifiedError> for EncryptError {
    fn from(_: UnspecifiedError) -> Self {
        Self::Unspecified
    }
}
#[cfg(feature = "ring")]
impl From<ring::error::Unspecified> for EncryptError {
    fn from(_: ring::error::Unspecified) -> Self {
        Self::Unspecified
    }
}

pub enum EncryptTryStreamError<E> {
    Encrypt(EncryptError),
    Upstream(E),
}
#[cfg(feature = "std")]
impl<E> Error for EncryptTryStreamError<E> where E: std::error::Error {}

impl<E> core::fmt::Debug for EncryptTryStreamError<E>
where
    E: core::fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Encrypt(e) => write!(f, "EncryptError({e:?})"),
            Self::Upstream(e) => write!(f, "Upstream({e:?})"),
        }
    }
}
impl<E> From<EncryptError> for EncryptTryStreamError<E> {
    fn from(e: EncryptError) -> Self {
        Self::Encrypt(e)
    }
}
impl<E> core::fmt::Display for EncryptTryStreamError<E>
where
    E: core::fmt::Display,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Encrypt(e) => core::fmt::Display::fmt(e, f),
            Self::Upstream(e) => core::fmt::Display::fmt(e, f),
        }
    }
}

#[derive(Debug, Clone)]
pub enum DecryptError {
    /// The underlying cryptography library, *ring* returned an unspecified error.
    Unspecified,
    /// The keyset does not contain the key used to encrypt the ciphertext
    KeyNotFound(KeyNotFoundError),
    SegmentLimitExceeded,
    EmptyCiphertext,
    DisabledKey(KeyDisabledError),
}

#[cfg(feature = "std")]
impl Error for DecryptError {}

impl From<KeyNotFoundError> for DecryptError {
    fn from(e: KeyNotFoundError) -> Self {
        Self::KeyNotFound(e)
    }
}
impl From<SegmentLimitExceededError> for DecryptError {
    fn from(_: SegmentLimitExceededError) -> Self {
        Self::SegmentLimitExceeded
    }
}
#[cfg(feature = "std")]
impl From<DecryptError> for std::io::Error {
    fn from(e: DecryptError) -> Self {
        Self::new(std::io::ErrorKind::Other, e)
    }
}

impl From<MalformedError> for DecryptError {
    fn from(_: MalformedError) -> Self {
        Self::Unspecified
    }
}

impl From<rust_crypto_aead::Error> for DecryptError {
    fn from(_: rust_crypto_aead::Error) -> Self {
        Self::Unspecified
    }
}
impl fmt::Display for DecryptError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unspecified => fmt::Display::fmt(&UnspecifiedError, f),
            Self::KeyNotFound(e) => fmt::Display::fmt(e, f),
            Self::SegmentLimitExceeded => fmt::Display::fmt(&SegmentLimitExceededError, f),
            Self::EmptyCiphertext => write!(f, "ciphertext must not be empty"),
            Self::DisabledKey(e) => fmt::Display::fmt(e, f),
        }
    }
}

impl From<UnspecifiedError> for DecryptError {
    fn from(_e: UnspecifiedError) -> Self {
        Self::Unspecified
    }
}
#[cfg(feature = "ring")]
impl From<ring::error::Unspecified> for DecryptError {
    fn from(_: ring::error::Unspecified) -> Self {
        Self::Unspecified
    }
}

#[derive(Debug, Clone)]
pub enum DecryptDeterministicallyError {
    /// The underlying cryptography library, *ring* returned an unspecified error.
    Unspecified,
    /// The keyset does not contain the key used to encrypt the ciphertext
    KeyNotFound(KeyNotFoundError),
    SegmentLimitExceeded,
    EmptyCiphertext,
    DisabledKey(KeyDisabledError),
    CiphertextTooShort,
}

#[cfg(feature = "std")]
impl Error for DecryptDeterministicallyError {}

impl From<KeyNotFoundError> for DecryptDeterministicallyError {
    fn from(e: KeyNotFoundError) -> Self {
        Self::KeyNotFound(e)
    }
}
impl From<SegmentLimitExceededError> for DecryptDeterministicallyError {
    fn from(_: SegmentLimitExceededError) -> Self {
        Self::SegmentLimitExceeded
    }
}
#[cfg(feature = "std")]
impl From<DecryptDeterministicallyError> for std::io::Error {
    fn from(e: DecryptDeterministicallyError) -> Self {
        Self::new(std::io::ErrorKind::Other, e)
    }
}

impl From<MalformedError> for DecryptDeterministicallyError {
    fn from(_: MalformedError) -> Self {
        Self::Unspecified
    }
}

impl From<rust_crypto_aead::Error> for DecryptDeterministicallyError {
    fn from(_: rust_crypto_aead::Error) -> Self {
        Self::Unspecified
    }
}
impl fmt::Display for DecryptDeterministicallyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unspecified => fmt::Display::fmt(&UnspecifiedError, f),
            Self::KeyNotFound(e) => fmt::Display::fmt(e, f),
            Self::SegmentLimitExceeded => fmt::Display::fmt(&SegmentLimitExceededError, f),
            Self::EmptyCiphertext => write!(f, "ciphertext must not be empty"),
            Self::DisabledKey(e) => fmt::Display::fmt(e, f),
            Self::CiphertextTooShort => write!(f, "cleartext is too short"),
        }
    }
}

impl From<UnspecifiedError> for DecryptDeterministicallyError {
    fn from(_e: UnspecifiedError) -> Self {
        Self::Unspecified
    }
}

pub enum DecryptStreamError<E> {
    Decrypt(DecryptError),
    Upstream(E),
}
#[cfg(feature = "std")]
impl<E> Error for DecryptStreamError<E> where E: std::error::Error {}
impl<E> Debug for DecryptStreamError<E>
where
    E: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Decrypt(e) => write!(f, "DecryptError({e:?})"),
            Self::Upstream(e) => write!(f, "Upstream({e:?})"),
        }
    }
}
impl<E> From<DecryptError> for DecryptStreamError<E> {
    fn from(e: DecryptError) -> Self {
        Self::Decrypt(e)
    }
}
impl<E> core::fmt::Display for DecryptStreamError<E>
where
    E: core::fmt::Display,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Decrypt(e) => core::fmt::Display::fmt(e, f),
            Self::Upstream(e) => core::fmt::Display::fmt(e, f),
        }
    }
}

#[derive(Debug)]
pub struct MalformedError(Box<dyn Error>);

impl From<base64::DecodeError> for MalformedError {
    fn from(e: base64::DecodeError) -> Self {
        Self(Box::new(e))
    }
}
impl From<serde_json::Error> for MalformedError {
    fn from(e: serde_json::Error) -> Self {
        Self(Box::new(e))
    }
}

impl From<&'static str> for MalformedError {
    fn from(s: &'static str) -> Self {
        #[cfg(feature = "std")]
        {
            s.into()
        }
        #[cfg(not(feature = "std"))]
        {
            Self(Box::new(s))
        }
    }
}

impl From<String> for MalformedError {
    fn from(s: String) -> Self {
        #[cfg(feature = "std")]
        {
            s.into()
        }
        #[cfg(not(feature = "std"))]
        {
            Self(Box::new(s))
        }
    }
}

impl fmt::Display for MalformedError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "malformed data: {}", &self.0)
    }
}

#[derive(Clone, Debug)]
pub struct InvalidAlgorithmError(pub String);

#[cfg(feature = "std")]
impl Error for InvalidAlgorithmError {}

impl fmt::Display for InvalidAlgorithmError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid or unsupported algorithm: \"{}\"", self.0)
    }
}

impl From<String> for InvalidAlgorithmError {
    fn from(v: String) -> Self {
        Self(v)
    }
}
impl From<&str> for InvalidAlgorithmError {
    fn from(v: &str) -> Self {
        Self(v.to_string())
    }
}

#[derive(Debug)]
pub enum TruncationError {
    NotTruncatable(String),
    LengthExceeded,
    MinLengthNotMet,
}

#[cfg(feature = "std")]
impl Error for TruncationError {}

impl Display for TruncationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotTruncatable(alg) => {
                write!(f, "truncation not supported for algorithm {alg}")
            }
            Self::LengthExceeded => write!(f, "truncation length exceeded"),
            Self::MinLengthNotMet => write!(f, "truncation min length not met"),
        }
    }
}
#[cfg(feature = "std")]
#[derive(Debug)]
pub enum MacVerificationReadError {
    MacVerificationError,
    IoError(std::io::Error),
}
#[cfg(feature = "std")]
impl Error for MacVerificationError {}

#[cfg(feature = "std")]
impl core::fmt::Display for MacVerificationReadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::MacVerificationError => write!(f, "MAC verification failed"),
            Self::IoError(e) => write!(f, "io error: {e}"),
        }
    }
}
#[cfg(feature = "std")]
impl From<std::io::Error> for MacVerificationReadError {
    fn from(e: std::io::Error) -> Self {
        Self::IoError(e)
    }
}
#[cfg(feature = "std")]
impl From<MacVerificationError> for MacVerificationReadError {
    fn from(_: MacVerificationError) -> Self {
        Self::MacVerificationError
    }
}

#[cfg(feature = "std")]
impl std::error::Error for MacVerificationReadError {}

#[derive(Debug, Clone)]
pub struct MacVerificationError;
impl fmt::Display for MacVerificationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MAC verification failed")
    }
}

impl From<UnspecifiedError> for MacVerificationError {
    fn from(_: UnspecifiedError) -> Self {
        Self {}
    }
}

#[derive(Debug)]
pub struct SealError(pub String);

#[cfg(feature = "std")]
impl Error for SealError {}

impl fmt::Display for SealError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "failed to seal:\n\ncaused by:\n\t{}", self.0)
    }
}
impl From<String> for SealError {
    fn from(e: String) -> Self {
        Self(e)
    }
}

impl From<&str> for SealError {
    fn from(e: &str) -> Self {
        Self(e.to_string())
    }
}

impl From<serde_json::Error> for SealError {
    fn from(e: serde_json::Error) -> Self {
        Self(e.to_string())
    }
}

impl From<chacha20poly1305::Error> for SealError {
    fn from(e: chacha20poly1305::Error) -> Self {
        Self(e.to_string())
    }
}

#[derive(Debug)]
pub struct OpenError(pub String);

#[cfg(feature = "std")]
impl Error for OpenError {}

impl fmt::Display for OpenError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "failed to open:\n\ncaused by:\n\t{}", self.0)
    }
}

impl From<String> for OpenError {
    fn from(e: String) -> Self {
        Self(e)
    }
}
impl From<miniz_oxide::inflate::DecompressError> for OpenError {
    fn from(e: miniz_oxide::inflate::DecompressError) -> Self {
        Self(e.to_string())
    }
}

impl From<&str> for OpenError {
    fn from(e: &str) -> Self {
        Self(e.to_string())
    }
}

impl From<serde_json::Error> for OpenError {
    fn from(e: serde_json::Error) -> Self {
        Self(e.to_string())
    }
}

impl From<aes_gcm::Error> for OpenError {
    fn from(_: aes_gcm::Error) -> Self {
        Self("error decrypting keyring".to_string())
    }
}
impl From<crypto_common::InvalidLength> for OpenError {
    fn from(e: crypto_common::InvalidLength) -> Self {
        Self(e.to_string())
    }
}

#[derive(Debug, Clone)]
pub enum RemoveKeyError {
    IsPrimaryKey(u32),
    KeyNotFound(KeyNotFoundError),
}

impl fmt::Display for RemoveKeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IsPrimaryKey(_) => write!(f, "cannot remove primary key"),
            Self::KeyNotFound(e) => fmt::Display::fmt(e, f),
        }
    }
}

#[cfg(any(feature = "aead", feature = "daead", feature = "mac", feature = "dsa"))]
impl From<KeyNotFoundError> for RemoveKeyError {
    fn from(e: KeyNotFoundError) -> Self {
        Self::KeyNotFound(e)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for RemoveKeyError {}

#[derive(Debug, Clone)]
pub enum DisableKeyError {
    IsPrimaryKey(u32),
    KeyNotFound(KeyNotFoundError),
}
impl fmt::Display for DisableKeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IsPrimaryKey(_) => write!(f, "cannot disable primary key"),
            Self::KeyNotFound(e) => fmt::Display::fmt(e, f),
        }
    }
}
impl From<KeyNotFoundError> for DisableKeyError {
    fn from(e: KeyNotFoundError) -> Self {
        Self::KeyNotFound(e)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for DisableKeyError {}

pub enum VerifyStreamError<E> {
    Upstream(E),
    FailedVerification,
}
impl<E> core::fmt::Debug for VerifyStreamError<E>
where
    E: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Upstream(e) => write!(f, "VerifyStreamError::Upstream({e:?})"),
            Self::FailedVerification => write!(f, "VerifyStreamError::FailedVerification"),
        }
    }
}
impl<E> core::fmt::Display for VerifyStreamError<E>
where
    E: Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Upstream(e) => write!(f, "failed to verify stream due to upstream error;\n\t{e}"),
            Self::FailedVerification => write!(f, "failed to verify stream"),
        }
    }
}
#[cfg(feature = "std")]
impl<E> std::error::Error for VerifyStreamError<E> where E: std::error::Error {}

impl<E> From<MacVerificationError> for VerifyStreamError<E> {
    fn from(_: MacVerificationError) -> Self {
        Self::FailedVerification
    }
}

#[derive(Clone, Debug)]
pub struct InvalidLengthError;

#[cfg(feature = "std")]
impl Error for InvalidLengthError {}

impl Display for InvalidLengthError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "invalid length")
    }
}

#[cfg(feature = "ring")]
impl From<ring::error::Unspecified> for InvalidLengthError {
    fn from(_: ring::error::Unspecified) -> Self {
        Self {}
    }
}

impl From<rust_crypto_hkdf::InvalidLength> for InvalidLengthError {
    fn from(_: rust_crypto_hkdf::InvalidLength) -> Self {
        Self {}
    }
}

pub struct KeyError(pub String);

#[cfg(feature = "std")]
impl Error for KeyError {}

impl fmt::Display for KeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "malformed key: {}", self.0)
    }
}
impl fmt::Debug for KeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "malformed key: {}", self.0)
    }
}

impl From<String> for KeyError {
    fn from(e: String) -> Self {
        Self(e)
    }
}
impl From<&str> for KeyError {
    fn from(e: &str) -> Self {
        Self(e.to_string())
    }
}
#[cfg(feature = "ring")]
impl From<ring::error::KeyRejected> for KeyError {
    fn from(e: ring::error::KeyRejected) -> Self {
        Self(e.to_string())
    }
}
#[cfg(feature = "p256")]
impl From<pkcs8::Error> for KeyError {
    fn from(e: pkcs8::Error) -> Self {
        Self(e.to_string())
    }
}
impl From<TryFromSliceError> for KeyError {
    fn from(e: TryFromSliceError) -> Self {
        Self(format!("invalid key length: {e}"))
    }
}
impl From<digest::InvalidLength> for KeyError {
    fn from(e: digest::InvalidLength) -> Self {
        Self(format!("invalid key length: {e}"))
    }
}
#[cfg(feature = "ed25519")]
impl From<ed25519_dalek::SignatureError> for KeyError {
    fn from(e: ed25519_dalek::SignatureError) -> Self {
        Self(e.to_string())
    }
}
#[cfg(feature = "signature")]
impl From<signature::Error> for SignatureError {
    fn from(e: signature::Error) -> Self {
        Self::Failure(e.to_string())
    }
}

impl From<elliptic_curve::Error> for KeyError {
    fn from(e: elliptic_curve::Error) -> Self {
        Self(e.to_string())
    }
}

impl From<sec1::Error> for KeyError {
    fn from(e: sec1::Error) -> Self {
        Self(e.to_string())
    }
}
#[derive(Debug, Clone)]
pub enum SignatureError {
    KeyNotFound(String),
    Failure(String),
    InvalidLen(usize),
}

#[cfg(feature = "std")]
impl Error for SignatureError {}

impl Display for SignatureError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SignatureError::KeyNotFound(id) => write!(f, "missing key: {id}"),
            SignatureError::Failure(id) => {
                write!(f, "verification failed: {id}")
            }
            SignatureError::InvalidLen(len) => {
                write!(f, "invalid signature len: {len}")
            }
        }
    }
}
#[cfg(feature = "ring")]
impl From<ring::error::Unspecified> for SignatureError {
    fn from(_: ring::error::Unspecified) -> Self {
        Self::Failure("unspecified error occurred".to_string())
    }
}

#[derive(Debug)]
pub enum TokenError {
    Signature(SignatureError),
    Validation(TokenValidationError),
    Json(serde_json::Error),
    Malformed,
}
impl From<DecodeError> for TokenError {
    fn from(e: DecodeError) -> Self {
        match e {
            DecodeError::Serde(e) => Self::Json(e),
            DecodeError::Base64(_) => Self::Malformed,
            DecodeError::Malformed(_) => Self::Malformed,
        }
    }
}
#[cfg(feature = "std")]
impl Error for TokenError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Signature(e) => Some(e),
            Self::Validation(e) => Some(e),
            Self::Json(e) => Some(e),
            Self::Malformed => None,
        }
    }
}

impl From<serde_json::Error> for TokenError {
    fn from(e: serde_json::Error) -> Self {
        Self::Json(e)
    }
}

impl From<SignatureError> for TokenError {
    fn from(e: SignatureError) -> Self {
        Self::Signature(e)
    }
}
impl From<MalformedError> for TokenError {
    fn from(_: MalformedError) -> Self {
        Self::Malformed
    }
}

impl Display for TokenError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TokenError::Signature(e) => write!(f, "signature error: {e}"),
            TokenError::Validation(e) => write!(f, "validation error: {e}"),
            TokenError::Malformed => write!(f, "malformed jws"),
            TokenError::Json(e) => write!(f, "json error: {e}"),
        }
    }
}

impl From<base64::DecodeError> for TokenError {
    fn from(_: base64::DecodeError) -> Self {
        Self::Malformed
    }
}
impl From<TokenValidationError> for TokenError {
    fn from(e: TokenValidationError) -> Self {
        Self::Validation(e)
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct DuplicatePubIdError(pub String);

impl Display for DuplicatePubIdError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "duplicate pub id: {}", self.0)
    }
}

#[cfg(feature = "std")]
impl Error for DuplicatePubIdError {}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct InvalidCurveError(pub String);

impl Display for InvalidCurveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid EllipticCurve: {}", self.0)
    }
}

#[cfg(feature = "std")]
impl Error for InvalidCurveError {}

#[derive(Debug)]
pub enum DecodeError {
    Serde(serde_json::Error),
    Base64(base64::DecodeError),
    Malformed(String),
}

impl From<&str> for DecodeError {
    fn from(e: &str) -> Self {
        Self::Malformed(e.to_string())
    }
}
impl Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DecodeError::Serde(e) => write!(f, "serde: {e}"),
            DecodeError::Base64(e) => write!(f, "base64: {e}"),
            DecodeError::Malformed(e) => write!(f, "malformed: {e}"),
        }
    }
}

#[cfg(feature = "std")]
impl Error for DecodeError {}
impl From<serde_json::Error> for DecodeError {
    fn from(e: serde_json::Error) -> Self {
        Self::Serde(e)
    }
}
impl From<base64::DecodeError> for DecodeError {
    fn from(e: base64::DecodeError) -> Self {
        Self::Base64(e)
    }
}

#[derive(Debug, Clone)]
pub enum InvalidNumericDateError {
    InvalidTimestamp(i64),
    OutOfRange(u64),
    #[cfg(feature = "std")]
    SystemTime(std::time::SystemTimeError),
}

impl Display for InvalidNumericDateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            InvalidNumericDateError::InvalidTimestamp(i) => {
                write!(f, "invalid timestamp: {i}")
            }
            InvalidNumericDateError::OutOfRange(u) => {
                write!(f, "timestamp out of range: {u}")
            }
            #[cfg(feature = "std")]
            InvalidNumericDateError::SystemTime(e) => {
                write!(f, "system time error: {e}",)
            }
        }
    }
}
#[cfg(feature = "std")]
impl From<std::time::SystemTimeError> for InvalidNumericDateError {
    fn from(e: std::time::SystemTimeError) -> Self {
        Self::SystemTime(e)
    }
}
impl From<u64> for InvalidNumericDateError {
    fn from(u: u64) -> Self {
        Self::OutOfRange(u)
    }
}
impl From<i64> for InvalidNumericDateError {
    fn from(e: i64) -> Self {
        Self::InvalidTimestamp(e)
    }
}

#[cfg(feature = "std")]
impl Error for InvalidNumericDateError {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenAudienceError {
    pub expected_audience: Option<String>,
    pub actual: Option<StringOrStrings>,
}

impl Display for TokenAudienceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.expected_audience {
            Some(aud) => write!(f, "audience \"{aud}\" not present"),
            None => write!(f, "error: audience present but not expected"),
        }
    }
}

#[cfg(feature = "std")]
impl Error for TokenAudienceError {}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TokenExpiredError {
    pub expiration_time: NumericDate,
    pub now: NumericDate,
    pub clock_skew: Duration,
}

impl Display for TokenExpiredError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "token is expired")
    }
}

#[cfg(feature = "std")]
impl Error for TokenExpiredError {}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TokenIssuerError {
    pub expected_issuer: Option<String>,
    pub actual: Option<String>,
}

#[cfg(feature = "std")]
impl Error for TokenIssuerError {}

impl Display for TokenIssuerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.expected_issuer {
            Some(iss) => match &self.actual {
                Some(actual) => write!(f, "expected issuer \"{iss}\", got \"{actual}\""),
                None => write!(f, "expected issuer \"{iss}\" but not present"),
            },
            None => write!(f, "issuer present but not expected"),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TokenNotYetValidError {
    pub not_before: NumericDate,
    pub now: NumericDate,
    pub clock_skew: Duration,
}

impl Display for TokenNotYetValidError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "token is not yet valid")
    }
}

#[cfg(feature = "std")]
impl Error for TokenNotYetValidError {}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TokenIssuedAtInFutureError {
    pub issued_at: NumericDate,
    pub now: NumericDate,
    pub clock_skew: Duration,
}

#[cfg(feature = "std")]
impl Error for TokenIssuedAtInFutureError {}

impl Display for TokenIssuedAtInFutureError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "token was issued in the future")
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum TokenValidationError {
    Audience(TokenAudienceError),
    Issuer(TokenIssuerError),
    Expired(TokenExpiredError),
    MissingExpiration,
    NotYetValid(TokenNotYetValidError),
    IssuedAtInFuture(TokenIssuedAtInFutureError),
}
impl Display for TokenValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TokenValidationError::Audience(err) => core::fmt::Display::fmt(err, f),
            TokenValidationError::MissingExpiration => write!(f, "token is missing an exp claim"),
            TokenValidationError::Expired(err) => core::fmt::Display::fmt(err, f),
            TokenValidationError::NotYetValid(err) => core::fmt::Display::fmt(err, f),
            TokenValidationError::IssuedAtInFuture(err) => core::fmt::Display::fmt(err, f),
            TokenValidationError::Issuer(err) => core::fmt::Display::fmt(err, f),
        }
    }
}

impl From<TokenAudienceError> for TokenValidationError {
    fn from(e: TokenAudienceError) -> Self {
        Self::Audience(e)
    }
}

impl From<TokenIssuerError> for TokenValidationError {
    fn from(e: TokenIssuerError) -> Self {
        Self::Issuer(e)
    }
}

impl From<TokenExpiredError> for TokenValidationError {
    fn from(e: TokenExpiredError) -> Self {
        Self::Expired(e)
    }
}

impl From<TokenNotYetValidError> for TokenValidationError {
    fn from(e: TokenNotYetValidError) -> Self {
        Self::NotYetValid(e)
    }
}

impl From<TokenIssuedAtInFutureError> for TokenValidationError {
    fn from(e: TokenIssuedAtInFutureError) -> Self {
        Self::IssuedAtInFuture(e)
    }
}

#[cfg(feature = "std")]
impl Error for TokenValidationError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            TokenValidationError::Audience(err) => Some(err),
            TokenValidationError::MissingExpiration => None,
            TokenValidationError::Expired(err) => Some(err),
            TokenValidationError::NotYetValid(err) => Some(err),
            TokenValidationError::IssuedAtInFuture(err) => Some(err),
            TokenValidationError::Issuer(err) => Some(err),
        }
    }
}