tower_oauth2_resource_server/
error.rs

1use std::{error::Error, fmt::Display};
2
3use http::{header::WWW_AUTHENTICATE, HeaderValue, Response, StatusCode};
4use jsonwebtoken::Algorithm;
5
6#[derive(Clone, Debug, PartialEq)]
7pub enum StartupError {
8    InvalidParameter(String),
9    OidcDiscoveryFailed(String),
10}
11
12impl Display for StartupError {
13    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14        write!(f, "{:?}", self)
15    }
16}
17impl Error for StartupError {}
18
19#[derive(Clone, Debug, PartialEq)]
20pub enum JwkError {
21    FetchFailed,
22    ParseFailed,
23    MissingKeyId,
24    DecodingFailed,
25}
26
27impl Display for JwkError {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        write!(f, "{:?}", self)
30    }
31}
32impl Error for JwkError {}
33
34#[derive(Clone, Debug, PartialEq)]
35pub enum AuthError {
36    MissingAuthorizationHeader,
37    InvalidAuthorizationHeader,
38    ParseJwtError,
39    InvalidKeyId,
40    UnsupportedAlgorithm(Algorithm),
41    ValidationFailed {
42        reason: jsonwebtoken::errors::ErrorKind,
43    },
44    AuthorizerNotFound,
45}
46
47impl Display for AuthError {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        write!(f, "{:?}", self)
50    }
51}
52impl Error for AuthError {}
53
54impl<B> From<AuthError> for Response<B>
55where
56    B: Default,
57{
58    fn from(e: AuthError) -> Self {
59        let mut response = Response::builder()
60            .status(StatusCode::UNAUTHORIZED)
61            .body(B::default())
62            .unwrap();
63        if e == AuthError::MissingAuthorizationHeader || e == AuthError::InvalidAuthorizationHeader
64        {
65            response
66                .headers_mut()
67                .insert(WWW_AUTHENTICATE, HeaderValue::from_str("Bearer").unwrap());
68        }
69        response
70    }
71}