Over engineered bearer token extraction (although it's not perfect yet).
This commit is contained in:
@@ -1,158 +1,100 @@
|
||||
use axum::{
|
||||
extract::{FromRef, FromRequestParts},
|
||||
http::{
|
||||
HeaderMap,
|
||||
header::{AUTHORIZATION, ToStrError},
|
||||
},
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
use axum::{extract::FromRequestParts, response::IntoResponse};
|
||||
|
||||
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)]
|
||||
pub struct Auth(pub Authorization);
|
||||
|
||||
impl<S> FromRequestParts<S> for Auth
|
||||
where
|
||||
PgPool: FromRef<S>,
|
||||
Bearer: AuthScheme + Authorizer<S>,
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = AppError;
|
||||
type Rejection = AuthError;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut axum::http::request::Parts,
|
||||
state: &S,
|
||||
) -> 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 token_hash = hash_secret(token);
|
||||
let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash)
|
||||
.await?
|
||||
.ok_or(AppError::Unauthorized("Invalid access token".to_string()))?;
|
||||
let credentials = Bearer::credentials(header.token()).map_err(Into::<AuthError>::into)?;
|
||||
let authorization = Bearer::authorize(credentials, state)
|
||||
.await
|
||||
.map_err(Into::<AuthError>::into)?;
|
||||
|
||||
Ok(Auth(Authorization {
|
||||
user_id: token.user_id,
|
||||
}))
|
||||
Ok(Self(authorization))
|
||||
}
|
||||
}
|
||||
|
||||
#[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)]
|
||||
enum AuthorizationHeaderError {
|
||||
#[error("Missing authorization header")]
|
||||
Missing,
|
||||
|
||||
#[error("Invalid authorization header encoding")]
|
||||
NotAscii(#[source] ToStrError),
|
||||
|
||||
#[error("Malformed authorization header")]
|
||||
MalformedValue,
|
||||
|
||||
#[error("Unsupported authorization scheme")]
|
||||
pub enum AuthError {
|
||||
#[error("unsupported scheme")]
|
||||
UnsupportedScheme,
|
||||
|
||||
#[error("Missing authorization token")]
|
||||
EmptyToken,
|
||||
#[error(transparent)]
|
||||
Header(#[from] AuthHeaderError),
|
||||
|
||||
#[error(transparent)]
|
||||
Bearer(#[from] BearerError),
|
||||
}
|
||||
|
||||
impl From<AuthorizationHeaderError> for AppError {
|
||||
fn from(error: AuthorizationHeaderError) -> Self {
|
||||
tracing::debug!(%error, "authorization header error");
|
||||
AppError::Unauthorized(error.to_string())
|
||||
impl From<AuthError> 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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));
|
||||
impl IntoResponse for AuthError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
AppError::from(self).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user