Skip to main content

jwt_compact_preview/
error.rs

1use thiserror::Error;
2
3/// Errors that may occur during token parsing.
4#[derive(Debug, Error)]
5pub enum ParseError {
6    /// Token has invalid structure.
7    ///
8    /// Valid tokens must consist of 3 base64url-encoded parts (header, claims, and signature)
9    /// separated by periods.
10    #[error("Invalid token structure")]
11    InvalidTokenStructure,
12
13    /// Cannot decode base64.
14    #[error("base64 decoding error: {}", _0)]
15    Base64(#[from] base64::DecodeError),
16
17    /// Token header cannot be parsed.
18    #[error("Malformed token header: {}", _0)]
19    MalformedHeader(#[source] serde_json::Error),
20
21    /// [Content type][cty] mentioned in the token header is not supported.
22    ///
23    /// Supported content types are JSON (used by default) and CBOR.
24    ///
25    /// [cty]: https://tools.ietf.org/html/rfc7515#section-4.1.10
26    #[error("Unsupported content type: {}", _0)]
27    UnsupportedContentType(String),
28}
29
30/// Errors that can occur during token validation.
31#[derive(Debug, Error)]
32pub enum ValidationError {
33    /// Algorithm mentioned in the token header differs from invoked one.
34    #[error("Token algorithm differs from the expected one")]
35    AlgorithmMismatch,
36
37    /// Token signature is malformed (e.g., has an incorrect length).
38    #[error("Malformed token signature: {}", _0)]
39    MalformedSignature(#[source] anyhow::Error),
40
41    /// Token signature has failed verification.
42    #[error("Signature has failed verification")]
43    InvalidSignature,
44
45    /// Token claims cannot be deserialized from JSON.
46    #[error("Cannot deserialize claims: {}", _0)]
47    MalformedClaims(#[source] serde_json::Error),
48
49    /// Token claims cannot be deserialized from CBOR.
50    #[error("Cannot deserialize claims: {}", _0)]
51    MalformedCborClaims(#[source] serde_cbor::error::Error),
52
53    /// Claim requested during validation is not present in the token.
54    #[error("Claim requested during validation is not present in the token")]
55    NoClaim,
56
57    /// Token has expired.
58    #[error("Token has expired")]
59    Expired,
60
61    /// Token is not yet valid as per `nbf` claim.
62    #[error("Token is not yet ready")]
63    NotMature,
64}
65
66/// Errors that can occur during token creation.
67#[derive(Debug, Error)]
68pub enum CreationError {
69    /// Token header cannot be serialized.
70    #[error("Cannot serialize header: {}", _0)]
71    Header(#[source] serde_json::Error),
72
73    /// Token claims cannot be serialized into JSON.
74    #[error("Cannot serialize claims: {}", _0)]
75    Claims(#[source] serde_json::Error),
76
77    /// Token claims cannot be serialized into CBOR.
78    #[error("Cannot serialize claims into CBOR: {}", _0)]
79    CborClaims(#[source] serde_cbor::error::Error),
80}