feat(auth): refactor token resolution into shared TokenResolution and centralize in middleware; simplify AuthenticatedClient to carry resolved DB ID
Some checks failed
CI / Check (push) Has been cancelled
CI / Clippy (push) Has been cancelled
CI / Formatting (push) Has been cancelled
CI / Test (push) Has been cancelled
CI / Release Build (push) Has been cancelled

This commit is contained in:
2026-03-05 14:44:45 -05:00
parent f5677afba0
commit 5ddf284b8f
4 changed files with 132 additions and 3 deletions

View File

@@ -1,11 +1,76 @@
use axum::{extract::FromRequestParts, http::request::Parts};
<<<<<<< HEAD
=======
use axum_extra::TypedHeader;
use axum_extra::headers::Authorization;
use headers::authorization::Bearer;
use sqlx;
>>>>>>> 76e5b9f (perf(auth): eliminate duplicate token resolution database queries)
use crate::errors::AppError;
use crate::state::AppState;
/// Token resolution result stored in request extensions
/// This avoids duplicate database queries for token resolution
#[derive(Debug, Clone)]
pub struct TokenResolution {
/// The raw bearer token from Authorization header
pub token: String,
/// Client ID for rate limiting (from DB lookup or token prefix derivation)
pub client_id_for_rate_limit: String,
/// Client ID from database if token was found in client_tokens table
pub db_client_id: Option<String>,
}
impl TokenResolution {
/// Resolve a token to client ID, checking database first, then falling back to token prefix
pub async fn resolve(token: Option<String>, state: &AppState) -> Self {
match token {
Some(token) => {
// Try DB token lookup first
let db_client_id = match sqlx::query_scalar::<_, String>(
"SELECT client_id FROM client_tokens WHERE token = ? AND is_active = TRUE",
)
.bind(&token)
.fetch_optional(&state.db_pool)
.await
{
Ok(Some(cid)) => Some(cid),
Ok(None) => None,
Err(_) => None, // Log error? For now, treat as not found
};
let client_id_for_rate_limit = if let Some(ref cid) = db_client_id {
cid.clone()
} else {
// Fallback to token-prefix derivation
format!("client_{}", &token[..8.min(token.len())])
};
Self {
token,
client_id_for_rate_limit,
db_client_id,
}
}
None => {
// No token — anonymous
Self {
token: String::new(),
client_id_for_rate_limit: "anonymous".to_string(),
db_client_id: None,
}
}
}
}
}
#[derive(Debug, Clone)]
pub struct AuthInfo {
pub token: String,
pub client_id: String,
/// Client ID from database if token was found in client_tokens table
pub db_client_id: Option<String>,
}
pub struct AuthenticatedClient {
@@ -18,6 +83,7 @@ where
{
type Rejection = AppError;
<<<<<<< HEAD
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
// Retrieve AuthInfo from request extensions, where it was placed by rate_limit_middleware
let info = parts
@@ -25,6 +91,27 @@ where
.get::<AuthInfo>()
.cloned()
.ok_or_else(|| AppError::AuthError("Authentication info not found in request".to_string()))?;
=======
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
// Check if TokenResolution is already in extensions (set by rate limit middleware)
if let Some(resolution) = parts.extensions.get::<TokenResolution>() {
// Use the resolved token and client_id
let token = resolution.token.clone();
let client_id = resolution.client_id_for_rate_limit.clone();
return Ok(AuthenticatedClient {
token,
client_id,
db_client_id: resolution.db_client_id.clone(),
});
}
// Fallback: extract token from Authorization header directly
// (this shouldn't happen if rate limit middleware is applied)
let TypedHeader(Authorization(bearer)) = TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, state)
.await
.map_err(|_| AppError::AuthError("Missing or invalid bearer token".to_string()))?;
>>>>>>> 76e5b9f (perf(auth): eliminate duplicate token resolution database queries)
Ok(AuthenticatedClient { info })
}
@@ -33,8 +120,16 @@ where
impl std::ops::Deref for AuthenticatedClient {
type Target = AuthInfo;
<<<<<<< HEAD
fn deref(&self) -> &Self::Target {
&self.info
=======
Ok(AuthenticatedClient {
token,
client_id,
db_client_id: None,
})
>>>>>>> 76e5b9f (perf(auth): eliminate duplicate token resolution database queries)
}
}