Struggling to clean up error handling.

This commit is contained in:
2026-10-10 17:18:36 +02:00
parent 5f85713892
commit 94b2f23a59
4 changed files with 64 additions and 48 deletions
+28 -7
View File
@@ -6,6 +6,7 @@ use axum::{
use crate::{ use crate::{
domain::DomainError, domain::DomainError,
repository::{ReferenceRelation, ReferenceViolationKind, RepositoryError}, repository::{ReferenceRelation, ReferenceViolationKind, RepositoryError},
routes::extractors::auth::AuthError,
}; };
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
@@ -22,6 +23,9 @@ pub enum AppError {
#[error("unauthorized")] #[error("unauthorized")]
Unauthorized(String), Unauthorized(String),
#[error("authorization error")]
Authorization(#[from] AuthError),
#[error("domain error")] #[error("domain error")]
Domain(#[from] DomainError), Domain(#[from] DomainError),
@@ -51,6 +55,21 @@ impl IntoResponse for AppError {
tracing::debug!(?message, "unauthorized"); tracing::debug!(?message, "unauthorized");
return error_response(StatusCode::UNAUTHORIZED, message); return error_response(StatusCode::UNAUTHORIZED, message);
} }
Self::Authorization(AuthError::UnsupportedScheme) => {
tracing::debug!("authorization error: unsupported scheme");
return error_response(StatusCode::UNAUTHORIZED, "Unsupported scheme");
}
Self::Authorization(AuthError::Header(error)) => {
tracing::debug!(%error, "authorization header error");
return error_response(StatusCode::UNAUTHORIZED, error.client_error_message());
}
Self::Authorization(AuthError::Bearer(error)) => {
tracing::debug!(%error, "bearer token error");
return error_response(StatusCode::UNAUTHORIZED, error.client_error_message());
}
Self::Authorization(AuthError::Repository(error)) => {
tracing::debug!(%error, "repository error");
}
Self::Domain(error) => { Self::Domain(error) => {
tracing::debug!(%error, "domain error"); tracing::debug!(%error, "domain error");
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string()); return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
@@ -136,14 +155,16 @@ struct ErrorResponse {
pub message: String, pub message: String,
} }
impl ErrorResponse { fn error_response(status_code: StatusCode, message: impl Into<String>) -> Response {
pub fn new(message: impl Into<String>) -> Self { (
Self { status_code,
axum::Json(ErrorResponse {
message: message.into(), message: message.into(),
} }),
} )
.into_response()
} }
fn error_response(status_code: StatusCode, message: impl Into<String>) -> Response { pub trait ClientError {
(status_code, axum::Json(ErrorResponse::new(message))).into_response() fn client_error_message(&self) -> &'static str;
} }
+6 -32
View File
@@ -8,14 +8,14 @@ pub use bearer::*;
pub use header::*; pub use header::*;
pub use principal::*; pub use principal::*;
use crate::error::AppError; use crate::{error::AppError, repository::RepositoryError};
#[derive(Debug)] #[derive(Debug)]
pub struct Auth<T = Bearer>(pub Principal<T>); pub struct Auth<T = Bearer>(pub Principal<T>);
impl<T, S> FromRequestParts<S> for Auth<T> impl<T, S> FromRequestParts<S> for Auth<T>
where where
T: AuthScheme + Authorizer<S, T>, T: AuthScheme + Authorizer<S>,
S: Send + Sync, S: Send + Sync,
{ {
type Rejection = AuthError; type Rejection = AuthError;
@@ -48,35 +48,9 @@ pub enum AuthError {
#[error(transparent)] #[error(transparent)]
Bearer(#[from] BearerError), Bearer(#[from] BearerError),
}
impl From<AuthError> for AppError { #[error(transparent)]
fn from(err: AuthError) -> Self { Repository(#[from] RepositoryError),
match err {
AuthError::UnsupportedScheme => {
AppError::Unauthorized("Unsupported authorization scheme".into())
}
AuthError::Header(AuthHeaderError::Missing) => {
AppError::Unauthorized("Missing authorization header".into())
}
AuthError::Header(AuthHeaderError::NotAscii(_)) => {
AppError::Unauthorized("Invalid authorization header encoding".into())
}
AuthError::Header(AuthHeaderError::MalformedValue) => {
AppError::Unauthorized("Malformed authorization header".into())
}
AuthError::Header(AuthHeaderError::EmptyScheme) => {
AppError::Unauthorized("Empty authorization scheme".into())
}
AuthError::Header(AuthHeaderError::EmptyToken) => {
AppError::Unauthorized("Empty token value".into())
}
AuthError::Bearer(BearerError::InvalidCredentials) => {
AppError::Unauthorized("Unauthorized".into())
}
AuthError::Bearer(BearerError::Repository(error)) => error.into(),
}
}
} }
impl IntoResponse for AuthError { impl IntoResponse for AuthError {
@@ -94,9 +68,9 @@ trait AuthScheme {
fn credentials(token: &str) -> Result<Self::Credentials, Self::Error>; fn credentials(token: &str) -> Result<Self::Credentials, Self::Error>;
} }
trait Authorizer<S, T>: AuthScheme { trait Authorizer<S>: AuthScheme + Sized {
fn authorize( fn authorize(
credentials: Self::Credentials, credentials: Self::Credentials,
state: &S, state: &S,
) -> impl Future<Output = Result<Principal<T>, Self::Error>> + Send; ) -> impl Future<Output = Result<Principal<Self>, Self::Error>> + Send;
} }
+17 -6
View File
@@ -13,15 +13,15 @@ pub struct Bearer;
impl AuthScheme for Bearer { impl AuthScheme for Bearer {
const SCHEME: &'static str = "Bearer"; const SCHEME: &'static str = "Bearer";
type Credentials = String; type Credentials = BearerToken;
type Error = BearerError; type Error = BearerError;
fn credentials(token: &str) -> Result<Self::Credentials, Self::Error> { fn credentials(token: &str) -> Result<Self::Credentials, Self::Error> {
Ok(token.to_string()) Ok(BearerToken(token.to_string()))
} }
} }
impl<S, T> Authorizer<S, T> for Bearer impl<S> Authorizer<S> for Bearer
where where
PgPool: FromRef<S>, PgPool: FromRef<S>,
S: Send + Sync, S: Send + Sync,
@@ -29,19 +29,21 @@ where
async fn authorize( async fn authorize(
credentials: Self::Credentials, credentials: Self::Credentials,
state: &S, state: &S,
) -> Result<Principal<T>, Self::Error> { ) -> Result<Principal<Self>, Self::Error> {
let pool = PgPool::from_ref(state); let pool = PgPool::from_ref(state);
let token_hash = hash_secret(&credentials); let token_hash = hash_secret(&credentials.0);
let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash) let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash)
.await .await
.map_err(BearerError::Repository)? .map_err(BearerError::Repository)?
.ok_or(BearerError::InvalidCredentials)?; .ok_or(BearerError::InvalidCredentials)?;
Ok(Principal::<T>::new(token.user_id)) Ok(Principal::new(token.user_id))
} }
} }
pub struct BearerToken(String);
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum BearerError { pub enum BearerError {
#[error("invalid credentials")] #[error("invalid credentials")]
@@ -50,3 +52,12 @@ pub enum BearerError {
#[error(transparent)] #[error(transparent)]
Repository(#[from] RepositoryError), Repository(#[from] RepositoryError),
} }
impl crate::error::ClientError for BearerError {
fn client_error_message(&self) -> &'static str {
match self {
BearerError::InvalidCredentials => "Invalid credentials",
BearerError::Repository(_) => "Repository error",
}
}
}
+13 -3
View File
@@ -4,8 +4,6 @@ use axum::{
response::IntoResponse, response::IntoResponse,
}; };
use crate::routes::extractors::auth::AuthError;
#[derive(Debug)] #[derive(Debug)]
pub struct AuthHeader { pub struct AuthHeader {
scheme: String, scheme: String,
@@ -77,9 +75,21 @@ pub enum AuthHeaderError {
EmptyToken, EmptyToken,
} }
impl crate::error::ClientError for AuthHeaderError {
fn client_error_message(&self) -> &'static str {
match self {
AuthHeaderError::Missing => "Missing authorization header",
AuthHeaderError::NotAscii(_) => "Invalid authorization header encoding",
AuthHeaderError::MalformedValue => "Malformed authorization header",
AuthHeaderError::EmptyScheme => "Empty authorization scheme",
AuthHeaderError::EmptyToken => "Empty authorization token",
}
}
}
impl IntoResponse for AuthHeaderError { impl IntoResponse for AuthHeaderError {
fn into_response(self) -> axum::response::Response { fn into_response(self) -> axum::response::Response {
Into::<AuthError>::into(self).into_response() Into::<super::AuthError>::into(self).into_response()
} }
} }