1use std::error::Error as StdError;
2use std::fmt;
3use std::result;
4use std::sync::Arc;
56/// A crate private constructor for `Error`.
7pub(crate) fn new_error(kind: ErrorKind) -> Error {
8 Error(Box::new(kind))
9}
1011/// A type alias for `Result<T, jsonwebtoken::errors::Error>`.
12pub type Result<T> = result::Result<T, Error>;
1314/// An error that can occur when encoding/decoding JWTs
15#[derive(Clone, Debug, Eq, PartialEq)]
16pub struct Error(Box<ErrorKind>);
1718impl Error {
19/// Return the specific type of this error.
20pub fn kind(&self) -> &ErrorKind {
21&self.0
22}
2324/// Unwrap this error into its underlying type.
25pub fn into_kind(self) -> ErrorKind {
26*self.0
27}
28}
2930/// The specific type of an error.
31///
32/// This enum may grow additional variants, the `#[non_exhaustive]`
33/// attribute makes sure clients don't count on exhaustive matching.
34/// (Otherwise, adding a new variant could break existing code.)
35#[non_exhaustive]
36#[derive(Clone, Debug)]
37pub enum ErrorKind {
38/// When a token doesn't have a valid JWT shape
39InvalidToken,
40/// When the signature doesn't match
41InvalidSignature,
42/// When the secret given is not a valid ECDSA key
43InvalidEcdsaKey,
44/// When the secret given is not a valid RSA key
45InvalidRsaKey(String),
46/// We could not sign with the given key
47RsaFailedSigning,
48/// When the algorithm from string doesn't match the one passed to `from_str`
49InvalidAlgorithmName,
50/// When a key is provided with an invalid format
51InvalidKeyFormat,
5253// Validation errors
54/// When a claim required by the validation is not present
55MissingRequiredClaim(String),
56/// When a token’s `exp` claim indicates that it has expired
57ExpiredSignature,
58/// When a token’s `iss` claim does not match the expected issuer
59InvalidIssuer,
60/// When a token’s `aud` claim does not match one of the expected audience values
61InvalidAudience,
62/// When a token’s `sub` claim does not match one of the expected subject values
63InvalidSubject,
64/// When a token’s `nbf` claim represents a time in the future
65ImmatureSignature,
66/// When the algorithm in the header doesn't match the one passed to `decode` or the encoding/decoding key
67 /// used doesn't match the alg requested
68InvalidAlgorithm,
69/// When the Validation struct does not contain at least 1 algorithm
70MissingAlgorithm,
7172// 3rd party errors
73/// An error happened when decoding some base64 text
74Base64(base64::DecodeError),
75/// An error happened while serializing/deserializing JSON
76Json(Arc<serde_json::Error>),
77/// Some of the text was invalid UTF-8
78Utf8(::std::string::FromUtf8Error),
79/// Something unspecified went wrong with crypto
80Crypto(::ring::error::Unspecified),
81}
8283impl StdError for Error {
84fn cause(&self) -> Option<&dyn StdError> {
85match &*self.0 {
86 ErrorKind::InvalidToken => None,
87 ErrorKind::InvalidSignature => None,
88 ErrorKind::InvalidEcdsaKey => None,
89 ErrorKind::RsaFailedSigning => None,
90 ErrorKind::InvalidRsaKey(_) => None,
91 ErrorKind::ExpiredSignature => None,
92 ErrorKind::MissingAlgorithm => None,
93 ErrorKind::MissingRequiredClaim(_) => None,
94 ErrorKind::InvalidIssuer => None,
95 ErrorKind::InvalidAudience => None,
96 ErrorKind::InvalidSubject => None,
97 ErrorKind::ImmatureSignature => None,
98 ErrorKind::InvalidAlgorithm => None,
99 ErrorKind::InvalidAlgorithmName => None,
100 ErrorKind::InvalidKeyFormat => None,
101 ErrorKind::Base64(err) => Some(err),
102 ErrorKind::Json(err) => Some(err.as_ref()),
103 ErrorKind::Utf8(err) => Some(err),
104 ErrorKind::Crypto(err) => Some(err),
105 }
106 }
107}
108109impl fmt::Display for Error {
110fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111match &*self.0 {
112 ErrorKind::InvalidToken
113 | ErrorKind::InvalidSignature
114 | ErrorKind::InvalidEcdsaKey
115 | ErrorKind::ExpiredSignature
116 | ErrorKind::RsaFailedSigning
117 | ErrorKind::MissingAlgorithm
118 | ErrorKind::InvalidIssuer
119 | ErrorKind::InvalidAudience
120 | ErrorKind::InvalidSubject
121 | ErrorKind::ImmatureSignature
122 | ErrorKind::InvalidAlgorithm
123 | ErrorKind::InvalidKeyFormat
124 | ErrorKind::InvalidAlgorithmName => write!(f, "{:?}", self.0),
125 ErrorKind::MissingRequiredClaim(c) => write!(f, "Missing required claim: {}", c),
126 ErrorKind::InvalidRsaKey(msg) => write!(f, "RSA key invalid: {}", msg),
127 ErrorKind::Json(err) => write!(f, "JSON error: {}", err),
128 ErrorKind::Utf8(err) => write!(f, "UTF-8 error: {}", err),
129 ErrorKind::Crypto(err) => write!(f, "Crypto error: {}", err),
130 ErrorKind::Base64(err) => write!(f, "Base64 error: {}", err),
131 }
132 }
133}
134135impl PartialEq for ErrorKind {
136fn eq(&self, other: &Self) -> bool {
137format!("{:?}", self) == format!("{:?}", other)
138 }
139}
140141// Equality of ErrorKind is an equivalence relation: it is reflexive, symmetric and transitive.
142impl Eq for ErrorKind {}
143144impl From<base64::DecodeError> for Error {
145fn from(err: base64::DecodeError) -> Error {
146 new_error(ErrorKind::Base64(err))
147 }
148}
149150impl From<serde_json::Error> for Error {
151fn from(err: serde_json::Error) -> Error {
152 new_error(ErrorKind::Json(Arc::new(err)))
153 }
154}
155156impl From<::std::string::FromUtf8Error> for Error {
157fn from(err: ::std::string::FromUtf8Error) -> Error {
158 new_error(ErrorKind::Utf8(err))
159 }
160}
161162impl From<::ring::error::Unspecified> for Error {
163fn from(err: ::ring::error::Unspecified) -> Error {
164 new_error(ErrorKind::Crypto(err))
165 }
166}
167168impl From<::ring::error::KeyRejected> for Error {
169fn from(_err: ::ring::error::KeyRejected) -> Error {
170 new_error(ErrorKind::InvalidEcdsaKey)
171 }
172}
173174impl From<ErrorKind> for Error {
175fn from(kind: ErrorKind) -> Error {
176 new_error(kind)
177 }
178}
179180#[cfg(test)]
181mod tests {
182use wasm_bindgen_test::wasm_bindgen_test;
183184use super::*;
185186#[test]
187 #[wasm_bindgen_test]
188fn test_error_rendering() {
189assert_eq!(
190"InvalidAlgorithmName",
191 Error::from(ErrorKind::InvalidAlgorithmName).to_string()
192 );
193 }
194}