surrealdb_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 RSA key
45    InvalidRsaKey(String),
46    /// We could not sign with the given key
47    RsaFailedSigning,
48    /// When the algorithm from string doesn't match the one passed to `from_str`
49    InvalidAlgorithmName,
50    /// When a key is provided with an invalid format
51    InvalidKeyFormat,
52
53    // Validation errors
54    /// When a claim required by the validation is not present
55    MissingRequiredClaim(String),
56    /// When a token’s `exp` claim indicates that it has expired
57    ExpiredSignature,
58    /// When a token’s `iss` claim does not match the expected issuer
59    InvalidIssuer,
60    /// When a token’s `aud` claim does not match one of the expected audience values
61    InvalidAudience,
62    /// When a token’s `sub` claim does not match one of the expected subject values
63    InvalidSubject,
64    /// When a token’s `nbf` claim represents a time in the future
65    ImmatureSignature,
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
68    InvalidAlgorithm,
69    /// When the Validation struct does not contain at least 1 algorithm
70    MissingAlgorithm,
71
72    // 3rd party errors
73    /// An error happened when decoding some base64 text
74    Base64(base64::DecodeError),
75    /// An error happened while serializing/deserializing JSON
76    Json(Arc<serde_json::Error>),
77    /// Some of the text was invalid UTF-8
78    Utf8(::std::string::FromUtf8Error),
79    /// Something unspecified went wrong with crypto
80    #[cfg(not(target_arch = "wasm32"))]
81    Crypto(::ring::error::Unspecified),
82}
83
84impl StdError for Error {
85    fn cause(&self) -> Option<&dyn StdError> {
86        match &*self.0 {
87            ErrorKind::InvalidToken => None,
88            ErrorKind::InvalidSignature => None,
89            ErrorKind::InvalidEcdsaKey => 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            #[cfg(not(target_arch = "wasm32"))]
106            ErrorKind::Crypto(err) => Some(err),
107        }
108    }
109}
110
111impl fmt::Display for Error {
112    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
113        match &*self.0 {
114            ErrorKind::InvalidToken
115            | ErrorKind::InvalidSignature
116            | ErrorKind::InvalidEcdsaKey
117            | ErrorKind::ExpiredSignature
118            | ErrorKind::RsaFailedSigning
119            | ErrorKind::MissingAlgorithm
120            | ErrorKind::InvalidIssuer
121            | ErrorKind::InvalidAudience
122            | ErrorKind::InvalidSubject
123            | ErrorKind::ImmatureSignature
124            | ErrorKind::InvalidAlgorithm
125            | ErrorKind::InvalidKeyFormat
126            | ErrorKind::InvalidAlgorithmName => write!(f, "{:?}", self.0),
127            ErrorKind::MissingRequiredClaim(c) => write!(f, "Missing required claim: {}", c),
128            ErrorKind::InvalidRsaKey(msg) => write!(f, "RSA key invalid: {}", msg),
129            ErrorKind::Json(err) => write!(f, "JSON error: {}", err),
130            ErrorKind::Utf8(err) => write!(f, "UTF-8 error: {}", err),
131            #[cfg(not(target_arch = "wasm32"))]
132            ErrorKind::Crypto(err) => write!(f, "Crypto error: {}", err),
133            ErrorKind::Base64(err) => write!(f, "Base64 error: {}", err),
134        }
135    }
136}
137
138impl PartialEq for ErrorKind {
139    fn eq(&self, other: &Self) -> bool {
140        format!("{:?}", self) == format!("{:?}", other)
141    }
142}
143
144// Equality of ErrorKind is an equivalence relation: it is reflexive, symmetric and transitive.
145impl Eq for ErrorKind {}
146
147impl From<base64::DecodeError> for Error {
148    fn from(err: base64::DecodeError) -> Error {
149        new_error(ErrorKind::Base64(err))
150    }
151}
152
153impl From<serde_json::Error> for Error {
154    fn from(err: serde_json::Error) -> Error {
155        new_error(ErrorKind::Json(Arc::new(err)))
156    }
157}
158
159impl From<::std::string::FromUtf8Error> for Error {
160    fn from(err: ::std::string::FromUtf8Error) -> Error {
161        new_error(ErrorKind::Utf8(err))
162    }
163}
164
165#[cfg(not(target_arch = "wasm32"))]
166impl From<::ring::error::Unspecified> for Error {
167    fn from(err: ::ring::error::Unspecified) -> Error {
168        new_error(ErrorKind::Crypto(err))
169    }
170}
171
172#[cfg(not(target_arch = "wasm32"))]
173impl From<::ring::error::KeyRejected> for Error {
174    fn from(_err: ::ring::error::KeyRejected) -> Error {
175        new_error(ErrorKind::InvalidEcdsaKey)
176    }
177}
178
179impl From<ErrorKind> for Error {
180    fn from(kind: ErrorKind) -> Error {
181        new_error(kind)
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    #[test]
190    fn test_error_rendering() {
191        assert_eq!(
192            "InvalidAlgorithmName",
193            Error::from(ErrorKind::InvalidAlgorithmName).to_string()
194        );
195    }
196}