use crate::i18n::translate_detail;
use axum::extract::ConnectInfo;
use axum::extract::Request;
use axum::http::header::CONTENT_TYPE;
use axum::http::StatusCode;
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::Json;
use dashmap::DashMap;
use limiteron::limiters::{Limiter, TokenBucketLimiter};
use serde_json::json;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::Instant;
use crate::backend::AuthBackend;
use crate::context::GarrisonPrincipal;
use crate::error::GarrisonError;
use crate::server::api_key_lockout::ApiKeyLockout;
struct BucketEntry {
limiter: Arc<TokenBucketLimiter>,
last_access: Instant,
}
pub struct RateLimitState {
buckets: DashMap<String, BucketEntry>,
capacity: u64,
refill_rate: u64,
max_entries: usize,
trusted_proxies: Vec<IpAddr>,
}
const DEFAULT_MAX_ENTRIES: usize = 100_000;
impl RateLimitState {
pub fn new(capacity: u32) -> Self {
Self::with_options(capacity, DEFAULT_MAX_ENTRIES, Vec::new())
}
pub fn with_options(capacity: u32, max_entries: usize, trusted_proxies: Vec<IpAddr>) -> Self {
let capacity = capacity as u64;
Self {
buckets: DashMap::with_capacity((max_entries / 64).max(64)),
capacity,
refill_rate: capacity,
max_entries: max_entries.max(1),
trusted_proxies,
}
}
pub fn bucket_count(&self) -> usize {
self.buckets.len()
}
}
pub fn parse_forwarded_for_rightmost(xff: &str, trusted_proxies: &[IpAddr]) -> Option<String> {
let hops: Vec<&str> = xff
.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.collect();
if hops.is_empty() {
return None;
}
for hop in hops.iter().rev() {
match hop.parse::<IpAddr>() {
Ok(ip) if trusted_proxies.contains(&ip) => continue,
Ok(_) => return Some((*hop).to_string()),
Err(_) => return None,
}
}
Some(hops[0].to_string())
}
pub fn extract_client_ip(req: &Request, trusted_proxies: &[IpAddr]) -> String {
let connect_ip = req
.extensions()
.get::<ConnectInfo<SocketAddr>>()
.map(|ci| ci.0.ip());
match connect_ip {
Some(ip) if trusted_proxies.contains(&ip) => req
.headers()
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|s| parse_forwarded_for_rightmost(s, trusted_proxies))
.unwrap_or_else(|| ip.to_string()),
Some(ip) => ip.to_string(),
None => "unknown".to_string(),
}
}
pub async fn rate_limit_middleware(
axum::extract::State(state): axum::extract::State<Arc<RateLimitState>>,
req: Request,
next: Next,
) -> Response {
let ip = extract_client_ip(&req, &state.trusted_proxies);
let is_new_ip = !state.buckets.contains_key(&ip);
let bucket = {
let mut entry = state
.buckets
.entry(ip.clone())
.or_insert_with(|| BucketEntry {
limiter: Arc::new(TokenBucketLimiter::new(state.capacity, state.refill_rate)),
last_access: Instant::now(),
});
entry.last_access = Instant::now();
entry.limiter.clone()
};
if is_new_ip && state.buckets.len() > state.max_entries {
if let Some(oldest_key) = state
.buckets
.iter()
.min_by_key(|e| e.value().last_access)
.map(|e| e.key().clone())
{
if oldest_key != ip {
state.buckets.remove(&oldest_key);
}
}
}
let allowed = match bucket.allow(1).await {
Ok(allowed) => allowed,
Err(e) => {
tracing::warn!(error = %e, "rate limiter error");
false
},
};
if !allowed {
let reset_secs = bucket
.remaining()
.await
.map(|snapshot| snapshot.reset_secs)
.unwrap_or(0);
return GarrisonError::RateLimited {
retry_after_secs: reset_secs,
}
.into_response();
}
next.run(req).await
}
#[derive(Debug, Clone)]
pub struct ApiKeyState {
pub api_key: String,
pub lockout: Arc<ApiKeyLockout>,
}
impl ApiKeyState {
pub fn new(api_key: impl Into<String>) -> Self {
let config = super::AuthServerConfig::default();
Self::with_lockout(
api_key,
config.api_key_lockout_threshold,
config.api_key_lockout_window_secs,
)
}
pub fn with_lockout(api_key: impl Into<String>, threshold: u32, window_secs: u64) -> Self {
Self {
api_key: api_key.into(),
lockout: Arc::new(ApiKeyLockout::new(threshold, window_secs)),
}
}
}
const CT_EQ_FIXED_WORKLOAD: usize = 256;
fn api_key_ct_eq(a: &str, b: &str) -> bool {
let a_bytes = a.as_bytes();
let b_bytes = b.as_bytes();
let len_ok = (a_bytes.len() <= CT_EQ_FIXED_WORKLOAD) & (b_bytes.len() <= CT_EQ_FIXED_WORKLOAD);
let mut a_padded = [0u8; CT_EQ_FIXED_WORKLOAD];
let mut b_padded = [0u8; CT_EQ_FIXED_WORKLOAD];
let a_len = a_bytes.len().min(CT_EQ_FIXED_WORKLOAD);
let b_len = b_bytes.len().min(CT_EQ_FIXED_WORKLOAD);
a_padded[..a_len].copy_from_slice(&a_bytes[..a_len]);
b_padded[..b_len].copy_from_slice(&b_bytes[..b_len]);
len_ok & crate::secure::ct_eq::constant_time_eq(&a_padded, &b_padded)
}
pub async fn api_key_auth_middleware(
axum::extract::State(state): axum::extract::State<Arc<ApiKeyState>>,
req: Request,
next: Next,
) -> Response {
if state.api_key.is_empty() {
return (
StatusCode::UNAUTHORIZED,
Json(json!({
"error": "unauthorized",
"message": translate_detail("server-invalid-api-key", &[])
})),
)
.into_response();
}
let source = req
.extensions()
.get::<ConnectInfo<SocketAddr>>()
.map(|ci| ci.0.ip().to_string())
.unwrap_or_else(|| "unknown".to_string());
if let Some(retry_after) = state.lockout.check_locked(&source) {
tracing::warn!(source = %source, retry_after, "{}", crate::i18n::translate_detail("logs-server-apikey-auth-locked-window", &[]));
return GarrisonError::RateLimited {
retry_after_secs: retry_after,
}
.into_response();
}
let mut header_values = req.headers().get_all("x-api-key").iter();
let first = header_values.next();
if header_values.next().is_some() {
let outcome = state.lockout.record_failure(&source);
tracing::warn!(source = %source, failures = outcome.count, "{}", crate::i18n::translate_detail("logs-server-apikey-duplicate-header", &[]));
return auth_failure_response(&state, &source, outcome);
}
let valid = first
.and_then(|v| v.to_str().ok())
.map(|k| api_key_ct_eq(k, &state.api_key))
.unwrap_or(false);
if !valid {
let outcome = state.lockout.record_failure(&source);
tracing::warn!(source = %source, failures = outcome.count, "{}", crate::i18n::translate_detail("logs-server-apikey-auth-failed", &[]));
return auth_failure_response(&state, &source, outcome);
}
state.lockout.record_success(&source);
next.run(req).await
}
fn auth_failure_response(
state: &ApiKeyState,
source: &str,
outcome: crate::server::api_key_lockout::FailureOutcome,
) -> Response {
if outcome.locked {
tracing::warn!(source = %source, threshold = state.lockout.threshold(), "{}", crate::i18n::translate_detail("logs-server-apikey-auth-locked-out", &[]));
return GarrisonError::RateLimited {
retry_after_secs: outcome.retry_after_secs,
}
.into_response();
}
(
StatusCode::UNAUTHORIZED,
Json(json!({
"error": "unauthorized",
"message": translate_detail("server-invalid-api-key", &[])
})),
)
.into_response()
}
pub async fn audit_log_middleware(req: Request, next: Next) -> Response {
let method = req.method().clone();
let path = req.uri().path().to_string();
let response = next.run(req).await;
let status = response.status();
tracing::info!(
method = %method,
path = %path,
status = status.as_u16(),
"auth_server_request"
);
response
}
const EXTERNAL_ALLOWED_PATHS: &[&str] = &[
"/api/v1/auth/login",
"/api/v1/auth/logout",
"/api/v1/auth/refresh",
];
pub fn is_external_allowed(path: &str) -> bool {
if EXTERNAL_ALLOWED_PATHS.contains(&path) {
return true;
}
if cfg!(feature = "oauth2-server") {
return matches!(
path,
"/oauth2/authorize" | "/oauth2/token" | "/oauth2/revoke"
);
}
false
}
pub async fn external_path_filter(req: Request, next: Next) -> Response {
if is_external_allowed(req.uri().path()) {
next.run(req).await
} else {
StatusCode::NOT_FOUND.into_response()
}
}
#[derive(Debug, Clone, Copy)]
pub struct ExternalLoginGate(pub bool);
pub async fn external_login_gate(
axum::extract::State(gate): axum::extract::State<ExternalLoginGate>,
req: Request,
next: Next,
) -> Response {
if !gate.0 && req.uri().path() == "/api/v1/auth/login" {
return StatusCode::NOT_FOUND.into_response();
}
next.run(req).await
}
pub async fn internal_path_filter(req: Request, next: Next) -> Response {
if is_external_allowed(req.uri().path()) {
StatusCode::NOT_FOUND.into_response()
} else {
next.run(req).await
}
}
#[derive(Debug, Clone)]
pub struct ClientIp(pub String);
#[derive(Debug, Clone)]
pub struct TrustedProxies(pub Vec<IpAddr>);
pub async fn inject_client_ip(mut req: Request, next: Next) -> Response {
let trusted_proxies = req
.extensions()
.get::<TrustedProxies>()
.map(|tp| tp.0.as_slice())
.unwrap_or_default();
let ip = extract_client_ip(&req, trusted_proxies);
#[cfg(feature = "session-hijack-detection")]
{
let _ = CLIENT_IP.try_with(|cell| {
*cell.borrow_mut() = Some(ip.clone());
});
}
req.extensions_mut().insert(ClientIp(ip));
next.run(req).await
}
#[cfg(feature = "session-hijack-detection")]
tokio::task_local! {
pub(crate) static CLIENT_IP: std::cell::RefCell<Option<String>>;
pub(crate) static CLIENT_USER_AGENT: std::cell::RefCell<Option<String>>;
}
#[cfg(feature = "session-hijack-detection")]
pub fn current_client_ip() -> Option<String> {
CLIENT_IP
.try_with(|cell| cell.borrow().clone())
.unwrap_or(None)
}
#[cfg(feature = "session-hijack-detection")]
pub fn current_user_agent() -> Option<String> {
CLIENT_USER_AGENT
.try_with(|cell| cell.borrow().clone())
.unwrap_or(None)
}
pub async fn inject_user_agent(req: Request, next: Next) -> Response {
#[cfg(feature = "session-hijack-detection")]
{
let ua = req
.headers()
.get(axum::http::header::USER_AGENT)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
CLIENT_USER_AGENT
.try_with(|cell| {
*cell.borrow_mut() = ua;
})
.ok();
}
next.run(req).await
}
pub async fn inject_login_client_ip(req: Request, next: Next) -> Response {
if req.uri().path() != "/api/v1/auth/login" {
return next.run(req).await;
}
let client_ip = req
.extensions()
.get::<ClientIp>()
.map(|c| c.0.clone())
.filter(|ip| ip != "unknown");
let (parts, body) = req.into_parts();
let bytes = match axum::body::to_bytes(body, 256 * 1024).await {
Ok(b) => b,
Err(e) => {
tracing::warn!(error = %e, "{}", crate::i18n::translate_detail("logs-server-inject-login-body-read-failed", &[]));
return (
StatusCode::PAYLOAD_TOO_LARGE,
[(
CONTENT_TYPE,
axum::http::HeaderValue::from_static("application/json"),
)],
payload_too_large_body(),
)
.into_response();
},
};
let mut json: serde_json::Value = match serde_json::from_slice(&bytes) {
Ok(v) => v,
Err(e) => {
tracing::warn!(error = %e, "inject_login_client_ip: malformed JSON body");
return (
StatusCode::BAD_REQUEST,
Json(json!({
"error": "bad_request",
"message": crate::i18n::translate_detail(
"server-http-body-invalid-json-msg",
&[]
)
})),
)
.into_response();
},
};
let should_inject = client_ip.is_some()
&& json
.get("params")
.and_then(|p| p.get("ip"))
.is_none_or(|v| v.is_null());
let new_body = if should_inject {
if let Some(params) = json.get_mut("params").and_then(|p| p.as_object_mut()) {
let ip = client_ip.unwrap_or_else(|| {
panic!(
"{}",
crate::i18n::translate_detail("server-inject-login-client-ip-invariant", &[],)
)
});
params.insert("ip".to_string(), serde_json::Value::String(ip));
}
axum::body::Body::from(serde_json::to_vec(&json).unwrap_or_else(|_| bytes.to_vec()))
} else {
axum::body::Body::from(bytes)
};
let req = Request::from_parts(parts, new_body);
next.run(req).await
}
fn rejection_body() -> String {
serde_json::json!({
"error": "bad_request",
"message": crate::i18n::translate_detail("server-http-body-validation-failed-msg", &[])
})
.to_string()
}
fn payload_too_large_body() -> String {
serde_json::json!({
"error": "payload_too_large",
"message": crate::i18n::translate_detail("server-http-body-too-large-msg", &[])
})
.to_string()
}
pub async fn sanitize_json_rejection_middleware(req: Request, next: Next) -> Response {
let response = next.run(req).await;
let is_rejection_status = matches!(
response.status(),
StatusCode::BAD_REQUEST
| StatusCode::UNSUPPORTED_MEDIA_TYPE
| StatusCode::UNPROCESSABLE_ENTITY
| StatusCode::PAYLOAD_TOO_LARGE
);
if !is_rejection_status {
return response;
}
let is_text_plain = response
.headers()
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("text/plain"));
if !is_text_plain {
return response;
}
let status = response.status();
let sanitized_body = if status == StatusCode::PAYLOAD_TOO_LARGE {
payload_too_large_body()
} else {
rejection_body()
};
let (_, body) = response.into_parts();
match axum::body::to_bytes(body, 64 * 1024).await {
Ok(bytes) if !bytes.is_empty() => {
let mut sanitized = axum::http::Response::new(axum::body::Body::from(sanitized_body));
*sanitized.status_mut() = status;
sanitized.headers_mut().insert(
CONTENT_TYPE,
axum::http::HeaderValue::from_static("application/json"),
);
sanitized
},
Ok(_) => {
let mut empty = axum::http::Response::new(axum::body::Body::empty());
*empty.status_mut() = status;
empty
},
Err(e) => {
tracing::warn!(error = %e, status = status.as_u16(), "{}", crate::i18n::translate_detail("logs-server-sanitize-rejection-body-read-failed", &[]));
(status, axum::body::Body::from(sanitized_body)).into_response()
},
}
}
pub async fn principal_inject_middleware(mut req: Request, next: Next) -> Response {
if let Some(backend) = req.extensions().get::<Arc<dyn AuthBackend>>().cloned() {
if let Some(token) = req
.headers()
.get("authorization")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.strip_prefix("Bearer "))
{
if let Ok(session) = backend.get_session(token).await {
req.extensions_mut().insert(GarrisonPrincipal {
login_id: session.login_id,
});
}
}
}
next.run(req).await
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use axum::http::Request;
use axum::routing::{get, post};
use axum::Extension;
use axum::Router;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use tower::ServiceExt;
fn ok_router() -> Router {
Router::new().route("/ping", get(|| async { "ok" }))
}
#[tokio::test]
async fn test_rate_limit_allows_under_limit() {
let state = Arc::new(RateLimitState::new(5));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
rate_limit_middleware,
));
for _ in 0..5 {
let resp = app
.clone()
.oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
}
#[tokio::test]
async fn test_rate_limit_blocks_over_limit() {
let state = Arc::new(RateLimitState::new(2));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
rate_limit_middleware,
));
for _ in 0..2 {
let resp = app
.clone()
.oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
let resp = app
.oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(json["error_code"], "RATE_LIMITED");
assert_eq!(json["error_id"], "ratelimit.rate_limited");
}
#[tokio::test]
async fn rate_limit_429_retry_after_matches_reset_secs() {
let state = Arc::new(RateLimitState::new(2));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
rate_limit_middleware,
));
for _ in 0..2 {
let resp = app
.clone()
.oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
let resp = app
.oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
let value = resp
.headers()
.get("Retry-After")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(0);
assert!(
value >= 1,
"Retry-After 应为 delta-seconds 且 >= 1,实际: {value}"
);
}
#[tokio::test]
async fn rate_limit_429_retry_after_floor_is_one() {
let state = Arc::new(RateLimitState::new(0));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
rate_limit_middleware,
));
let resp = app
.oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
let value = resp
.headers()
.get("Retry-After")
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
assert_eq!(value, "1", "reset_secs=0 应取下限 1");
}
#[tokio::test]
async fn rate_limit_429_body_carries_request_id() {
let state = Arc::new(RateLimitState::new(0));
let app = ok_router()
.layer(axum::middleware::from_fn_with_state(
state,
rate_limit_middleware,
))
.layer(axum::middleware::from_fn(
crate::web::request_id::request_id_middleware,
));
let resp = app
.oneshot(
Request::builder()
.uri("/ping")
.header("X-Request-ID", "gw-429-corr")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
assert_eq!(
resp.headers()
.get("X-Request-ID")
.and_then(|v| v.to_str().ok()),
Some("gw-429-corr")
);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(json["request_id"], "gw-429-corr");
}
#[tokio::test]
async fn rate_limit_bucket_cleanup_when_exceeds_max_entries() {
let state = Arc::new(RateLimitState::with_options(5, 2, Vec::new()));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state.clone(),
rate_limit_middleware,
));
for addr in ["10.0.0.1:8080", "10.0.0.2:8080", "10.0.0.3:8080"] {
let req = Request::builder()
.uri("/ping")
.extension(ConnectInfo::<SocketAddr>(addr.parse().unwrap()))
.body(Body::empty())
.unwrap();
let _resp = app.clone().oneshot(req).await.unwrap();
}
assert!(
state.bucket_count() <= 2,
"bucket 数量 {} 超过 max_entries=2",
state.bucket_count()
);
}
#[tokio::test]
async fn rate_limit_multi_ip_isolation() {
let state = Arc::new(RateLimitState::new(2));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
rate_limit_middleware,
));
for _ in 0..2 {
let req = Request::builder()
.uri("/ping")
.extension(ConnectInfo::<SocketAddr>("10.0.0.1:8080".parse().unwrap()))
.body(Body::empty())
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
let req = Request::builder()
.uri("/ping")
.extension(ConnectInfo::<SocketAddr>("10.0.0.1:8080".parse().unwrap()))
.body(Body::empty())
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::TOO_MANY_REQUESTS,
"IP 10.0.0.1 第 3 个请求应被限速"
);
for _ in 0..2 {
let req = Request::builder()
.uri("/ping")
.extension(ConnectInfo::<SocketAddr>("10.0.0.2:8080".parse().unwrap()))
.body(Body::empty())
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::OK,
"IP 10.0.0.2 应有独立配额,不受 10.0.0.1 影响"
);
}
}
#[test]
fn extract_client_ip_ignores_untrusted_proxy_xff() {
let trusted = [IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))];
let req = Request::builder()
.uri("/ping")
.header("x-forwarded-for", "1.2.3.4")
.extension(ConnectInfo::<SocketAddr>(
"203.0.113.1:1234".parse().unwrap(),
))
.body(Body::empty())
.unwrap();
assert_eq!(extract_client_ip(&req, &trusted), "203.0.113.1");
}
#[test]
fn extract_client_ip_uses_xff_from_trusted_proxy() {
let trusted = [IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))];
let req = Request::builder()
.uri("/ping")
.header("x-forwarded-for", "1.2.3.4")
.extension(ConnectInfo::<SocketAddr>("10.0.0.1:8080".parse().unwrap()))
.body(Body::empty())
.unwrap();
assert_eq!(extract_client_ip(&req, &trusted), "1.2.3.4");
}
#[test]
fn extract_client_ip_no_connect_info_returns_unknown() {
let trusted = [IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))];
let req = Request::builder()
.uri("/ping")
.header("x-forwarded-for", "1.2.3.4")
.body(Body::empty())
.unwrap();
assert_eq!(extract_client_ip(&req, &trusted), "unknown");
}
#[test]
fn extract_client_ip_trusted_proxy_no_xff_uses_connect_ip() {
let trusted = [IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))];
let req = Request::builder()
.uri("/ping")
.extension(ConnectInfo::<SocketAddr>("10.0.0.1:8080".parse().unwrap()))
.body(Body::empty())
.unwrap();
assert_eq!(extract_client_ip(&req, &trusted), "10.0.0.1");
}
#[tokio::test]
async fn test_api_key_auth_missing_header() {
let state = Arc::new(ApiKeyState::new("secret-key"));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
api_key_auth_middleware,
));
let resp = app
.oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_api_key_auth_wrong_key() {
let state = Arc::new(ApiKeyState::new("secret-key"));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
api_key_auth_middleware,
));
let resp = app
.oneshot(
Request::builder()
.uri("/ping")
.header("x-api-key", "wrong-key")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_api_key_auth_correct_key() {
let state = Arc::new(ApiKeyState::new("secret-key"));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
api_key_auth_middleware,
));
let resp = app
.oneshot(
Request::builder()
.uri("/ping")
.header("x-api-key", "secret-key")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_audit_log_middleware_passes_through() {
let app = ok_router().layer(axum::middleware::from_fn(audit_log_middleware));
let resp = app
.oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_api_key_auth_empty_key_rejects_all() {
let state = Arc::new(ApiKeyState::new(String::new()));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
api_key_auth_middleware,
));
let resp = app
.oneshot(
Request::builder()
.uri("/ping")
.header("x-api-key", "any-key")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[test]
fn test_api_key_ct_eq() {
assert!(api_key_ct_eq("abc", "abc"));
assert!(!api_key_ct_eq("abc", "abx"));
assert!(!api_key_ct_eq("abc", "ab"));
assert!(!api_key_ct_eq("abc", "abcd"));
assert!(api_key_ct_eq("", ""));
assert!(!api_key_ct_eq("", "a"));
assert!(!api_key_ct_eq("abcdefgh", "abcdefgx"));
}
#[test]
fn api_key_ct_eq_different_lengths_returns_false() {
assert!(!api_key_ct_eq("a", "ab"));
assert!(!api_key_ct_eq("ab", "a"));
assert!(!api_key_ct_eq("", "x"));
assert!(!api_key_ct_eq("x", ""));
assert!(!api_key_ct_eq("abc", "abcd"));
assert!(!api_key_ct_eq("abcd", "abc"));
assert!(!api_key_ct_eq("hello", "hello world"));
assert!(!api_key_ct_eq("0123456789abcdef", "0123456789abcdef0"));
}
#[test]
fn api_key_ct_eq_same_value_returns_true() {
assert!(api_key_ct_eq("", ""));
assert!(api_key_ct_eq("a", "a"));
assert!(api_key_ct_eq("abc", "abc"));
assert!(api_key_ct_eq("hello", "hello"));
assert!(api_key_ct_eq(
"sk-garrison-0123456789abcdef0123456789abcdef",
"sk-garrison-0123456789abcdef0123456789abcdef"
));
assert!(api_key_ct_eq("p@ssw0rd!#$%", "p@ssw0rd!#$%"));
}
#[test]
fn api_key_ct_eq_different_value_returns_false() {
assert!(!api_key_ct_eq("abc", "xbc"));
assert!(!api_key_ct_eq("abc", "abx"));
assert!(!api_key_ct_eq("abc", "axc"));
assert!(!api_key_ct_eq("a", "b"));
assert!(!api_key_ct_eq(
"sk-garrison-aaaaaaaaaaaaaaaaaaaaaaaa",
"sk-garrison-bbbbbbbbbbbbbbbbbbbbbbbb"
));
assert!(!api_key_ct_eq(
"sk-garrison-0123456789abcdef0123456789abcdef",
"sk-garrison-0123456789abcdef0123456789abcdeg"
));
}
#[test]
fn api_key_ct_eq_empty_strings_returns_true() {
assert!(api_key_ct_eq("", ""));
assert!(!api_key_ct_eq("", " "));
assert!(!api_key_ct_eq(" ", ""));
}
const INTERNAL_PATHS: &[&str] = &[
"/api/v1/auth/check-login",
"/api/v1/auth/check-permission",
"/api/v1/auth/check-role",
"/api/v1/auth/check-safe",
"/api/v1/auth/check-disable",
"/api/v1/auth/check-api-key",
"/api/v1/auth/get-token-info",
"/api/v1/auth/get-session",
"/api/v1/auth/kickout",
"/api/v1/auth/switch-to",
"/api/v1/auth/renew-to-equivalent",
"/api/v1/auth/health",
];
fn make_all_routes_router() -> Router {
Router::new()
.route("/api/v1/auth/login", post(|| async { "ok" }))
.route("/api/v1/auth/logout", post(|| async { "ok" }))
.route("/api/v1/auth/refresh", post(|| async { "ok" }))
.route("/api/v1/auth/check-login", post(|| async { "ok" }))
.route("/api/v1/auth/check-permission", post(|| async { "ok" }))
.route("/api/v1/auth/check-role", post(|| async { "ok" }))
.route("/api/v1/auth/check-safe", post(|| async { "ok" }))
.route("/api/v1/auth/check-disable", post(|| async { "ok" }))
.route("/api/v1/auth/check-api-key", post(|| async { "ok" }))
.route("/api/v1/auth/get-token-info", post(|| async { "ok" }))
.route("/api/v1/auth/get-session", post(|| async { "ok" }))
.route("/api/v1/auth/kickout", post(|| async { "ok" }))
.route("/api/v1/auth/switch-to", post(|| async { "ok" }))
.route("/api/v1/auth/renew-to-equivalent", post(|| async { "ok" }))
.route("/api/v1/auth/health", get(|| async { "ok" }))
}
#[tokio::test]
async fn test_external_path_filter_allows_external_paths() {
for &path in EXTERNAL_ALLOWED_PATHS {
let app =
make_all_routes_router().layer(axum::middleware::from_fn(external_path_filter));
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri(path)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::OK,
"外网 path-filter 应放行 {}",
path
);
}
}
#[tokio::test]
async fn test_external_login_gate_disabled_blocks_login() {
let app = make_all_routes_router().layer(axum::middleware::from_fn_with_state(
ExternalLoginGate(false),
external_login_gate,
));
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND, "默认应拒绝外网 login");
}
#[tokio::test]
async fn test_external_login_gate_enabled_allows_login() {
let app = make_all_routes_router().layer(axum::middleware::from_fn_with_state(
ExternalLoginGate(true),
external_login_gate,
));
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK, "显式启用后 login 应放行");
}
#[tokio::test]
async fn test_external_path_filter_blocks_internal_paths() {
for &path in INTERNAL_PATHS {
let method = if path == "/api/v1/auth/health" {
"GET"
} else {
"POST"
};
let app =
make_all_routes_router().layer(axum::middleware::from_fn(external_path_filter));
let resp = app
.oneshot(
Request::builder()
.method(method)
.uri(path)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::NOT_FOUND,
"外网 path-filter 应拒绝 {}",
path
);
}
}
#[tokio::test]
async fn test_internal_path_filter_blocks_external_paths() {
for &path in EXTERNAL_ALLOWED_PATHS {
let app =
make_all_routes_router().layer(axum::middleware::from_fn(internal_path_filter));
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri(path)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::NOT_FOUND,
"内网 path-filter 应拒绝 {}",
path
);
}
}
#[tokio::test]
async fn test_internal_path_filter_allows_internal_paths() {
for &path in INTERNAL_PATHS {
let method = if path == "/api/v1/auth/health" {
"GET"
} else {
"POST"
};
let app =
make_all_routes_router().layer(axum::middleware::from_fn(internal_path_filter));
let resp = app
.oneshot(
Request::builder()
.method(method)
.uri(path)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::OK,
"内网 path-filter 应放行 {}",
path
);
}
}
struct MockAuthBackend;
#[async_trait::async_trait]
impl AuthBackend for MockAuthBackend {
async fn login(
&self,
_login_id: &str,
_params: &crate::backend::types::LoginParams,
) -> crate::error::GarrisonResult<String> {
Ok("valid-token".to_string())
}
async fn logout(&self, _token: &str) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn check_login(&self, token: &str) -> crate::error::GarrisonResult<bool> {
Ok(token == "valid-token")
}
async fn check_permission(
&self,
_token: &str,
_permission: &str,
) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn check_role(&self, _token: &str, _role: &str) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn check_safe(&self, _token: &str) -> crate::error::GarrisonResult<bool> {
Ok(false)
}
async fn check_disable(&self, _token: &str) -> crate::error::GarrisonResult<bool> {
Ok(false)
}
async fn check_api_key(
&self,
_api_key: &str,
_namespace: &str,
) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn get_token_info(
&self,
token: &str,
) -> crate::error::GarrisonResult<crate::backend::types::TokenInfo> {
Ok(crate::backend::types::TokenInfo {
token: token.to_string(),
created_at: 1000,
last_active_at: 2000,
})
}
async fn get_session(
&self,
token: &str,
) -> crate::error::GarrisonResult<crate::backend::types::SessionData> {
if token == "valid-token" {
Ok(crate::backend::types::SessionData {
token: token.to_string(),
login_id: "1001".to_string(),
created_at: 1000,
last_active_at: 2000,
attrs: std::collections::HashMap::new(),
device: None,
ip: None,
user_agent: None,
safe_services: std::collections::HashMap::new(),
#[cfg(feature = "session-extra")]
dynamic_active_timeout: None,
#[cfg(feature = "session-extra")]
is_anon: false,
effective_timeout: None,
amr_ledger: Vec::new(),
auth_time: None,
})
} else {
Err(crate::error::GarrisonError::InvalidToken(
"token 无效".to_string(),
))
}
}
async fn kickout(&self, _login_id: &str) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn switch_to(
&self,
_token: &str,
_target_login_id: &str,
) -> crate::error::GarrisonResult<()> {
Ok(())
}
async fn renew_to_equivalent(&self, _token: &str) -> crate::error::GarrisonResult<String> {
Ok("new-token".to_string())
}
}
#[tokio::test]
async fn test_principal_inject_no_auth_header_passes_through() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let app = ok_router()
.layer(axum::middleware::from_fn(principal_inject_middleware))
.layer(Extension(backend));
let resp = app
.oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_principal_inject_invalid_token_passes_through() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let app = ok_router()
.layer(axum::middleware::from_fn(principal_inject_middleware))
.layer(Extension(backend));
let resp = app
.oneshot(
Request::builder()
.uri("/ping")
.header("authorization", "Bearer invalid-token")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_principal_inject_valid_token_injects_principal() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let app = Router::new()
.route(
"/principal",
get(
|principal: axum::extract::Extension<GarrisonPrincipal>| async move {
principal.0.login_id
},
),
)
.layer(axum::middleware::from_fn(principal_inject_middleware))
.layer(Extension(backend));
let resp = app
.oneshot(
Request::builder()
.uri("/principal")
.header("authorization", "Bearer valid-token")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(
std::str::from_utf8(&body).unwrap(),
"1001",
"有效 token 应注入 login_id=1001"
);
}
#[tokio::test]
async fn test_principal_inject_no_backend_passes_through() {
let app = ok_router().layer(axum::middleware::from_fn(principal_inject_middleware));
let resp = app
.oneshot(
Request::builder()
.uri("/ping")
.header("authorization", "Bearer some-token")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_inject_client_ip_direct_connection() {
let app = Router::new()
.route(
"/ip",
get(|req: super::Request| async move {
req.extensions()
.get::<ClientIp>()
.map(|c| c.0.clone())
.unwrap_or_default()
}),
)
.layer(axum::middleware::from_fn(inject_client_ip))
.layer(Extension(TrustedProxies(vec![])));
let req = Request::builder()
.uri("/ip")
.extension(ConnectInfo::<SocketAddr>(
"203.0.113.1:12345".parse().unwrap(),
))
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(std::str::from_utf8(&body).unwrap(), "203.0.113.1");
}
#[tokio::test]
async fn test_inject_client_ip_trusted_proxy_with_xff() {
let trusted = vec![IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))];
let app = Router::new()
.route(
"/ip",
get(|req: super::Request| async move {
req.extensions()
.get::<ClientIp>()
.map(|c| c.0.clone())
.unwrap_or_default()
}),
)
.layer(axum::middleware::from_fn(inject_client_ip))
.layer(Extension(TrustedProxies(trusted)));
let req = Request::builder()
.uri("/ip")
.header("x-forwarded-for", "198.51.100.5, 10.0.0.1")
.extension(ConnectInfo::<SocketAddr>("10.0.0.1:8080".parse().unwrap()))
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(
std::str::from_utf8(&body).unwrap(),
"198.51.100.5",
"可信代理场景应取 rightmost-untrusted 跳"
);
}
#[tokio::test]
async fn test_inject_client_ip_forged_leftmost_xff_ignored() {
let trusted = vec![IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))];
let app = Router::new()
.route(
"/ip",
get(|req: super::Request| async move {
req.extensions()
.get::<ClientIp>()
.map(|c| c.0.clone())
.unwrap_or_default()
}),
)
.layer(axum::middleware::from_fn(inject_client_ip))
.layer(Extension(TrustedProxies(trusted)));
let req = Request::builder()
.uri("/ip")
.header("x-forwarded-for", "1.2.3.4, 198.51.100.5, 10.0.0.1")
.extension(ConnectInfo::<SocketAddr>("10.0.0.1:8080".parse().unwrap()))
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(
std::str::from_utf8(&body).unwrap(),
"198.51.100.5",
"预伪造的最左值必须被忽略,取最右不可信跳"
);
}
#[test]
fn test_parse_forwarded_for_rightmost_all_trusted_returns_leftmost() {
let trusted = vec![
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)),
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2)),
];
assert_eq!(
super::parse_forwarded_for_rightmost("10.0.0.2, 10.0.0.1", &trusted),
Some("10.0.0.2".to_string())
);
}
#[test]
fn test_parse_forwarded_for_rightmost_empty_returns_none() {
assert_eq!(super::parse_forwarded_for_rightmost("", &[]), None);
assert_eq!(super::parse_forwarded_for_rightmost(" , ", &[]), None);
}
#[tokio::test]
async fn test_inject_client_ip_untrusted_proxy_ignores_xff() {
let trusted = vec![IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))];
let app = Router::new()
.route(
"/ip",
get(|req: super::Request| async move {
req.extensions()
.get::<ClientIp>()
.map(|c| c.0.clone())
.unwrap_or_default()
}),
)
.layer(axum::middleware::from_fn(inject_client_ip))
.layer(Extension(TrustedProxies(trusted)));
let req = Request::builder()
.uri("/ip")
.header("x-forwarded-for", "198.51.100.5")
.extension(ConnectInfo::<SocketAddr>(
"203.0.113.50:9999".parse().unwrap(),
))
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(
std::str::from_utf8(&body).unwrap(),
"203.0.113.50",
"非可信代理的 XFF 应被忽略"
);
}
#[tokio::test]
async fn test_inject_client_ip_no_connect_info() {
let app = Router::new()
.route(
"/ip",
get(|req: super::Request| async move {
req.extensions()
.get::<ClientIp>()
.map(|c| c.0.clone())
.unwrap_or_default()
}),
)
.layer(axum::middleware::from_fn(inject_client_ip))
.layer(Extension(TrustedProxies(vec![])));
let req = Request::builder().uri("/ip").body(Body::empty()).unwrap();
let resp = app.oneshot(req).await.unwrap();
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(std::str::from_utf8(&body).unwrap(), "unknown");
}
#[tokio::test]
async fn test_inject_login_client_ip_fills_null_ip() {
let app = Router::new()
.route(
"/api/v1/auth/login",
post(|body: axum::Json<serde_json::Value>| async move { axum::Json(body.0) }),
)
.layer(axum::middleware::from_fn(inject_login_client_ip))
.layer(Extension(ClientIp("203.0.113.1".to_string())));
let req = Request::builder()
.uri("/api/v1/auth/login")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_string(&serde_json::json!({
"login_id": "user1",
"params": { "ip": null, "ua": "test" }
}))
.unwrap(),
))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(
json["params"]["ip"].as_str().unwrap(),
"203.0.113.1",
"null ip 应被自动填充"
);
}
#[tokio::test]
async fn test_inject_login_client_ip_fills_missing_ip() {
let app = Router::new()
.route(
"/api/v1/auth/login",
post(|body: axum::Json<serde_json::Value>| async move { axum::Json(body.0) }),
)
.layer(axum::middleware::from_fn(inject_login_client_ip))
.layer(Extension(ClientIp("10.0.0.5".to_string())));
let req = Request::builder()
.uri("/api/v1/auth/login")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_string(&serde_json::json!({
"login_id": "user1",
"params": { "ua": "test" }
}))
.unwrap(),
))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(
json["params"]["ip"].as_str().unwrap(),
"10.0.0.5",
"缺失 ip 字段应被自动填充"
);
}
#[tokio::test]
async fn test_inject_login_client_ip_does_not_override_existing() {
let app = Router::new()
.route(
"/api/v1/auth/login",
post(|body: axum::Json<serde_json::Value>| async move { axum::Json(body.0) }),
)
.layer(axum::middleware::from_fn(inject_login_client_ip))
.layer(Extension(ClientIp("203.0.113.1".to_string())));
let req = Request::builder()
.uri("/api/v1/auth/login")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_string(&serde_json::json!({
"login_id": "user1",
"params": { "ip": "192.168.1.100" }
}))
.unwrap(),
))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(
json["params"]["ip"].as_str().unwrap(),
"192.168.1.100",
"已有 ip 值不应被覆盖"
);
}
#[tokio::test]
async fn test_inject_login_client_ip_skips_non_login_path() {
let app = Router::new()
.route(
"/api/v1/auth/logout",
post(|body: axum::Json<serde_json::Value>| async move { axum::Json(body.0) }),
)
.layer(axum::middleware::from_fn(inject_login_client_ip))
.layer(Extension(ClientIp("203.0.113.1".to_string())));
let req = Request::builder()
.uri("/api/v1/auth/logout")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_string(&serde_json::json!({ "token": "abc" })).unwrap(),
))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert!(json.get("params").is_none(), "非 login 路径不应注入 params");
}
#[tokio::test]
async fn test_inject_login_client_ip_unknown_skipped() {
let app = Router::new()
.route(
"/api/v1/auth/login",
post(|body: axum::Json<serde_json::Value>| async move { axum::Json(body.0) }),
)
.layer(axum::middleware::from_fn(inject_login_client_ip))
.layer(Extension(ClientIp("unknown".to_string())));
let req = Request::builder()
.uri("/api/v1/auth/login")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_string(&serde_json::json!({
"login_id": "user1",
"params": { "ua": "test" }
}))
.unwrap(),
))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert!(json["params"].get("ip").is_none(), "unknown IP 不应被注入");
}
#[tokio::test]
async fn inject_login_client_ip_oversize_body_returns_413() {
let app = Router::new()
.route(
"/api/v1/auth/login",
post(|body: axum::Json<serde_json::Value>| async move { axum::Json(body.0) }),
)
.layer(axum::middleware::from_fn(inject_login_client_ip))
.layer(Extension(ClientIp("203.0.113.1".to_string())));
let oversize = vec![b'x'; 256 * 1024 + 1];
let req = Request::builder()
.uri("/api/v1/auth/login")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(oversize))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::PAYLOAD_TOO_LARGE,
"超限 body 应返回 413 而非空 body 透传"
);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(json["error"], "payload_too_large");
}
#[derive(serde::Deserialize)]
struct SanitizeProbeBody {
#[serde(rename = "token")]
_token: String,
}
#[tokio::test]
async fn sanitize_json_rejection_hides_type_details_on_422() {
let app = Router::new()
.route(
"/api/v1/auth/check-login",
post(|_: axum::Json<SanitizeProbeBody>| async { "ok" }),
)
.layer(axum::middleware::from_fn(
sanitize_json_rejection_middleware,
));
let req = Request::builder()
.uri("/api/v1/auth/check-login")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(r#"{"token":{"a":1}}"#))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::UNPROCESSABLE_ENTITY,
"状态码保持 422(4xx 语义不变,仅清洗 body)"
);
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
"application/json",
"清洗后应为 JSON 错误体"
);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let text = std::str::from_utf8(&body).unwrap();
assert_eq!(
text,
rejection_body(),
"统一错误体,无任何类型/字段/偏移细节"
);
for leaked in ["SanitizeProbeBody", "expected", "line", "column", "token"] {
assert!(
!text.contains(leaked),
"响应不得泄露 {leaked},实际: {text}"
);
}
}
#[tokio::test]
async fn sanitize_json_rejection_unifies_400_and_415() {
let app = Router::new()
.route(
"/api/v1/auth/check-login",
post(|_: axum::Json<SanitizeProbeBody>| async { "ok" }),
)
.layer(axum::middleware::from_fn(
sanitize_json_rejection_middleware,
));
let req = Request::builder()
.uri("/api/v1/auth/check-login")
.method("POST")
.header("content-type", "application/json")
.body(Body::from("{bad json"))
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let text = std::str::from_utf8(&body).unwrap();
assert!(!text.contains("EOF"), "不得回显诊断细节: {text}");
assert!(serde_json::from_slice::<serde_json::Value>(&body).is_ok());
let req = Request::builder()
.uri("/api/v1/auth/check-login")
.method("POST")
.body(Body::from(r#"{"token":"x"}"#))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
assert!(serde_json::from_slice::<serde_json::Value>(&body).is_ok());
}
#[tokio::test]
async fn sanitize_json_rejection_unifies_413_oversize_body() {
let app = Router::new()
.route(
"/api/v1/auth/refresh",
post(|_: axum::Json<SanitizeProbeBody>| async { "ok" }),
)
.layer(axum::extract::DefaultBodyLimit::max(256 * 1024))
.layer(axum::middleware::from_fn(
sanitize_json_rejection_middleware,
));
let oversize = vec![b'x'; 256 * 1024 + 1];
let req = Request::builder()
.uri("/api/v1/auth/refresh")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(oversize))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::PAYLOAD_TOO_LARGE,
"超限 body 应保持 413 语义"
);
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
"application/json",
"裸 text/plain 413 应归一为 JSON 错误体"
);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let text = std::str::from_utf8(&body).unwrap();
assert_eq!(
text,
payload_too_large_body(),
"413 错误体应与 login 路径统一"
);
assert!(
!text.contains("buffer"),
"不得回显 axum 内部诊断,实际: {text}"
);
}
#[tokio::test]
async fn sanitize_json_rejection_passes_json_and_404_through() {
let app = Router::new()
.route(
"/biz",
post(|| async {
(
StatusCode::BAD_REQUEST,
axum::Json(serde_json::json!({"error": "custom"})),
)
}),
)
.layer(axum::middleware::from_fn(
sanitize_json_rejection_middleware,
));
let req = Request::builder()
.uri("/biz")
.method("POST")
.body(Body::empty())
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(json["error"], "custom", "业务 JSON 错误体不应被清洗");
let req = Request::builder()
.uri("/no-such-route")
.method("POST")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn api_key_auth_rejects_duplicate_header_wrong_first() {
let state = Arc::new(ApiKeyState::with_lockout("secret-key", 0, 300));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
api_key_auth_middleware,
));
let resp = app
.oneshot(
Request::builder()
.uri("/ping")
.header("x-api-key", "wrong-key")
.header("x-api-key", "secret-key")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::UNAUTHORIZED,
"重复头应 fail-closed 拒绝,不按首值/末值任一语义放行"
);
}
#[tokio::test]
async fn api_key_auth_rejects_duplicate_header_valid_first() {
let state = Arc::new(ApiKeyState::with_lockout("secret-key", 0, 300));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
api_key_auth_middleware,
));
let resp = app
.oneshot(
Request::builder()
.uri("/ping")
.header("x-api-key", "secret-key")
.header("x-api-key", "wrong-key")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn api_key_lockout_blocks_correct_key_after_threshold() {
let state = Arc::new(ApiKeyState::with_lockout("secret-key", 2, 300));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
api_key_auth_middleware,
));
let wrong = |app: &Router| {
let req = Request::builder()
.uri("/ping")
.header("x-api-key", "wrong")
.body(Body::empty())
.unwrap();
app.clone().oneshot(req)
};
let resp = wrong(&app).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "第 1 次失败仍 401");
let resp = wrong(&app).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::TOO_MANY_REQUESTS,
"达阈值请求本身即返回 429"
);
assert!(
resp.headers().get("Retry-After").is_some(),
"429 应携带 Retry-After 头"
);
let req = Request::builder()
.uri("/ping")
.header("x-api-key", "secret-key")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::TOO_MANY_REQUESTS,
"锁定窗口内正确 key 也应 429"
);
}
#[tokio::test]
async fn api_key_lockout_resets_on_success() {
let state = Arc::new(ApiKeyState::with_lockout("secret-key", 2, 300));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
api_key_auth_middleware,
));
let send = |key: &'static str, app: &Router| {
let req = Request::builder()
.uri("/ping")
.header("x-api-key", key)
.body(Body::empty())
.unwrap();
app.clone().oneshot(req)
};
assert_eq!(
send("wrong", &app).await.unwrap().status(),
StatusCode::UNAUTHORIZED
);
assert_eq!(
send("secret-key", &app).await.unwrap().status(),
StatusCode::OK
);
assert_eq!(
send("wrong", &app).await.unwrap().status(),
StatusCode::UNAUTHORIZED
);
assert_eq!(
send("secret-key", &app).await.unwrap().status(),
StatusCode::OK,
"成功清零后第二次失败(count=1)不应锁定"
);
}
#[tokio::test]
async fn api_key_lockout_window_expiry_unlocks() {
let state = Arc::new(ApiKeyState::with_lockout("secret-key", 1, 1));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
api_key_auth_middleware,
));
let req = Request::builder()
.uri("/ping")
.header("x-api-key", "wrong")
.body(Body::empty())
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::TOO_MANY_REQUESTS,
"阈值 1:首次失败即锁定"
);
tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
let req = Request::builder()
.uri("/ping")
.header("x-api-key", "secret-key")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::OK,
"窗口过期后锁定应解除,正确 key 恢复 200"
);
}
#[tokio::test]
async fn api_key_lockout_disabled_when_threshold_zero() {
let state = Arc::new(ApiKeyState::with_lockout("secret-key", 0, 300));
let app = ok_router().layer(axum::middleware::from_fn_with_state(
state,
api_key_auth_middleware,
));
for _ in 0..20 {
let req = Request::builder()
.uri("/ping")
.header("x-api-key", "wrong")
.body(Body::empty())
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "禁用态应恒 401");
}
let req = Request::builder()
.uri("/ping")
.header("x-api-key", "secret-key")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK, "禁用态下合法 key 应 200");
}
}