Over engineered bearer token extraction (although it's not perfect yet).
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
mod account;
|
||||
mod authorization;
|
||||
mod cents;
|
||||
mod direction;
|
||||
mod recurring_transaction;
|
||||
@@ -10,6 +11,7 @@ mod user_app;
|
||||
mod user_app_secret;
|
||||
|
||||
pub use account::*;
|
||||
pub use authorization::*;
|
||||
pub use cents::*;
|
||||
pub use direction::*;
|
||||
pub use recurring_transaction::*;
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ mod accounts;
|
||||
mod auth_passkey;
|
||||
mod auth_token;
|
||||
mod dtos;
|
||||
mod extractors;
|
||||
pub mod extractors;
|
||||
mod scheduled_transactions;
|
||||
mod transactions;
|
||||
mod user_app_secrets;
|
||||
|
||||
@@ -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 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()))?;
|
||||
|
||||
Ok(Auth(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 header = AuthHeader::from_request_parts(parts, state).await?;
|
||||
if !header.scheme().eq_ignore_ascii_case(Bearer::SCHEME) {
|
||||
return Err(AuthError::UnsupportedScheme);
|
||||
}
|
||||
|
||||
let token = token.trim();
|
||||
if token.is_empty() {
|
||||
return Err(AuthorizationHeaderError::EmptyToken);
|
||||
}
|
||||
let credentials = Bearer::credentials(header.token()).map_err(Into::<AuthError>::into)?;
|
||||
let authorization = Bearer::authorize(credentials, state)
|
||||
.await
|
||||
.map_err(Into::<AuthError>::into)?;
|
||||
|
||||
Ok(token)
|
||||
Ok(Self(authorization))
|
||||
}
|
||||
}
|
||||
|
||||
#[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;
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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
|
||||
));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user