From dbf6c3d9f50b796e3c141d429738d77bd46fde71 Mon Sep 17 00:00:00 2001 From: Rogier Reerink Date: Fri, 9 Oct 2026 18:03:54 +0200 Subject: [PATCH] Fine tuned authorization header errors. --- server/src/error.rs | 8 +- server/src/routes/auth_token.rs | 10 +- server/src/routes/extractors/auth.rs | 136 ++++++++++++++++++++++---- server/src/routes/user_app_secrets.rs | 2 +- server/src/routes/user_apps.rs | 2 +- 5 files changed, 129 insertions(+), 29 deletions(-) diff --git a/server/src/error.rs b/server/src/error.rs index c9006a6..e579aae 100644 --- a/server/src/error.rs +++ b/server/src/error.rs @@ -20,7 +20,7 @@ pub enum AppError { NotFound, #[error("unauthorized")] - Unauthorized, + Unauthorized(String), #[error("domain error")] Domain(#[from] DomainError), @@ -47,9 +47,9 @@ impl IntoResponse for AppError { tracing::debug!("not found"); return error_response(StatusCode::NOT_FOUND, "Not found"); } - Self::Unauthorized => { - tracing::debug!("unauthorized"); - return error_response(StatusCode::UNAUTHORIZED, "Unauthorized"); + Self::Unauthorized(message) => { + tracing::debug!(?message, "unauthorized"); + return error_response(StatusCode::UNAUTHORIZED, message); } Self::Domain(error) => { tracing::debug!(%error, "domain error"); diff --git a/server/src/routes/auth_token.rs b/server/src/routes/auth_token.rs index d128381..35c24ad 100644 --- a/server/src/routes/auth_token.rs +++ b/server/src/routes/auth_token.rs @@ -43,12 +43,16 @@ async fn issue_token( .map_err(repository::RepositoryError::from)?; if !repository::user_app_secrets::verify(&mut *tx, client_id, &secret_hash).await? { - return Err(AppError::Unauthorized); + return Err(AppError::Unauthorized( + "Invalid client credentials".to_string(), + )); } let user_app = repository::user_apps::get_by_id(&mut *tx, client_id) .await? - .ok_or(AppError::Unauthorized)?; + .ok_or(AppError::Unauthorized( + "Invalid client credentials".to_string(), + ))?; repository::tokens::issue( &mut *tx, @@ -82,7 +86,7 @@ async fn issue_token( ) .await?; if !rotated { - return Err(AppError::Unauthorized); + return Err(AppError::Unauthorized("Invalid refresh token".to_string())); } tx.commit() .await diff --git a/server/src/routes/extractors/auth.rs b/server/src/routes/extractors/auth.rs index ecafd40..e912891 100644 --- a/server/src/routes/extractors/auth.rs +++ b/server/src/routes/extractors/auth.rs @@ -1,7 +1,9 @@ use axum::{ - RequestPartsExt, extract::{FromRef, FromRequestParts}, - http::HeaderMap, + http::{ + HeaderMap, + header::{AUTHORIZATION, ToStrError}, + }, }; use sqlx::PgPool; use uuid::Uuid; @@ -24,25 +26,11 @@ where ) -> Result { let pool = PgPool::from_ref(state); - let headers = parts.extract::().await.map_err(|e| { - tracing::error!("Failed to extract headers: {:?}", e); - AppError::Internal - })?; - - let token_hash = headers - .get(axum::http::header::AUTHORIZATION) - .and_then(|h| h.to_str().ok()) - .and_then(|h| h.split_once(' ')) - .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("Bearer")) - .map(|(_, token)| token.trim()) - .filter(|token| !token.is_empty()) - .map(hash_secret) - .ok_or(AppError::Unauthorized)?; - + let token = bearer_token(&parts.headers)?; + let token_hash = hash_secret(token); let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash) - .await - .map_err(|_| AppError::Internal)? - .ok_or(AppError::Unauthorized)?; + .await? + .ok_or(AppError::Unauthorized("Invalid access token".to_string()))?; Ok(Auth(Authorization { user_id: token.user_id, @@ -60,3 +48,111 @@ impl Authorization { self.user_id } } + +fn bearer_token(headers: &HeaderMap) -> Result<&str, AuthorizationHeaderError> { + let value = headers + .get(AUTHORIZATION) + .ok_or(AuthorizationHeaderError::Missing)? + .to_str() + .map_err(AuthorizationHeaderError::NotAscii)?; + + let (scheme, token) = value + .split_once(' ') + .ok_or(AuthorizationHeaderError::MalformedValue)?; + + if !scheme.eq_ignore_ascii_case("Bearer") { + return Err(AuthorizationHeaderError::UnsupportedScheme); + } + + let token = token.trim(); + if token.is_empty() { + return Err(AuthorizationHeaderError::EmptyToken); + } + + Ok(token) +} + +#[derive(Debug, thiserror::Error)] +enum AuthorizationHeaderError { + #[error("Missing authorization header")] + Missing, + + #[error("Invalid authorization header encoding")] + NotAscii(#[source] ToStrError), + + #[error("Malformed authorization header")] + MalformedValue, + + #[error("Unsupported authorization scheme")] + UnsupportedScheme, + + #[error("Missing authorization token")] + EmptyToken, +} + +impl From for AppError { + fn from(error: AuthorizationHeaderError) -> Self { + tracing::debug!(%error, "authorization header error"); + AppError::Unauthorized(error.to_string()) + } +} + +#[cfg(test)] +mod tests { + use axum::http::HeaderValue; + + use super::*; + + fn headers_with(value: &[u8]) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert(AUTHORIZATION, HeaderValue::from_bytes(value).unwrap()); + headers + } + + #[test] + fn extracts_bearer_token() { + let headers = headers_with(b"Bearer abc123"); + assert_eq!(bearer_token(&headers).unwrap(), "abc123"); + } + + #[test] + fn accepts_case_insensitive_scheme_and_trims_token() { + let headers = headers_with(b"bearer abc123 "); + assert_eq!(bearer_token(&headers).unwrap(), "abc123"); + } + + #[test] + fn rejects_missing_header() { + let headers = HeaderMap::new(); + let error = bearer_token(&headers).unwrap_err(); + assert!(matches!(error, AuthorizationHeaderError::Missing)); + } + + #[test] + fn rejects_non_utf8_header() { + let headers = headers_with(&[b'B', b'e', b'a', b'r', b' ', 0xFF]); + let error = bearer_token(&headers).unwrap_err(); + assert!(matches!(error, AuthorizationHeaderError::NotAscii(_))); + } + + #[test] + fn rejects_value_without_separator() { + let headers = headers_with(b"Bearer"); + let error = bearer_token(&headers).unwrap_err(); + assert!(matches!(error, AuthorizationHeaderError::MalformedValue)); + } + + #[test] + fn rejects_unsupported_scheme() { + let headers = headers_with(b"Basic abc123"); + let error = bearer_token(&headers).unwrap_err(); + assert!(matches!(error, AuthorizationHeaderError::UnsupportedScheme)); + } + + #[test] + fn rejects_empty_token() { + let headers = headers_with(b"Bearer "); + let error = bearer_token(&headers).unwrap_err(); + assert!(matches!(error, AuthorizationHeaderError::EmptyToken)); + } +} diff --git a/server/src/routes/user_app_secrets.rs b/server/src/routes/user_app_secrets.rs index f6bc7f4..1dcaf6d 100644 --- a/server/src/routes/user_app_secrets.rs +++ b/server/src/routes/user_app_secrets.rs @@ -161,6 +161,6 @@ async fn ensure_app_ownership( ) -> Result<(), AppError> { match repository::user_apps::find_owner_by_id(&mut *connection, app_id).await? { Some(owner) if owner == user_id => Ok(()), - Some(_) | None => Err(AppError::NotFound).into(), + Some(_) | None => Err(AppError::NotFound), } } diff --git a/server/src/routes/user_apps.rs b/server/src/routes/user_apps.rs index fba5cf3..737da9e 100644 --- a/server/src/routes/user_apps.rs +++ b/server/src/routes/user_apps.rs @@ -96,7 +96,7 @@ async fn upsert_user_app( .as_ref() .is_some_and(|previous| previous.user_id != user_id) { - return Err(AppError::Conflict("User app ID is already in use".into()).into()); + return Err(AppError::Conflict("User app ID is already in use".into())); } tx.commit().await.map_err(RepositoryError::from)?;