From d3778302811573dbb3cb99ea716f9d15bf067e69 Mon Sep 17 00:00:00 2001 From: Griffin Smith Date: Mon, 16 May 2022 11:18:23 -0400 Subject: feat(net/alcoholic_jwt): Implement Error for ValidationError This allows using it unchanged in contexts where working with &dyn Error is desirable, such as when using anyhow. Change-Id: Ide34025e432204546b2c80b14b870af42dbfbb44 Reviewed-on: https://cl.tvl.fyi/c/depot/+/5615 Tested-by: BuildkiteCI Reviewed-by: tazjin Autosubmit: grfn --- net/alcoholic_jwt/src/lib.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'net') diff --git a/net/alcoholic_jwt/src/lib.rs b/net/alcoholic_jwt/src/lib.rs index 297bf2a990..1b50a91177 100644 --- a/net/alcoholic_jwt/src/lib.rs +++ b/net/alcoholic_jwt/src/lib.rs @@ -84,6 +84,8 @@ use openssl::rsa::Rsa; use openssl::sign::Verifier; use serde::de::DeserializeOwned; use serde_json::Value; +use std::error::Error; +use std::fmt::{self, Display}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; #[cfg(test)] @@ -219,6 +221,38 @@ pub enum ValidationError { InvalidClaims(Vec<&'static str>), } +impl Error for ValidationError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + ValidationError::InvalidBase64(e) => Some(e), + ValidationError::OpenSSL(e) => Some(e), + ValidationError::JSON(e) => Some(e), + ValidationError::InvalidComponents + | ValidationError::InvalidJWK + | ValidationError::InvalidSignature + | ValidationError::InvalidClaims(_) => None, + } + } +} + +impl Display for ValidationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ValidationError::InvalidComponents => { + f.write_str("Invalid number of token components in JWT") + } + ValidationError::InvalidBase64(_) => f.write_str("Invalid Base64 encoding in JWT"), + ValidationError::InvalidJWK => f.write_str("JWK decoding failed"), + ValidationError::InvalidSignature => f.write_str("JWT signature validation failed"), + ValidationError::OpenSSL(e) => write!(f, "SSL error: {}", e), + ValidationError::JSON(e) => write!(f, "JSON error: {}", e), + ValidationError::InvalidClaims(errs) => { + write!(f, "Invalid claims: {}", errs.join(", ")) + } + } + } +} + type JWTResult = Result; impl From for ValidationError { -- cgit 1.4.1