From 7fb3abc93d01850a2fec0f391fba8c57588597b5 Mon Sep 17 00:00:00 2001 From: Rogier Reerink Date: Fri, 9 Oct 2026 16:45:36 +0200 Subject: [PATCH] Added an authorization header bearer token extraction demo. --- ...ec0633eff66b73beed646069ad4db7450fd33.json | 112 ++++++++++++++++++ server/src/database/tokens.rs | 25 ++++ server/src/repository/tokens.rs | 28 +++++ server/src/routes/accounts.rs | 3 +- server/src/routes/extractors.rs | 1 + server/src/routes/extractors/auth.rs | 68 +++++++++++ 6 files changed, 236 insertions(+), 1 deletion(-) create mode 100644 server/.sqlx/query-458c87cbcf275d5b6f05abb9e5bec0633eff66b73beed646069ad4db7450fd33.json create mode 100644 server/src/routes/extractors/auth.rs diff --git a/server/.sqlx/query-458c87cbcf275d5b6f05abb9e5bec0633eff66b73beed646069ad4db7450fd33.json b/server/.sqlx/query-458c87cbcf275d5b6f05abb9e5bec0633eff66b73beed646069ad4db7450fd33.json new file mode 100644 index 0000000..47a3e77 --- /dev/null +++ b/server/.sqlx/query-458c87cbcf275d5b6f05abb9e5bec0633eff66b73beed646069ad4db7450fd33.json @@ -0,0 +1,112 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT *\n FROM tokens\n WHERE access_token_hash = $1\n AND access_expires_at > now()\n AND revoked_at IS NULL\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "tokens", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "access_token_hash", + "type_info": "Bytea", + "origin": { + "Table": { + "table": "tokens", + "name": "access_token_hash" + } + } + }, + { + "ordinal": 2, + "name": "refresh_token_hash", + "type_info": "Bytea", + "origin": { + "Table": { + "table": "tokens", + "name": "refresh_token_hash" + } + } + }, + { + "ordinal": 3, + "name": "access_expires_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "tokens", + "name": "access_expires_at" + } + } + }, + { + "ordinal": 4, + "name": "refresh_expires_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "tokens", + "name": "refresh_expires_at" + } + } + }, + { + "ordinal": 5, + "name": "refreshed_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "tokens", + "name": "refreshed_at" + } + } + }, + { + "ordinal": 6, + "name": "revoked_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "tokens", + "name": "revoked_at" + } + } + }, + { + "ordinal": 7, + "name": "created_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "tokens", + "name": "created_at" + } + } + } + ], + "parameters": { + "Left": [ + "Bytea" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + true, + true, + false + ] + }, + "hash": "458c87cbcf275d5b6f05abb9e5bec0633eff66b73beed646069ad4db7450fd33" +} diff --git a/server/src/database/tokens.rs b/server/src/database/tokens.rs index 1b7ae02..e98456d 100644 --- a/server/src/database/tokens.rs +++ b/server/src/database/tokens.rs @@ -2,6 +2,31 @@ use chrono::{DateTime, Utc}; use super::{DatabaseError, dtos::TokenRow}; +pub async fn get_by_access_token_hash<'e, E>( + executor: E, + access_token_hash: &[u8], +) -> Result, DatabaseError> +where + E: sqlx::Executor<'e, Database = sqlx::Postgres>, +{ + let row = sqlx::query_as!( + TokenRow, + r#" + SELECT * + FROM tokens + WHERE access_token_hash = $1 + AND access_expires_at > now() + AND revoked_at IS NULL + "#, + access_token_hash, + ) + .fetch_optional(executor) + .await + .map_err(DatabaseError::from)?; + + Ok(row) +} + pub async fn issue<'e, E>(executor: E, token: TokenRow) -> Result<(), DatabaseError> where E: sqlx::Executor<'e, Database = sqlx::Postgres>, diff --git a/server/src/repository/tokens.rs b/server/src/repository/tokens.rs index a059a55..b111a6f 100644 --- a/server/src/repository/tokens.rs +++ b/server/src/repository/tokens.rs @@ -6,6 +6,21 @@ use crate::{ domain::Token, }; +pub async fn get_by_access_token_hash<'e, E>( + executor: E, + access_token_hash: &[u8], +) -> Result, RepositoryError> +where + E: sqlx::Executor<'e, Database = sqlx::Postgres>, +{ + let token = db::get_by_access_token_hash(executor, access_token_hash) + .await? + .map(decode) + .transpose()?; + + Ok(token) +} + pub async fn issue<'e, E>(executor: E, token: Token) -> Result<(), RepositoryError> where E: sqlx::Executor<'e, Database = sqlx::Postgres>, @@ -42,6 +57,19 @@ where Ok(db::revoke(executor, token_hash).await?) } +fn decode(token: TokenRow) -> Result { + Ok(Token { + id: token.id, + access_token_hash: token.access_token_hash, + refresh_token_hash: token.refresh_token_hash, + access_expires_at: token.access_expires_at, + refresh_expires_at: token.refresh_expires_at, + refreshed_at: token.refreshed_at, + revoked_at: token.revoked_at, + created_at: token.created_at, + }) +} + fn encode(token: Token) -> TokenRow { TokenRow { id: token.id, diff --git a/server/src/routes/accounts.rs b/server/src/routes/accounts.rs index cd848d8..c210383 100644 --- a/server/src/routes/accounts.rs +++ b/server/src/routes/accounts.rs @@ -5,7 +5,7 @@ use uuid::Uuid; use super::{ dtos::account::{AccountRequest, AccountResponse}, - extractors::{json::Json, path::Path, query::Query}, + extractors::{auth::Auth, json::Json, path::Path, query::Query}, }; use crate::{ error::AppError, @@ -33,6 +33,7 @@ pub struct QueryParams { #[axum::debug_handler] #[tracing::instrument(skip(pool))] async fn list_accounts( + Auth(auth): Auth, State(pool): State, Query(query): Query, ) -> Result>, AppError> { diff --git a/server/src/routes/extractors.rs b/server/src/routes/extractors.rs index f3a4443..514eb45 100644 --- a/server/src/routes/extractors.rs +++ b/server/src/routes/extractors.rs @@ -1,3 +1,4 @@ +pub mod auth; pub mod form; pub mod json; pub mod path; diff --git a/server/src/routes/extractors/auth.rs b/server/src/routes/extractors/auth.rs new file mode 100644 index 0000000..aa819f8 --- /dev/null +++ b/server/src/routes/extractors/auth.rs @@ -0,0 +1,68 @@ +use axum::{ + RequestPartsExt, + extract::{FromRef, FromRequestParts}, + http::HeaderMap, +}; +use sqlx::PgPool; +use uuid::Uuid; + +use crate::{crypto::hash_secret, error::AppError, repository}; + +#[derive(Debug)] +pub struct Auth(pub Authorization); + +impl FromRequestParts for Auth +where + PgPool: FromRef, + S: Send + Sync, +{ + type Rejection = AppError; + + async fn from_request_parts( + parts: &mut axum::http::request::Parts, + state: &S, + ) -> 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 = repository::tokens::get_by_access_token_hash(&pool, &token_hash) + .await + .map_err(|_| AppError::Internal)? + .ok_or(AppError::Unauthorized)?; + + Ok(Auth(Authorization { + user_id: token.id, + app_id: None, + })) + } +} + +#[derive(Debug)] +pub struct Authorization { + user_id: Uuid, + app_id: Option, +} + +impl Authorization { + pub fn user_id(&self) -> Uuid { + self.user_id + } + + pub fn app_id(&self) -> Option { + self.app_id + } +}