small_jwt 1.1.0

Simple and small JWT libary
Documentation
pub type Result<T> = std::result::Result<T, Error>;

/// Crate level error.
/// Supplies both user-level single error and inner dependency errors.
#[derive(Debug)]
pub enum Error {
    /// `token.split('.')` is less than 3 parts.
    InvalidTokenLength,
    /// Token signature is not the same as `Alg(header.payload, secret)`.
    InvalidTokenSignature,

    /// `serde_json::Error` error wrapper.
    SerdeJsonError(serde_json::Error),
    /// `hmac::digest::InvalidLength` error wrapper.
    SignError(hmac::digest::InvalidLength),
    /// `base64::DecodeError` error wrapper.
    B64DecodeError(base64::DecodeError),
    /// `std::string::FromUtf8Error` error wrapper.
    FromUtf8Error(std::string::FromUtf8Error),
}

impl std::error::Error for Error {}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let message = match self {
            Error::InvalidTokenLength => "Invalid token, not enough parts",
            Error::InvalidTokenSignature => "Calculated token signature difference from provided signature",
            Error::SerdeJsonError(_) => "Serde_json error",
            Error::SignError(_) => "HMAC error",
            Error::B64DecodeError(_) => "Base64 error",
            Error::FromUtf8Error(_) => "UTF-8 convertion error",
        };

        write!(f, "{message}")
    }
}

impl From<serde_json::Error> for Error {
    fn from(error: serde_json::Error) -> Self {
        Self::SerdeJsonError(error)
    }
}

impl From<hmac::digest::InvalidLength> for Error {
    fn from(error: hmac::digest::InvalidLength) -> Self {
        Self::SignError(error)
    }
}

impl From<base64::DecodeError> for Error {
    fn from(error: base64::DecodeError) -> Self {
        Self::B64DecodeError(error)
    }
}

impl From<std::string::FromUtf8Error> for Error {
    fn from(error: std::string::FromUtf8Error) -> Self {
        Self::FromUtf8Error(error)
    }
}