jsonwebtoken/
errors.rs

1use std::error::Error as StdError;
2use std::fmt;
3use std::result;
4use std::sync::Arc;
5
6/// A crate private constructor for `Error`.
7pub(crate) fn new_error(kind: ErrorKind) -> Error {
8    Error(Box::new(kind))
9}
10
11/// A type alias for `Result<T, jsonwebtoken::errors::Error>`.
12pub type Result<T> = result::Result<T, Error>;
13
14/// An error that can occur when encoding/decoding JWTs
15#[derive(Clone, Debug, Eq, PartialEq)]
16pub struct Error(Box<ErrorKind>);
17
18impl Error {
19    /// Return the specific type of this error.
20    pub fn kind(&self) -> &ErrorKind {
21        &self.0
22    }
23
24    /// Unwrap this error into its underlying type.
25    pub fn into_kind(self) -> ErrorKind {
26        *self.0
27    }
28}
29
30/// 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
39    InvalidToken,
40    /// When the signature doesn't match
41    InvalidSignature,
42    /// When the secret given is not a valid ECDSA key
43    InvalidEcdsaKey,
44    /// When the secret given is not a valid EdDSA key
45    InvalidEddsaKey,
46    /// When the secret given is not a valid RSA key
47    InvalidRsaKey(String),
48    /// We could not sign with the given key
49    RsaFailedSigning,
50    /// When the algorithm from string doesn't match the one passed to `from_str`
51    InvalidAlgorithmName,
52    /// When a key is provided with an invalid format
53    InvalidKeyFormat,
54
55    // Validation errors
56    /// When a claim required by the validation is not present
57    MissingRequiredClaim(String),
58    /// When a token’s `exp` claim indicates that it has expired
59    ExpiredSignature,
60    /// When a token’s `iss` claim does not match the expected issuer
61    InvalidIssuer,
62    /// When a token’s `aud` claim does not match one of the expected audience values
63    InvalidAudience,
64    /// When a token’s `sub` claim does not match one of the expected subject values
65    InvalidSubject,
66    /// When a token’s `nbf` claim represents a time in the future
67    ImmatureSignature,
68    /// When the algorithm in the header doesn't match the one passed to `decode` or the encoding/decoding key
69    /// used doesn't match the alg requested
70    InvalidAlgorithm,
71    /// When the Validation struct does not contain at least 1 algorithm
72    MissingAlgorithm,
73
74    // 3rd party errors
75    /// An error happened when decoding some base64 text
76    Base64(base64::DecodeError),
77    /// An error happened while serializing/deserializing JSON
78    Json(Arc<serde_json::Error>),
79    /// Some of the text was invalid UTF-8
80    Utf8(::std::string::FromUtf8Error),
81}
82
83impl StdError for Error {
84    fn cause(&self) -> Option<&dyn StdError> {
85        match &*self.0 {
86            ErrorKind::InvalidToken => None,
87            ErrorKind::InvalidSignature => None,
88            ErrorKind::InvalidEcdsaKey => None,
89            ErrorKind::InvalidEddsaKey => None,
90            ErrorKind::RsaFailedSigning => None,
91            ErrorKind::InvalidRsaKey(_) => None,
92            ErrorKind::ExpiredSignature => None,
93            ErrorKind::MissingAlgorithm => None,
94            ErrorKind::MissingRequiredClaim(_) => None,
95            ErrorKind::InvalidIssuer => None,
96            ErrorKind::InvalidAudience => None,
97            ErrorKind::InvalidSubject => None,
98            ErrorKind::ImmatureSignature => None,
99            ErrorKind::InvalidAlgorithm => None,
100            ErrorKind::InvalidAlgorithmName => None,
101            ErrorKind::InvalidKeyFormat => None,
102            ErrorKind::Base64(err) => Some(err),
103            ErrorKind::Json(err) => Some(err.as_ref()),
104            ErrorKind::Utf8(err) => Some(err),
105        }
106    }
107}
108
109impl fmt::Display for Error {
110    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111        match &*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::InvalidEddsaKey
125            | ErrorKind::InvalidAlgorithmName => write!(f, "{:?}", self.0),
126            ErrorKind::MissingRequiredClaim(c) => write!(f, "Missing required claim: {}", c),
127            ErrorKind::InvalidRsaKey(msg) => write!(f, "RSA key invalid: {}", msg),
128            ErrorKind::Json(err) => write!(f, "JSON error: {}", err),
129            ErrorKind::Utf8(err) => write!(f, "UTF-8 error: {}", err),
130            ErrorKind::Base64(err) => write!(f, "Base64 error: {}", err),
131        }
132    }
133}
134
135impl PartialEq for ErrorKind {
136    fn eq(&self, other: &Self) -> bool {
137        format!("{:?}", self) == format!("{:?}", other)
138    }
139}
140
141// Equality of ErrorKind is an equivalence relation: it is reflexive, symmetric and transitive.
142impl Eq for ErrorKind {}
143
144impl From<base64::DecodeError> for Error {
145    fn from(err: base64::DecodeError) -> Error {
146        new_error(ErrorKind::Base64(err))
147    }
148}
149
150impl From<serde_json::Error> for Error {
151    fn from(err: serde_json::Error) -> Error {
152        new_error(ErrorKind::Json(Arc::new(err)))
153    }
154}
155
156impl From<::std::string::FromUtf8Error> for Error {
157    fn from(err: ::std::string::FromUtf8Error) -> Error {
158        new_error(ErrorKind::Utf8(err))
159    }
160}
161
162impl From<ErrorKind> for Error {
163    fn from(kind: ErrorKind) -> Error {
164        new_error(kind)
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use wasm_bindgen_test::wasm_bindgen_test;
171
172    use super::*;
173
174    #[test]
175    #[wasm_bindgen_test]
176    fn test_error_rendering() {
177        assert_eq!(
178            "InvalidAlgorithmName",
179            Error::from(ErrorKind::InvalidAlgorithmName).to_string()
180        );
181    }
182}