use std::fmt;
use std::time::Duration;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthError {
Malformed(String),
InvalidCredentials,
Expired,
NotYetValid,
InvalidClaims(String),
UnknownKey(String),
Unavailable(String),
Key(String),
TooManyAttempts {
retry_after: Duration,
},
Config(String),
}
impl AuthError {
pub fn http_status(&self) -> u16 {
match self {
Self::Unavailable(_) => 503,
Self::Key(_) | Self::Config(_) => 500,
Self::TooManyAttempts { .. } => 429,
_ => 401,
}
}
#[inline]
pub fn is_rejection(&self) -> bool {
self.http_status() == 401
}
}
impl fmt::Display for AuthError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Malformed(m) => write!(f, "malformed credential: {m}"),
Self::InvalidCredentials => f.write_str("invalid credentials"),
Self::Expired => f.write_str("the token has expired"),
Self::NotYetValid => f.write_str("the token is not valid yet"),
Self::InvalidClaims(m) => write!(f, "invalid token claims: {m}"),
Self::UnknownKey(m) => write!(f, "no verification key: {m}"),
Self::Unavailable(m) => write!(f, "authentication backend unavailable: {m}"),
Self::Key(m) => write!(f, "key material: {m}"),
Self::TooManyAttempts { retry_after } => write!(
f,
"too many failed attempts; retry in {} s",
retry_after_secs(*retry_after)
),
Self::Config(m) => write!(f, "authentication is misconfigured: {m}"),
}
}
}
impl std::error::Error for AuthError {}
pub(crate) fn retry_after_secs(d: Duration) -> u64 {
d.as_secs()
.saturating_add(u64::from(d.subsec_nanos() > 0))
.max(1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn statuses_and_messages() {
let cases = [
(
AuthError::Malformed("x".into()),
401,
"malformed credential: x",
),
(AuthError::InvalidCredentials, 401, "invalid credentials"),
(AuthError::Expired, 401, "expired"),
(AuthError::NotYetValid, 401, "not valid yet"),
(AuthError::InvalidClaims("aud".into()), 401, "claims: aud"),
(AuthError::UnknownKey("k1".into()), 401, "key: k1"),
(AuthError::Unavailable("db".into()), 503, "unavailable: db"),
(AuthError::Key("pem".into()), 500, "key material: pem"),
(
AuthError::TooManyAttempts {
retry_after: Duration::from_millis(1_500),
},
429,
"retry in 2 s",
),
(AuthError::Config("iss".into()), 500, "misconfigured: iss"),
];
for (error, status, text) in cases {
assert_eq!(error.http_status(), status, "{error:?}");
assert_eq!(error.is_rejection(), status == 401);
assert!(error.to_string().contains(text), "{error}");
}
assert_eq!(retry_after_secs(Duration::ZERO), 1);
assert_eq!(retry_after_secs(Duration::from_secs(900)), 900);
}
}