use crate::domain::auth::ApiKeyScope;
use crate::presentation::middleware::auth_types::{AuthError, AuthState};
use axum::body::Body;
use axum::http::{header, Request};
use dbnexus::DbPool;
use std::sync::Arc;
const PERM_READ: &str = "crawlrs:read";
const PERM_WRITE: &str = "crawlrs:write";
const PERM_ADMIN: &str = "crawlrs:admin";
const DEFAULT_SEARCH_LIMIT: u32 = 100;
const DEFAULT_SCRAPE_LIMIT: u32 = 50;
const BEARER_PREFIX: &str = "Bearer ";
const MAX_BEARER_TOKEN_LEN: usize = 1024;
pub fn map_perms_to_scope(perms: &[String]) -> ApiKeyScope {
let mut read = false;
let mut write = false;
let mut admin = false;
for perm in perms {
match perm.as_str() {
PERM_ADMIN => {
read = true;
write = true;
admin = true;
}
PERM_READ => read = true,
PERM_WRITE => write = true,
_ => {}
}
}
ApiKeyScope::with_custom_limits(
read,
write,
admin,
DEFAULT_SEARCH_LIMIT,
DEFAULT_SCRAPE_LIMIT,
)
}
pub fn extract_bearer(req: &Request<Body>) -> Result<String, AuthError> {
let auth_header = req.headers().get(header::AUTHORIZATION).ok_or_else(|| {
log::debug!("Bearer token rejected: Authorization header missing");
AuthError::InvalidKey
})?;
let value = auth_header.to_str().map_err(|_| {
log::debug!("Bearer token rejected: header value not visible ASCII");
AuthError::InvalidKey
})?;
if !value.starts_with(BEARER_PREFIX) {
log::debug!(
"Bearer token rejected: scheme not 'Bearer ' (case-sensitive, RFC 7235 legacy)"
);
return Err(AuthError::InvalidKey);
}
let token = &value[BEARER_PREFIX.len()..];
if token.is_empty() {
log::debug!("Bearer token rejected: token empty after 'Bearer ' prefix");
return Err(AuthError::InvalidKey);
}
if token.len() > MAX_BEARER_TOKEN_LEN {
log::warn!(
"Bearer token rejected: length {} exceeds max {} (CWE-208)",
token.len(),
MAX_BEARER_TOKEN_LEN
);
return Err(AuthError::InvalidKey);
}
Ok(token.to_string())
}
pub async fn bridge_to_auth_state(
pool: Arc<DbPool>,
api_key_id: crate::domain::id::Id,
perms: &[String],
team_id: crate::domain::id::Id,
) -> Result<AuthState, AuthError> {
let scope = map_perms_to_scope(perms);
Ok(AuthState::new(pool, team_id, api_key_id, scope))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::domain::auth::ScopePermission;
#[test]
fn test_map_perms_admin_grants_all() {
let perms = vec!["crawlrs:admin".to_string()];
let scope = map_perms_to_scope(&perms);
assert!(scope.read, "admin should grant read");
assert!(scope.write, "admin should grant write");
assert!(scope.admin, "admin should grant admin");
}
#[test]
fn test_map_perms_read_grants_only_read() {
let perms = vec!["crawlrs:read".to_string()];
let scope = map_perms_to_scope(&perms);
assert!(scope.read, "read should grant read");
assert!(!scope.write, "read should NOT grant write");
assert!(!scope.admin, "read should NOT grant admin");
}
#[test]
fn test_map_perms_write_grants_only_write() {
let perms = vec!["crawlrs:write".to_string()];
let scope = map_perms_to_scope(&perms);
assert!(!scope.read, "write should NOT grant read (least privilege)");
assert!(scope.write, "write should grant write");
assert!(!scope.admin, "write should NOT grant admin");
}
#[test]
fn test_map_perms_read_and_write_grants_read_write() {
let perms = vec!["crawlrs:read".to_string(), "crawlrs:write".to_string()];
let scope = map_perms_to_scope(&perms);
assert!(scope.read, "read+write should grant read");
assert!(scope.write, "read+write should grant write");
assert!(!scope.admin, "read+write should NOT grant admin");
}
#[test]
fn test_map_perms_empty_denies_all() {
let perms: Vec<String> = vec![];
let scope = map_perms_to_scope(&perms);
assert!(!scope.read, "empty perms should deny read");
assert!(!scope.write, "empty perms should deny write");
assert!(!scope.admin, "empty perms should deny admin");
}
#[test]
fn test_map_perms_unknown_perm_denies_all() {
let perms = vec!["otherapp:read".to_string(), "foo:admin".to_string()];
let scope = map_perms_to_scope(&perms);
assert!(!scope.read, "unknown perm should deny read");
assert!(!scope.write, "unknown perm should deny write");
assert!(!scope.admin, "unknown perm should deny admin");
}
#[test]
fn test_map_perms_admin_and_read_dedup() {
let perms = vec!["crawlrs:admin".to_string(), "crawlrs:read".to_string()];
let scope = map_perms_to_scope(&perms);
assert!(scope.read, "admin+read should grant read");
assert!(scope.write, "admin+read should grant write");
assert!(scope.admin, "admin+read should grant admin");
}
#[test]
fn test_map_perms_case_sensitive() {
let perms = vec!["Crawlrs:admin".to_string(), "CRAWLRS:READ".to_string()];
let scope = map_perms_to_scope(&perms);
assert!(!scope.read, "wrong case should deny read");
assert!(!scope.write, "wrong case should deny write");
assert!(!scope.admin, "wrong case should deny admin");
}
#[test]
fn test_map_perms_default_limits() {
let perms = vec!["crawlrs:admin".to_string()];
let scope = map_perms_to_scope(&perms);
assert_eq!(
scope.search_limit, 100,
"search_limit should be default 100"
);
assert_eq!(scope.scrape_limit, 50, "scrape_limit should be default 50");
}
#[test]
fn test_map_perms_mixed_with_unknown() {
let perms = vec![
"crawlrs:read".to_string(),
"otherapp:write".to_string(),
"crawlrs:admin".to_string(),
];
let scope = map_perms_to_scope(&perms);
assert!(scope.read, "mixed with admin should grant read");
assert!(scope.write, "mixed with admin should grant write");
assert!(scope.admin, "mixed with admin should grant admin");
}
#[test]
fn test_perm_constants() {
assert_eq!(PERM_READ, "crawlrs:read");
assert_eq!(PERM_WRITE, "crawlrs:write");
assert_eq!(PERM_ADMIN, "crawlrs:admin");
assert_eq!(DEFAULT_SEARCH_LIMIT, 100);
assert_eq!(DEFAULT_SCRAPE_LIMIT, 50);
assert_eq!(BEARER_PREFIX, "Bearer ");
}
fn make_request(auth_header: Option<&str>) -> Request<Body> {
let mut req = axum::http::Request::builder()
.uri("/")
.body(Body::empty())
.unwrap();
if let Some(value) = auth_header {
req.headers_mut()
.insert(header::AUTHORIZATION, value.parse().unwrap());
}
req
}
#[test]
fn test_extract_bearer_valid_token() {
let req = make_request(Some("Bearer ak_test_12345"));
let result = extract_bearer(&req);
assert!(result.is_ok(), "valid Bearer should be Ok");
assert_eq!(result.unwrap(), "ak_test_12345");
}
#[test]
fn test_extract_bearer_missing_header() {
let req = make_request(None);
let result = extract_bearer(&req);
assert!(result.is_err(), "missing header should be Err");
match result.unwrap_err() {
AuthError::InvalidKey => {}
other => panic!("expected InvalidKey, got {:?}", other),
}
}
#[test]
fn test_extract_bearer_wrong_scheme() {
let req = make_request(Some("Basic abc123"));
let result = extract_bearer(&req);
assert!(result.is_err(), "non-Bearer scheme should be Err");
match result.unwrap_err() {
AuthError::InvalidKey => {}
other => panic!("expected InvalidKey, got {:?}", other),
}
}
#[test]
fn test_extract_bearer_empty_token() {
let req = make_request(Some("Bearer "));
let result = extract_bearer(&req);
assert!(result.is_err(), "empty token should be Err");
match result.unwrap_err() {
AuthError::InvalidKey => {}
other => panic!("expected InvalidKey, got {:?}", other),
}
}
#[test]
fn test_extract_bearer_case_sensitive_scheme() {
let req = make_request(Some("bearer ak_test"));
let result = extract_bearer(&req);
assert!(result.is_err(), "lowercase 'bearer' should be Err");
match result.unwrap_err() {
AuthError::InvalidKey => {}
other => panic!("expected InvalidKey, got {:?}", other),
}
}
#[test]
fn test_extract_bearer_non_ascii_header() {
let mut req = axum::http::Request::builder()
.uri("/")
.body(Body::empty())
.unwrap();
let non_ascii_value = axum::http::HeaderValue::from_bytes(b"Bearer \x80abc").unwrap();
req.headers_mut()
.insert(header::AUTHORIZATION, non_ascii_value);
let result = extract_bearer(&req);
assert!(result.is_err(), "non-ASCII header should be Err");
match result.unwrap_err() {
AuthError::InvalidKey => {}
other => panic!("expected InvalidKey, got {:?}", other),
}
}
#[test]
fn test_extract_bearer_token_with_special_chars() {
let req = make_request(Some("Bearer ak.test_key=123"));
let result = extract_bearer(&req);
assert!(result.is_ok());
assert_eq!(result.unwrap(), "ak.test_key=123");
}
async fn make_test_pool() -> Option<Arc<DbPool>> {
if crate::common::test_helpers::skip_if_no_test_db() {
return None;
}
Some(crate::common::test_helpers::create_test_db_pool())
}
#[tokio::test]
async fn test_bridge_to_auth_state_admin_perms() {
let pool = match make_test_pool().await {
Some(p) => p,
None => {
eprintln!(
"[skip] TEST_DATABASE_URL not set — test requires real DbPool for AuthState::new"
);
return;
}
};
let api_key_id = crate::domain::id::Id::generate();
let perms = vec!["crawlrs:admin".to_string()];
let team_id = crate::domain::id::Id::generate();
let auth_state = bridge_to_auth_state(pool, api_key_id, &perms, team_id)
.await
.expect("admin bridge should succeed");
assert_eq!(auth_state.api_key_id, api_key_id);
assert_eq!(auth_state.team_id, team_id);
assert!(auth_state.scope.read);
assert!(auth_state.scope.write);
assert!(auth_state.scope.admin);
assert!(auth_state.scope.has_permission(ScopePermission::Admin));
}
#[tokio::test]
async fn test_bridge_to_auth_state_read_perms() {
let pool = match make_test_pool().await {
Some(p) => p,
None => {
eprintln!(
"[skip] TEST_DATABASE_URL not set — test requires real DbPool for AuthState::new"
);
return;
}
};
let api_key_id = crate::domain::id::Id::generate();
let perms = vec!["crawlrs:read".to_string()];
let team_id = crate::domain::id::Id::generate();
let auth_state = bridge_to_auth_state(pool, api_key_id, &perms, team_id)
.await
.expect("read bridge should succeed");
assert_eq!(auth_state.api_key_id, api_key_id);
assert_eq!(auth_state.team_id, team_id);
assert!(auth_state.scope.read);
assert!(!auth_state.scope.write);
assert!(!auth_state.scope.admin);
}
#[tokio::test]
async fn test_bridge_to_auth_state_empty_perms_denied_scope() {
let pool = match make_test_pool().await {
Some(p) => p,
None => {
eprintln!(
"[skip] TEST_DATABASE_URL not set — test requires real DbPool for AuthState::new"
);
return;
}
};
let api_key_id = crate::domain::id::Id::generate();
let perms: Vec<String> = vec![];
let team_id = crate::domain::id::Id::generate();
let auth_state = bridge_to_auth_state(pool, api_key_id, &perms, team_id)
.await
.expect("empty perms should still bridge successfully");
assert_eq!(auth_state.api_key_id, api_key_id);
assert_eq!(auth_state.team_id, team_id);
assert!(!auth_state.scope.read);
assert!(!auth_state.scope.write);
assert!(!auth_state.scope.admin);
}
#[tokio::test]
async fn test_bridge_to_auth_state_unknown_perms_denied_scope() {
let pool = match make_test_pool().await {
Some(p) => p,
None => {
eprintln!(
"[skip] TEST_DATABASE_URL not set — test requires real DbPool for AuthState::new"
);
return;
}
};
let api_key_id = crate::domain::id::Id::generate();
let perms = vec!["otherapp:admin".to_string(), "foo:read".to_string()];
let team_id = crate::domain::id::Id::generate();
let auth_state = bridge_to_auth_state(pool, api_key_id, &perms, team_id)
.await
.expect("unknown perms should still bridge successfully");
assert!(!auth_state.scope.read);
assert!(!auth_state.scope.write);
assert!(!auth_state.scope.admin);
}
#[test]
fn test_from_garrison_401_to_invalid_key() {
let cases = vec![
garrison::error::GarrisonError::NotLogin("test".to_string()),
garrison::error::GarrisonError::InvalidToken("test".to_string()),
garrison::error::GarrisonError::TokenRevoked("test".to_string()),
garrison::error::GarrisonError::ExpiredToken("test".to_string()),
];
for err in cases {
let auth_err = AuthError::from_garrison(err);
match auth_err {
AuthError::InvalidKey => {}
other => panic!("expected InvalidKey, got {:?}", other),
}
}
}
#[test]
fn test_from_garrison_403_disable_service_to_inactive_key() {
let err = garrison::error::GarrisonError::DisableService {
service: "default".to_string(),
until: None,
};
let auth_err = AuthError::from_garrison(err);
match auth_err {
AuthError::InactiveKey => {}
other => panic!("expected InactiveKey, got {:?}", other),
}
}
#[test]
fn test_from_garrison_403_others_to_forbidden() {
let cases = vec![
garrison::error::GarrisonError::NotPermission("test".to_string()),
garrison::error::GarrisonError::NotRole("test".to_string()),
garrison::error::GarrisonError::SmsChannelRecycled,
];
for err in cases {
let auth_err = AuthError::from_garrison(err);
match auth_err {
AuthError::Forbidden(_) => {}
other => panic!("expected Forbidden, got {:?}", other),
}
}
}
#[test]
fn test_from_garrison_firewall_blocked_to_rate_limited() {
let auth_err = AuthError::from_garrison(garrison::error::GarrisonError::FirewallBlocked(
"bruteforce".to_string(),
));
match auth_err {
AuthError::RateLimited => {}
other => panic!("expected RateLimited, got {:?}", other),
}
}
#[test]
fn test_from_garrison_429_to_rate_limited() {
let err = garrison::error::GarrisonError::SmsRateLimitExceeded {
window: "hourly".to_string(),
};
let auth_err = AuthError::from_garrison(err);
match auth_err {
AuthError::RateLimited => {}
other => panic!("expected RateLimited, got {:?}", other),
}
}
#[test]
fn test_from_garrison_502_to_network_error() {
let err = garrison::error::GarrisonError::Network("test".to_string());
let auth_err = AuthError::from_garrison(err);
match auth_err {
AuthError::NetworkError(_) => {}
other => panic!("expected NetworkError, got {:?}", other),
}
}
#[test]
fn test_from_garrison_501_to_not_implemented() {
let err = garrison::error::GarrisonError::NotImplemented("test".to_string());
let auth_err = AuthError::from_garrison(err);
match auth_err {
AuthError::NotImplemented(_) => {}
other => panic!("expected NotImplemented, got {:?}", other),
}
}
#[test]
fn test_from_garrison_400_to_invalid_param() {
let cases = vec![
garrison::error::GarrisonError::InvalidParam("test".to_string()),
garrison::error::GarrisonError::NotSafe {
reason: "MFA_TOTP_REQUIRED".to_string(),
},
garrison::error::GarrisonError::SmsVerifyMaxAttempts,
garrison::error::GarrisonError::SmsCodeNotFound,
];
for err in cases {
let auth_err = AuthError::from_garrison(err);
match auth_err {
AuthError::InvalidParam(_) => {}
other => panic!("expected InvalidParam, got {:?}", other),
}
}
}
#[test]
fn test_from_garrison_500_to_internal_error() {
let cases = vec![
garrison::error::GarrisonError::Dao("test".to_string()),
garrison::error::GarrisonError::Config("test".to_string()),
garrison::error::GarrisonError::Internal("test".to_string()),
garrison::error::GarrisonError::Session("test".to_string()),
garrison::error::GarrisonError::Annotation("test".to_string()),
garrison::error::GarrisonError::Context("test".to_string()),
garrison::error::GarrisonError::OAuth2("test".to_string()),
garrison::error::GarrisonError::InvalidStateTransition {
from: "A".to_string(),
to: "B".to_string(),
},
];
for err in cases {
let auth_err = AuthError::from_garrison(err);
match auth_err {
AuthError::InternalError(_) => {}
other => panic!("expected InternalError, got {:?}", other),
}
}
}
#[test]
fn test_from_garrison_exception_code_neg1_to_invalid_key() {
let err = garrison::error::GarrisonError::Exception(Box::new(
garrison::exception::GarrisonException::new(-1, "test"),
));
let auth_err = AuthError::from_garrison(err);
match auth_err {
AuthError::InvalidKey => {}
other => panic!("expected InvalidKey, got {:?}", other),
}
}
#[test]
fn test_from_garrison_exception_code_neg2_to_forbidden() {
let err = garrison::error::GarrisonError::Exception(Box::new(
garrison::exception::GarrisonException::new(-2, "test"),
));
let auth_err = AuthError::from_garrison(err);
match auth_err {
AuthError::Forbidden(_) => {}
other => panic!("expected Forbidden, got {:?}", other),
}
}
#[test]
fn test_from_garrison_exception_other_code_to_internal_error() {
let err = garrison::error::GarrisonError::Exception(Box::new(
garrison::exception::GarrisonException::new(100, "test"),
));
let auth_err = AuthError::from_garrison(err);
match auth_err {
AuthError::InternalError(_) => {}
other => panic!("expected InternalError, got {:?}", other),
}
}
}