Over engineered bearer token extraction (although it's not perfect yet).

This commit is contained in:
2026-10-10 12:15:00 +02:00
parent 1655becf39
commit 30efddbc20
6 changed files with 320 additions and 130 deletions
+2
View File
@@ -1,4 +1,5 @@
mod account; mod account;
mod authorization;
mod cents; mod cents;
mod direction; mod direction;
mod recurring_transaction; mod recurring_transaction;
@@ -10,6 +11,7 @@ mod user_app;
mod user_app_secret; mod user_app_secret;
pub use account::*; pub use account::*;
pub use authorization::*;
pub use cents::*; pub use cents::*;
pub use direction::*; pub use direction::*;
pub use recurring_transaction::*; pub use recurring_transaction::*;
+16
View File
@@ -0,0 +1,16 @@
use uuid::Uuid;
#[derive(Debug)]
pub struct Authorization {
user_id: Uuid,
}
impl Authorization {
pub fn new(user_id: Uuid) -> Self {
Self { user_id }
}
pub fn user_id(&self) -> Uuid {
self.user_id
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ mod accounts;
mod auth_passkey; mod auth_passkey;
mod auth_token; mod auth_token;
mod dtos; mod dtos;
mod extractors; pub mod extractors;
mod scheduled_transactions; mod scheduled_transactions;
mod transactions; mod transactions;
mod user_app_secrets; mod user_app_secrets;
+71 -129
View File
@@ -1,158 +1,100 @@
use axum::{ use axum::{extract::FromRequestParts, response::IntoResponse};
extract::{FromRef, FromRequestParts},
http::{
HeaderMap,
header::{AUTHORIZATION, ToStrError},
},
};
use sqlx::PgPool;
use uuid::Uuid;
use crate::{crypto::hash_secret, error::AppError, repository}; mod bearer;
mod header;
pub use bearer::*;
pub use header::*;
use crate::{domain::Authorization, error::AppError};
#[derive(Debug)] #[derive(Debug)]
pub struct Auth(pub Authorization); pub struct Auth(pub Authorization);
impl<S> FromRequestParts<S> for Auth impl<S> FromRequestParts<S> for Auth
where where
PgPool: FromRef<S>, Bearer: AuthScheme + Authorizer<S>,
S: Send + Sync, S: Send + Sync,
{ {
type Rejection = AppError; type Rejection = AuthError;
async fn from_request_parts( async fn from_request_parts(
parts: &mut axum::http::request::Parts, parts: &mut axum::http::request::Parts,
state: &S, state: &S,
) -> Result<Self, Self::Rejection> { ) -> Result<Self, Self::Rejection> {
let pool = PgPool::from_ref(state); let header = AuthHeader::from_request_parts(parts, state).await?;
if !header.scheme().eq_ignore_ascii_case(Bearer::SCHEME) {
return Err(AuthError::UnsupportedScheme);
}
let token = bearer_token(&parts.headers)?; let credentials = Bearer::credentials(header.token()).map_err(Into::<AuthError>::into)?;
let token_hash = hash_secret(token); let authorization = Bearer::authorize(credentials, state)
let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash) .await
.await? .map_err(Into::<AuthError>::into)?;
.ok_or(AppError::Unauthorized("Invalid access token".to_string()))?;
Ok(Auth(Authorization { Ok(Self(authorization))
user_id: token.user_id,
}))
} }
} }
#[derive(Debug)]
pub struct Authorization {
user_id: Uuid,
}
impl Authorization {
pub fn user_id(&self) -> Uuid {
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)] #[derive(Debug, thiserror::Error)]
enum AuthorizationHeaderError { pub enum AuthError {
#[error("Missing authorization header")] #[error("unsupported scheme")]
Missing,
#[error("Invalid authorization header encoding")]
NotAscii(#[source] ToStrError),
#[error("Malformed authorization header")]
MalformedValue,
#[error("Unsupported authorization scheme")]
UnsupportedScheme, UnsupportedScheme,
#[error("Missing authorization token")] #[error(transparent)]
EmptyToken, Header(#[from] AuthHeaderError),
#[error(transparent)]
Bearer(#[from] BearerError),
} }
impl From<AuthorizationHeaderError> for AppError { impl From<AuthError> for AppError {
fn from(error: AuthorizationHeaderError) -> Self { fn from(err: AuthError) -> Self {
tracing::debug!(%error, "authorization header error"); match err {
AppError::Unauthorized(error.to_string()) 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(),
}
} }
} }
#[cfg(test)] impl IntoResponse for AuthError {
mod tests { fn into_response(self) -> axum::response::Response {
use axum::http::HeaderValue; AppError::from(self).into_response()
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));
} }
} }
trait AuthScheme {
const SCHEME: &'static str;
type Credentials: Send;
type Error: Into<AuthError>;
fn credentials(token: &str) -> Result<Self::Credentials, Self::Error>;
}
trait Authorizer<S>: AuthScheme {
fn authorize(
credentials: Self::Credentials,
state: &S,
) -> impl Future<Output = Result<Authorization, Self::Error>> + Send;
}
@@ -0,0 +1,52 @@
use axum::extract::FromRef;
use sqlx::PgPool;
use super::{AuthScheme, Authorizer};
use crate::{
crypto::hash_secret,
repository::{self, RepositoryError},
};
#[derive(Debug)]
pub struct Bearer;
impl AuthScheme for Bearer {
const SCHEME: &'static str = "Bearer";
type Credentials = String;
type Error = BearerError;
fn credentials(token: &str) -> Result<Self::Credentials, Self::Error> {
Ok(token.to_string())
}
}
impl<S> Authorizer<S> for Bearer
where
PgPool: FromRef<S>,
S: Send + Sync,
{
async fn authorize(
credentials: Self::Credentials,
state: &S,
) -> Result<crate::domain::Authorization, Self::Error> {
let pool = PgPool::from_ref(state);
let token_hash = hash_secret(&credentials);
let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash)
.await
.map_err(|error| BearerError::Repository(error))?
.ok_or(BearerError::InvalidCredentials)?;
Ok(crate::domain::Authorization::new(token.user_id))
}
}
#[derive(Debug, thiserror::Error)]
pub enum BearerError {
#[error("invalid credentials")]
InvalidCredentials,
#[error(transparent)]
Repository(#[from] RepositoryError),
}
+178
View File
@@ -0,0 +1,178 @@
use axum::{
extract::FromRequestParts,
http::header::{AUTHORIZATION, ToStrError},
response::IntoResponse,
};
use crate::routes::extractors::auth::AuthError;
#[derive(Debug)]
pub struct AuthHeader {
scheme: String,
token: String,
}
impl AuthHeader {
pub fn scheme(&self) -> &str {
&self.scheme
}
pub fn token(&self) -> &str {
&self.token
}
}
impl<S> FromRequestParts<S> for AuthHeader
where
S: Send + Sync,
{
type Rejection = AuthHeaderError;
async fn from_request_parts(
parts: &mut axum::http::request::Parts,
_state: &S,
) -> Result<Self, Self::Rejection> {
let value = parts
.headers
.get(AUTHORIZATION)
.ok_or(AuthHeaderError::Missing)?
.to_str()
.map_err(AuthHeaderError::NotAscii)?;
let (scheme, token) = value
.split_once(' ')
.map(|(s, t)| (s, t.trim()))
.ok_or(AuthHeaderError::MalformedValue)?;
if scheme.is_empty() {
return Err(AuthHeaderError::EmptyScheme)?;
}
if token.is_empty() {
return Err(AuthHeaderError::EmptyToken)?;
}
Ok(AuthHeader {
scheme: scheme.to_string(),
token: token.to_string(),
})
}
}
#[derive(Debug, thiserror::Error)]
pub enum AuthHeaderError {
#[error("missing header")]
Missing,
#[error("invalid encoding")]
NotAscii(#[source] ToStrError),
#[error("malformed value")]
MalformedValue,
#[error("empty scheme")]
EmptyScheme,
#[error("empty token")]
EmptyToken,
}
impl IntoResponse for AuthHeaderError {
fn into_response(self) -> axum::response::Response {
Into::<AuthError>::into(self).into_response()
}
}
#[cfg(test)]
mod tests {
use axum::http::{HeaderMap, HeaderValue, Request, request::Parts};
use super::*;
fn headers(value: &[u8]) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_bytes(value).unwrap());
headers
}
fn parts(headers: HeaderMap) -> Parts {
let (mut parts, _) = Request::builder().body(()).unwrap().into_parts();
parts.headers = headers;
parts
}
#[tokio::test]
async fn extracts_scheme_and_token() {
let mut parts = parts(headers(b"Bearer abc123"));
let auth_header = AuthHeader::from_request_parts(&mut parts, &())
.await
.unwrap();
assert_eq!(auth_header.scheme(), "Bearer");
assert_eq!(auth_header.token(), "abc123");
}
#[tokio::test]
async fn trims_token() {
let mut parts = parts(headers(b"bearer abc123 "));
let auth_header = AuthHeader::from_request_parts(&mut parts, &())
.await
.unwrap();
assert_eq!(auth_header.scheme(), "bearer");
assert_eq!(auth_header.token(), "abc123");
}
#[tokio::test]
async fn rejects_missing_header() {
let mut parts = parts(HeaderMap::new());
assert!(matches!(
AuthHeader::from_request_parts(&mut parts, &())
.await
.unwrap_err(),
AuthHeaderError::Missing
));
}
#[tokio::test]
async fn rejects_non_utf8_header() {
let mut parts = parts(headers(&[b'B', b'e', b'a', b'r', b' ', 0xFF]));
assert!(matches!(
AuthHeader::from_request_parts(&mut parts, &())
.await
.unwrap_err(),
AuthHeaderError::NotAscii(_)
));
}
#[tokio::test]
async fn rejects_value_without_separator() {
let mut parts = parts(headers(b"Bearer"));
assert!(matches!(
AuthHeader::from_request_parts(&mut parts, &())
.await
.unwrap_err(),
AuthHeaderError::MalformedValue
));
}
#[tokio::test]
async fn rejects_empty_scheme() {
let mut parts = parts(headers(b" abc123"));
assert!(matches!(
AuthHeader::from_request_parts(&mut parts, &())
.await
.unwrap_err(),
AuthHeaderError::EmptyScheme
));
}
#[tokio::test]
async fn rejects_empty_token() {
let mut parts = parts(headers(b"Bearer "));
assert!(matches!(
AuthHeader::from_request_parts(&mut parts, &())
.await
.unwrap_err(),
AuthHeaderError::EmptyToken
));
}
}