#[cfg(not(feature = "auth"))]
use crate::common::constants::default_identity::DEFAULT_IDENTITY_TOKEN_HASH;
use crate::domain::auth::{ApiKeyScope, ScopePermission};
use crate::domain::services::audit_service::AuditServiceTrait;
#[cfg(feature = "auth")]
use crate::infrastructure::database::entities::api_key;
pub use crate::presentation::middleware::auth_types::{AuthError, AuthState};
use axum::extract::State;
#[cfg(feature = "auth")]
use axum::response::IntoResponse;
use axum::{
body::Body,
http::{Request, StatusCode},
middleware::Next,
response::Response,
};
#[cfg(feature = "auth")]
use dbnexus::sea_orm::EntityTrait;
#[cfg(feature = "auth")]
use dbnexus::DbPool;
#[cfg(feature = "auth")]
use log::debug;
#[cfg(feature = "auth")]
use lru::LruCache;
#[cfg(feature = "auth")]
use parking_lot::RwLock as ParkRwLock;
#[cfg(feature = "auth")]
use sha2::{Digest, Sha256};
#[cfg(feature = "auth")]
use std::num::NonZeroUsize;
use std::sync::Arc;
#[cfg(feature = "auth")]
use std::sync::LazyLock;
#[cfg(feature = "auth")]
use std::time::{Duration, Instant};
#[cfg(feature = "auth")]
const TEAM_ID_CACHE_CAPACITY: usize = 4096;
#[cfg(feature = "auth")]
const TEAM_ID_CACHE_TTL: Duration = Duration::from_secs(60);
#[cfg(feature = "auth")]
static TEAM_ID_CACHE: LazyLock<
ParkRwLock<LruCache<crate::domain::id::Id, (crate::domain::id::Id, Instant)>>,
> = LazyLock::new(|| {
ParkRwLock::new(LruCache::new(
NonZeroUsize::new(TEAM_ID_CACHE_CAPACITY).expect("TEAM_ID_CACHE_CAPACITY must be > 0"),
))
});
#[cfg(feature = "auth")]
pub fn team_id_cache_len() -> usize {
TEAM_ID_CACHE.read().len()
}
#[cfg(all(any(test, feature = "test-mocks"), feature = "auth"))]
pub fn reset_team_id_cache() {
TEAM_ID_CACHE.write().clear();
}
#[cfg(feature = "auth")]
#[cfg_attr(not(feature = "teams"), allow(dead_code))]
async fn fetch_team_id_by_api_key_id(
pool: &Arc<DbPool>,
api_key_id: crate::domain::id::Id,
) -> Result<Option<crate::domain::id::Id>, AuthError> {
let cached_hit = {
let mut cache = TEAM_ID_CACHE.write();
if let Some((team_id, cached_at)) = cache.get(&api_key_id) {
if cached_at.elapsed() < TEAM_ID_CACHE_TTL {
Some(*team_id)
} else {
cache.pop(&api_key_id);
None
}
} else {
None
}
};
if let Some(team_id) = cached_hit {
debug!(
"TEAM_ID_CACHE hit: api_key_id={} team_id={}",
api_key_id, team_id
);
return Ok(Some(team_id));
}
let session = pool
.get_session("admin")
.await
.map_err(|e| AuthError::InternalError(format!("db session: {}", e)))?;
let conn = session
.connection()
.map_err(|e| AuthError::InternalError(format!("db conn: {}", e)))?;
let result = api_key::Entity::find_by_id(api_key_id.to_uuid_v8())
.one(conn)
.await?;
if let Some(ref model) = result {
let team_id: crate::domain::id::Id = model.team_id.into();
{
let mut cache = TEAM_ID_CACHE.write();
cache.push(api_key_id, (team_id, Instant::now()));
}
debug!(
"TEAM_ID_CACHE miss→fill: api_key_id={} team_id={}",
api_key_id, team_id
);
}
Ok(result.map(|m| m.team_id.into()))
}
#[cfg(feature = "auth")]
fn hash_token(token: &str) -> String {
let digest = Sha256::digest(token.as_bytes());
format!("sha256:{}", hex::encode(digest))
}
fn inject_auth_state(req: &mut Request<Body>, auth_state: AuthState, token_hash: &str) {
req.extensions_mut().insert(auth_state);
req.extensions_mut().insert(token_hash.to_string());
}
static TRUSTED_PROXY_CONFIG: std::sync::OnceLock<
std::sync::Arc<crate::infrastructure::security::secure_ip::TrustedProxyConfig>,
> = std::sync::OnceLock::new();
pub fn configure_trusted_proxies(settings: &crate::config::settings::Settings) {
let config = std::sync::Arc::new(
crate::infrastructure::security::secure_ip::TrustedProxyConfig::from_settings(
settings.trusted_proxies.enabled,
settings.trusted_proxies.proxies.clone(),
),
);
if TRUSTED_PROXY_CONFIG.set(config).is_err() {
log::debug!("trusted proxy config already initialized; keeping first value");
}
}
#[cfg(feature = "auth")]
pub async fn garrison_ip_context_middleware(req: axum::extract::Request, next: Next) -> Response {
let trusted = TRUSTED_PROXY_CONFIG.get().cloned().unwrap_or_else(|| {
std::sync::Arc::new(
crate::infrastructure::security::secure_ip::TrustedProxyConfig::default(),
)
});
let ip = crate::infrastructure::security::secure_ip::get_secure_client_ip(&req, &trusted);
match ip.as_str() {
"unknown" | "" => next.run(req).await,
_ => garrison::stp::with_current_ip(ip, next.run(req)).await,
}
}
#[cfg(feature = "auth")]
pub async fn auth_middleware_inner(
State(pool): State<Arc<DbPool>>,
mut req: axum::http::Request<Body>,
next: Next,
) -> Response {
use crate::presentation::middleware::auth_bridge::extract_bearer;
let path = req.uri().path().to_string();
debug!("AuthMiddleware (garrison) processing path: {}", path);
if crate::presentation::middleware::is_public_endpoint(&path) {
debug!("Public endpoint {}, skipping auth", path);
return next.run(req).await;
}
let raw = match extract_bearer(&req) {
Ok(t) => t,
Err(e) => return e.into_response(),
};
let (login_id, perms) = match verify_api_key_scopes(&raw).await {
Ok(credentials) => credentials,
Err(e) => return e.into_response(),
};
if let Some(response) =
resolve_and_inject_auth_state(&pool, login_id, perms, &raw, &mut req).await
{
return response;
}
debug!("API Key authentication successful (garrison path)");
next.run(req).await
}
#[cfg(feature = "auth")]
async fn resolve_and_inject_auth_state(
pool: &Arc<DbPool>,
login_id: String,
perms: Vec<String>,
raw: &str,
req: &mut axum::http::Request<Body>,
) -> Option<Response> {
use crate::presentation::middleware::auth_bridge::bridge_to_auth_state;
let api_key_id = match login_id.parse::<crate::domain::id::Id>() {
Ok(u) => u,
Err(_) => return Some(AuthError::InvalidLoginId(login_id).into_response()),
};
#[cfg(feature = "teams")]
let team_id = match fetch_team_id_by_api_key_id(pool, api_key_id).await {
Ok(Some(tid)) => tid,
Ok(None) => return Some(AuthError::KeyNotFound(api_key_id).into_response()),
Err(e) => return Some(e.into_response()),
};
#[cfg(not(feature = "teams"))]
let team_id = crate::common::constants::default_identity::DEFAULT_TEAM_ID;
let auth_state = match bridge_to_auth_state(pool.clone(), api_key_id, &perms, team_id).await {
Ok(s) => s,
Err(e) => return Some(e.into_response()),
};
let token_hash = hash_token(raw);
inject_auth_state(req, auth_state, &token_hash);
None
}
#[cfg(feature = "auth")]
async fn verify_api_key_scopes(raw: &str) -> Result<(String, Vec<String>), AuthError> {
use garrison::protocol::apikey::ApiKeyHandler;
let dao = match crate::infrastructure::auth::get_garrison_dao() {
Some(d) => d,
None => {
let e = garrison::error::GarrisonError::Session(
"auth-middleware: garrison dao not initialized".to_string(),
);
return Err(AuthError::from_garrison(e));
}
};
let ip_ctx = garrison::stp::current_ip();
if let Some(ip) = &ip_ctx {
if let Some(err) = check_ip_blocked(&dao, ip).await {
return Err(err);
}
}
let handler = ApiKeyHandler::new(Arc::clone(&dao));
let info = match handler.verify_with_namespace(raw, "crawlrs").await {
Ok(i) => i,
Err(e) => {
if let Some(ip) = &ip_ctx {
if let Some(err) = record_failure_and_check_block(&dao, ip).await {
return Err(err);
}
}
return Err(AuthError::from_garrison(e));
}
};
Ok((info.login_id, info.scopes))
}
#[cfg(feature = "auth")]
async fn check_ip_blocked(
dao: &Arc<dyn garrison::prelude::GarrisonDao>,
ip: &str,
) -> Option<AuthError> {
use garrison::strategy::firewall::brute_force::{BruteForceConfig, BruteForceStrategy};
use garrison::strategy::firewall::FirewallContext;
let strategy = BruteForceStrategy::new(BruteForceConfig::default(), Arc::clone(dao));
let fw_ctx = FirewallContext::new(ip);
match strategy.is_blocked(&fw_ctx).await {
Ok(true) => {
let e = garrison::error::GarrisonError::FirewallBlocked(format!(
"auth-middleware-ip-blocked::{}",
ip
));
Some(AuthError::from_garrison(e))
}
Ok(false) | Err(_) => None,
}
}
#[cfg(feature = "auth")]
async fn record_failure_and_check_block(
dao: &Arc<dyn garrison::prelude::GarrisonDao>,
ip: &str,
) -> Option<AuthError> {
use garrison::strategy::firewall::brute_force::{BruteForceConfig, BruteForceStrategy};
use garrison::strategy::firewall::FirewallContext;
let strategy = BruteForceStrategy::new(BruteForceConfig::default(), Arc::clone(dao));
let fw_ctx = FirewallContext::new(ip);
if let Err(rec_err) = strategy.record_failure(&fw_ctx).await {
debug!(
"brute force record_failure failed (ip={}, err={})",
ip, rec_err
);
}
match strategy.is_blocked(&fw_ctx).await {
Ok(true) => {
let e = garrison::error::GarrisonError::FirewallBlocked(format!(
"auth-middleware-ip-blocked::{}",
ip
));
Some(AuthError::from_garrison(e))
}
Ok(false) | Err(_) => None,
}
}
#[cfg(not(feature = "auth"))]
static ALLOW_UNAUTHENTICATED: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
#[cfg(not(feature = "auth"))]
static DENY_LOG_ONCE: std::sync::OnceLock<()> = std::sync::OnceLock::new();
#[cfg(not(feature = "auth"))]
static ALLOW_LOG_ONCE: std::sync::OnceLock<()> = std::sync::OnceLock::new();
#[cfg(not(feature = "auth"))]
pub fn allow_unauthenticated_protected() {
ALLOW_LOG_ONCE.get_or_init(|| {
log::error!(
"{}",
crate::i18n::tr_log("auth-allow-unauthenticated-enabled")
);
});
ALLOW_UNAUTHENTICATED.store(true, std::sync::atomic::Ordering::SeqCst);
}
#[cfg(all(test, not(feature = "auth")))]
pub(crate) fn _reset_unauthenticated_for_test() {
ALLOW_UNAUTHENTICATED.store(false, std::sync::atomic::Ordering::SeqCst);
}
#[cfg(not(feature = "auth"))]
pub(crate) async fn default_identity_middleware(
State(template): State<AuthState>,
mut req: Request<Body>,
next: Next,
) -> Response {
use axum::response::IntoResponse as _;
if !ALLOW_UNAUTHENTICATED.load(std::sync::atomic::Ordering::SeqCst) {
DENY_LOG_ONCE.get_or_init(|| {
log::error!(
"{}",
crate::i18n::tr_log("auth-disabled-unauthenticated-denied")
);
});
return (StatusCode::UNAUTHORIZED, "authentication required").into_response();
}
inject_auth_state(&mut req, template, DEFAULT_IDENTITY_TOKEN_HASH);
next.run(req).await
}
pub async fn scope_middleware(req: Request<Body>, next: Next) -> Result<Response, StatusCode> {
let path = req.uri().path().to_string();
let method = req.method().clone();
let required_scope = determine_required_scope(&path, method.as_ref());
if let Some(required) = required_scope {
let auth_state = req
.extensions()
.get::<AuthState>()
.ok_or(StatusCode::UNAUTHORIZED)?;
if !auth_state.scope.has_permission(required) {
log::info!(
"Scope denied: API Key {} lacks {:?} for {} {}",
auth_state.api_key_id,
required,
method,
path
);
if let Some(audit_service) = req.extensions().get::<Arc<dyn AuditServiceTrait>>() {
let api_key_scope: ApiKeyScope = required.into();
let reason = format!("Missing required scope: {:?}", required);
if let Err(e) = audit_service
.log_deny(
"scope.denied".to_string(),
Some(auth_state.api_key_id),
Some(auth_state.team_id),
reason,
Some(api_key_scope),
)
.await
{
log::error!(
"audit log_deny failed for scope.denied event: api_key_id={} team_id={} err={}",
auth_state.api_key_id,
auth_state.team_id,
e
);
}
}
return Err(StatusCode::FORBIDDEN);
}
}
Ok(next.run(req).await)
}
fn is_path_prefix(path: &str, prefix: &str) -> bool {
path == prefix || (path.starts_with(prefix) && path[prefix.len()..].starts_with('/'))
}
fn determine_required_scope(path: &str, method: &str) -> Option<ScopePermission> {
if is_path_prefix(path, "/api/v1/teams") || is_path_prefix(path, "/api/v1/billing") {
return Some(ScopePermission::Admin);
}
if method == "POST" || method == "PUT" || method == "PATCH" || method == "DELETE" {
return Some(ScopePermission::Write);
}
None
}
#[cfg(all(test, feature = "auth"))]
pub fn test_auth_state(
db: Arc<DbPool>,
team_id: crate::domain::id::Id,
api_key_id: crate::domain::id::Id,
) -> AuthState {
AuthState::new(db, team_id, api_key_id, ApiKeyScope::default())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_path_prefix_exact_match() {
assert!(is_path_prefix("/api/v1/teams", "/api/v1/teams"));
}
#[test]
fn test_is_path_prefix_with_slash() {
assert!(is_path_prefix("/api/v1/teams/123", "/api/v1/teams"));
}
#[test]
fn test_is_path_prefix_suffix_without_slash_no_match() {
assert!(!is_path_prefix("/api/v1/teams-secret", "/api/v1/teams"));
}
#[test]
fn test_is_path_prefix_no_match() {
assert!(!is_path_prefix("/v1/search", "/api/v1/teams"));
}
#[test]
fn test_determine_required_scope_teams_admin() {
assert_eq!(
determine_required_scope("/api/v1/teams", "GET"),
Some(ScopePermission::Admin)
);
}
#[test]
fn test_determine_required_scope_teams_subpath_admin() {
assert_eq!(
determine_required_scope("/api/v1/teams/123", "GET"),
Some(ScopePermission::Admin)
);
}
#[test]
fn test_determine_required_scope_billing_admin() {
assert_eq!(
determine_required_scope("/api/v1/billing", "GET"),
Some(ScopePermission::Admin)
);
}
#[test]
fn test_determine_required_scope_teams_secret_not_admin() {
assert_eq!(
determine_required_scope("/api/v1/teams-secret", "GET"),
None
);
}
#[test]
fn test_determine_required_scope_post_write() {
assert_eq!(
determine_required_scope("/v1/search", "POST"),
Some(ScopePermission::Write)
);
assert_eq!(
determine_required_scope("/v1/scrape", "POST"),
Some(ScopePermission::Write)
);
}
#[test]
fn test_determine_required_scope_get_none() {
assert_eq!(determine_required_scope("/v1/search", "GET"), None);
assert_eq!(determine_required_scope("/v1/crawl/123", "GET"), None);
}
#[test]
fn test_determine_required_scope_put_delete_patch_write() {
assert_eq!(
determine_required_scope("/v1/crawl/123", "PUT"),
Some(ScopePermission::Write)
);
assert_eq!(
determine_required_scope("/v1/crawl/123", "DELETE"),
Some(ScopePermission::Write)
);
assert_eq!(
determine_required_scope("/v1/crawl/123", "PATCH"),
Some(ScopePermission::Write)
);
}
#[cfg(feature = "auth")]
mod hash_token_tests {
use super::*;
#[test]
fn test_hash_token_returns_sha256_prefix() {
let hash = hash_token("test_token");
assert!(
hash.starts_with("sha256:"),
"hash must start with 'sha256:' prefix, got: {hash}"
);
}
#[test]
fn test_hash_token_is_deterministic() {
let hash1 = hash_token("same_token");
let hash2 = hash_token("same_token");
assert_eq!(hash1, hash2, "same input must produce same hash");
}
#[test]
fn test_hash_token_different_inputs_different_outputs() {
let hash1 = hash_token("token_a");
let hash2 = hash_token("token_b");
assert_ne!(
hash1, hash2,
"different inputs must produce different hashes"
);
}
#[test]
fn test_hash_token_does_not_contain_plaintext() {
let token = "sensitive_secret_token_12345";
let hash = hash_token(token);
assert!(
!hash.contains(token),
"hash must not contain plaintext token (CWE-532)"
);
}
}
#[cfg(feature = "auth")]
mod team_id_cache_tests {
use super::*;
use std::time::Duration;
fn reset_team_id_cache_for_test() {
reset_team_id_cache();
}
#[test]
fn test_team_id_cache_len_starts_at_zero() {
reset_team_id_cache_for_test();
assert_eq!(team_id_cache_len(), 0);
}
#[test]
fn test_team_id_cache_constants() {
assert_eq!(TEAM_ID_CACHE_CAPACITY, 4096);
assert_eq!(TEAM_ID_CACHE_TTL, Duration::from_secs(60));
}
}
#[cfg(not(feature = "auth"))]
mod default_identity_tests {
use super::*;
use crate::common::constants::default_identity::{DEFAULT_API_KEY_ID, DEFAULT_TEAM_ID};
use crate::common::test_helpers::create_test_db_pool;
use axum::{
middleware::from_fn_with_state, response::IntoResponse, routing::get, Extension, Router,
};
use tower::ServiceExt;
async fn reflect_extensions(
Extension(auth_state): Extension<AuthState>,
) -> impl IntoResponse {
(
StatusCode::OK,
format!(
"auth_team={}\nauth_key={}\nread={}\nwrite={}\nadmin={}",
auth_state.team_id,
auth_state.api_key_id,
auth_state.scope.read,
auth_state.scope.write,
auth_state.scope.admin,
),
)
}
fn make_default_identity_router(template: AuthState) -> Router {
Router::new()
.route("/v1/echo", get(reflect_extensions))
.layer(from_fn_with_state(template, default_identity_middleware))
}
#[tokio::test]
async fn default_identity_middleware_denies_by_default_with_401() {
let _guard = UNAUTH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
_reset_unauthenticated_for_test();
let pool = create_test_db_pool();
let template = AuthState::new(
pool,
DEFAULT_TEAM_ID,
DEFAULT_API_KEY_ID,
ApiKeyScope::denied(),
);
let response = make_default_identity_router(template)
.oneshot(
Request::builder()
.uri("/v1/echo")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn allow_unauthenticated_protected_opt_in_injects_template_identity() {
let _guard = UNAUTH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
_reset_unauthenticated_for_test();
allow_unauthenticated_protected();
let pool = create_test_db_pool();
let template = AuthState::new(
pool,
DEFAULT_TEAM_ID,
DEFAULT_API_KEY_ID,
ApiKeyScope::denied(),
);
let response = make_default_identity_router(template)
.oneshot(
Request::builder()
.uri("/v1/echo")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = String::from_utf8(
axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap()
.to_vec(),
)
.unwrap();
assert!(body.contains(&format!("auth_team={}", DEFAULT_TEAM_ID)));
assert!(body.contains(&format!("auth_key={}", DEFAULT_API_KEY_ID)));
assert!(body.contains("read=false"));
assert!(body.contains("write=false"));
assert!(body.contains("admin=false"));
_reset_unauthenticated_for_test();
}
static UNAUTH_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[tokio::test]
async fn default_identity_middleware_passes_without_authorization_header() {
let _guard = UNAUTH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
allow_unauthenticated_protected();
let pool = create_test_db_pool();
let template = AuthState::new(
pool,
DEFAULT_TEAM_ID,
DEFAULT_API_KEY_ID,
ApiKeyScope::denied(),
);
let response = make_default_identity_router(template)
.oneshot(
Request::builder()
.uri("/v1/echo")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
_reset_unauthenticated_for_test();
}
#[tokio::test]
async fn default_identity_middleware_ignores_invalid_authorization_header() {
let _guard = UNAUTH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
allow_unauthenticated_protected();
let pool = create_test_db_pool();
let template = AuthState::new(
pool,
DEFAULT_TEAM_ID,
DEFAULT_API_KEY_ID,
ApiKeyScope::denied(),
);
let response = make_default_identity_router(template)
.oneshot(
Request::builder()
.uri("/v1/echo")
.header("Authorization", "Bearer fake_token_should_be_ignored")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
_reset_unauthenticated_for_test();
}
}
}