From 06092be6030681466d94534b348420d6494a07b2 Mon Sep 17 00:00:00 2001 From: Rogier Reerink Date: Sat, 10 Oct 2026 17:17:16 +0200 Subject: [PATCH] Struggling to clean up error handling. --- server/src/error.rs | 35 +++++++++++++++---- server/src/routes/extractors/auth.rs | 38 ++++----------------- server/src/routes/extractors/auth/bearer.rs | 23 +++++++++---- server/src/routes/extractors/auth/header.rs | 16 +++++++-- 4 files changed, 64 insertions(+), 48 deletions(-) diff --git a/server/src/error.rs b/server/src/error.rs index e579aae..1dfa4b9 100644 --- a/server/src/error.rs +++ b/server/src/error.rs @@ -6,6 +6,7 @@ use axum::{ use crate::{ domain::DomainError, repository::{ReferenceRelation, ReferenceViolationKind, RepositoryError}, + routes::extractors::auth::AuthError, }; #[derive(Debug, thiserror::Error)] @@ -22,6 +23,9 @@ pub enum AppError { #[error("unauthorized")] Unauthorized(String), + #[error("authorization error")] + Authorization(#[from] AuthError), + #[error("domain error")] Domain(#[from] DomainError), @@ -51,6 +55,21 @@ impl IntoResponse for AppError { tracing::debug!(?message, "unauthorized"); 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.error_message()); + } + Self::Authorization(AuthError::Bearer(error)) => { + tracing::debug!(%error, "bearer token error"); + return error_response(StatusCode::UNAUTHORIZED, error.error_message()); + } + Self::Authorization(AuthError::Repository(error)) => { + tracing::debug!(%error, "repository error"); + } Self::Domain(error) => { tracing::debug!(%error, "domain error"); return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string()); @@ -136,14 +155,16 @@ struct ErrorResponse { pub message: String, } -impl ErrorResponse { - pub fn new(message: impl Into) -> Self { - Self { +fn error_response(status_code: StatusCode, message: impl Into) -> Response { + ( + status_code, + axum::Json(ErrorResponse { message: message.into(), - } - } + }), + ) + .into_response() } -fn error_response(status_code: StatusCode, message: impl Into) -> Response { - (status_code, axum::Json(ErrorResponse::new(message))).into_response() +pub trait ClientError { + fn error_message(&self) -> &'static str; } diff --git a/server/src/routes/extractors/auth.rs b/server/src/routes/extractors/auth.rs index f2be4de..5483fc4 100644 --- a/server/src/routes/extractors/auth.rs +++ b/server/src/routes/extractors/auth.rs @@ -8,14 +8,14 @@ pub use bearer::*; pub use header::*; pub use principal::*; -use crate::error::AppError; +use crate::{error::AppError, repository::RepositoryError}; #[derive(Debug)] pub struct Auth(pub Principal); impl FromRequestParts for Auth where - T: AuthScheme + Authorizer, + T: AuthScheme + Authorizer, S: Send + Sync, { type Rejection = AuthError; @@ -48,35 +48,9 @@ pub enum AuthError { #[error(transparent)] Bearer(#[from] BearerError), -} -impl From for AppError { - fn from(err: AuthError) -> Self { - 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(), - } - } + #[error(transparent)] + Repository(#[from] RepositoryError), } impl IntoResponse for AuthError { @@ -94,9 +68,9 @@ trait AuthScheme { fn credentials(token: &str) -> Result; } -trait Authorizer: AuthScheme { +trait Authorizer: AuthScheme + Sized { fn authorize( credentials: Self::Credentials, state: &S, - ) -> impl Future, Self::Error>> + Send; + ) -> impl Future, Self::Error>> + Send; } diff --git a/server/src/routes/extractors/auth/bearer.rs b/server/src/routes/extractors/auth/bearer.rs index 0128855..279ed68 100644 --- a/server/src/routes/extractors/auth/bearer.rs +++ b/server/src/routes/extractors/auth/bearer.rs @@ -13,15 +13,15 @@ pub struct Bearer; impl AuthScheme for Bearer { const SCHEME: &'static str = "Bearer"; - type Credentials = String; + type Credentials = BearerToken; type Error = BearerError; fn credentials(token: &str) -> Result { - Ok(token.to_string()) + Ok(BearerToken(token.to_string())) } } -impl Authorizer for Bearer +impl Authorizer for Bearer where PgPool: FromRef, S: Send + Sync, @@ -29,19 +29,21 @@ where async fn authorize( credentials: Self::Credentials, state: &S, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> { 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) .await .map_err(BearerError::Repository)? .ok_or(BearerError::InvalidCredentials)?; - Ok(Principal::::new(token.user_id)) + Ok(Principal::new(token.user_id)) } } +pub struct BearerToken(String); + #[derive(Debug, thiserror::Error)] pub enum BearerError { #[error("invalid credentials")] @@ -50,3 +52,12 @@ pub enum BearerError { #[error(transparent)] Repository(#[from] RepositoryError), } + +impl crate::error::ClientError for BearerError { + fn error_message(&self) -> &'static str { + match self { + BearerError::InvalidCredentials => "Invalid credentials", + BearerError::Repository(_) => "Repository error", + } + } +} diff --git a/server/src/routes/extractors/auth/header.rs b/server/src/routes/extractors/auth/header.rs index 4c71548..aa6f41c 100644 --- a/server/src/routes/extractors/auth/header.rs +++ b/server/src/routes/extractors/auth/header.rs @@ -4,8 +4,6 @@ use axum::{ response::IntoResponse, }; -use crate::routes::extractors::auth::AuthError; - #[derive(Debug)] pub struct AuthHeader { scheme: String, @@ -77,9 +75,21 @@ pub enum AuthHeaderError { EmptyToken, } +impl crate::error::ClientError for AuthHeaderError { + fn 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 { fn into_response(self) -> axum::response::Response { - Into::::into(self).into_response() + Into::::into(self).into_response() } }