Fine tuned authorization header errors.

This commit is contained in:
2026-10-09 18:03:54 +02:00
parent 1f6de34e5b
commit dbf6c3d9f5
5 changed files with 129 additions and 29 deletions
+4 -4
View File
@@ -20,7 +20,7 @@ pub enum AppError {
NotFound, NotFound,
#[error("unauthorized")] #[error("unauthorized")]
Unauthorized, Unauthorized(String),
#[error("domain error")] #[error("domain error")]
Domain(#[from] DomainError), Domain(#[from] DomainError),
@@ -47,9 +47,9 @@ impl IntoResponse for AppError {
tracing::debug!("not found"); tracing::debug!("not found");
return error_response(StatusCode::NOT_FOUND, "Not found"); return error_response(StatusCode::NOT_FOUND, "Not found");
} }
Self::Unauthorized => { Self::Unauthorized(message) => {
tracing::debug!("unauthorized"); tracing::debug!(?message, "unauthorized");
return error_response(StatusCode::UNAUTHORIZED, "Unauthorized"); return error_response(StatusCode::UNAUTHORIZED, message);
} }
Self::Domain(error) => { Self::Domain(error) => {
tracing::debug!(%error, "domain error"); tracing::debug!(%error, "domain error");
+7 -3
View File
@@ -43,12 +43,16 @@ async fn issue_token(
.map_err(repository::RepositoryError::from)?; .map_err(repository::RepositoryError::from)?;
if !repository::user_app_secrets::verify(&mut *tx, client_id, &secret_hash).await? { 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) let user_app = repository::user_apps::get_by_id(&mut *tx, client_id)
.await? .await?
.ok_or(AppError::Unauthorized)?; .ok_or(AppError::Unauthorized(
"Invalid client credentials".to_string(),
))?;
repository::tokens::issue( repository::tokens::issue(
&mut *tx, &mut *tx,
@@ -82,7 +86,7 @@ async fn issue_token(
) )
.await?; .await?;
if !rotated { if !rotated {
return Err(AppError::Unauthorized); return Err(AppError::Unauthorized("Invalid refresh token".to_string()));
} }
tx.commit() tx.commit()
.await .await
+116 -20
View File
@@ -1,7 +1,9 @@
use axum::{ use axum::{
RequestPartsExt,
extract::{FromRef, FromRequestParts}, extract::{FromRef, FromRequestParts},
http::HeaderMap, http::{
HeaderMap,
header::{AUTHORIZATION, ToStrError},
},
}; };
use sqlx::PgPool; use sqlx::PgPool;
use uuid::Uuid; use uuid::Uuid;
@@ -24,25 +26,11 @@ where
) -> Result<Self, Self::Rejection> { ) -> Result<Self, Self::Rejection> {
let pool = PgPool::from_ref(state); let pool = PgPool::from_ref(state);
let headers = parts.extract::<HeaderMap>().await.map_err(|e| { let token = bearer_token(&parts.headers)?;
tracing::error!("Failed to extract headers: {:?}", e); let token_hash = hash_secret(token);
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 = 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(|_| AppError::Internal)? .ok_or(AppError::Unauthorized("Invalid access token".to_string()))?;
.ok_or(AppError::Unauthorized)?;
Ok(Auth(Authorization { Ok(Auth(Authorization {
user_id: token.user_id, user_id: token.user_id,
@@ -60,3 +48,111 @@ impl Authorization {
self.user_id 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<AuthorizationHeaderError> 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));
}
}
+1 -1
View File
@@ -161,6 +161,6 @@ async fn ensure_app_ownership(
) -> Result<(), AppError> { ) -> Result<(), AppError> {
match repository::user_apps::find_owner_by_id(&mut *connection, app_id).await? { match repository::user_apps::find_owner_by_id(&mut *connection, app_id).await? {
Some(owner) if owner == user_id => Ok(()), Some(owner) if owner == user_id => Ok(()),
Some(_) | None => Err(AppError::NotFound).into(), Some(_) | None => Err(AppError::NotFound),
} }
} }
+1 -1
View File
@@ -96,7 +96,7 @@ async fn upsert_user_app(
.as_ref() .as_ref()
.is_some_and(|previous| previous.user_id != user_id) .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)?; tx.commit().await.map_err(RepositoryError::from)?;