use axum::extract::ConnectInfo;
use axum::extract::Request;
use axum::http::StatusCode;
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::Json;
use limiteron::limiters::{Limiter, TokenBucketLimiter};
use parking_lot::Mutex;
use serde_json::json;
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::Instant;
use crate::backend::AuthBackend;
use crate::context::GarrisonPrincipal;
struct BucketEntry {
limiter: Arc<TokenBucketLimiter>,
last_access: Instant,
}
pub struct RateLimitState {
buckets: Mutex<HashMap<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: Mutex::new(HashMap::new()),
capacity,
refill_rate: capacity,
max_entries: max_entries.max(1),
trusted_proxies,
}
}
pub fn bucket_count(&self) -> usize {
self.buckets.lock().len()
}
}
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| s.split(',').next())
.map(|s| s.trim().to_string())
.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 bucket = {
let mut buckets = state.buckets.lock();
if !buckets.contains_key(&ip) && buckets.len() >= state.max_entries {
if let Some(oldest_key) = buckets
.iter()
.min_by_key(|(_, e)| e.last_access)
.map(|(k, _)| k.clone())
{
buckets.remove(&oldest_key);
}
}
let entry = 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()
};
let allowed = match bucket.allow(1).await {
Ok(allowed) => allowed,
Err(e) => {
tracing::warn!(error = %e, "rate limiter error");
false
},
};
if !allowed {
return (
StatusCode::TOO_MANY_REQUESTS,
Json(json!({
"error": "rate_limited",
"message": "请求过于频繁"
})),
)
.into_response();
}
next.run(req).await
}
#[derive(Debug, Clone)]
pub struct ApiKeyState {
pub api_key: String,
}
fn constant_time_eq(a: &str, b: &str) -> bool {
use subtle::ConstantTimeEq;
let a_bytes = a.as_bytes();
let b_bytes = b.as_bytes();
let len_eq = (a_bytes.len() as u64).ct_eq(&(b_bytes.len() as u64));
let max_len = a_bytes.len().max(b_bytes.len());
let mut byte_eq = subtle::Choice::from(1);
for i in 0..max_len {
let x = a_bytes.get(i).copied().unwrap_or(0);
let y = b_bytes.get(i).copied().unwrap_or(0);
byte_eq &= x.ct_eq(&y);
}
(len_eq & byte_eq).unwrap_u8() == 1
}
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": "无效的 API Key"
})),
)
.into_response();
}
let valid = req
.headers()
.get("x-api-key")
.and_then(|v| v.to_str().ok())
.map(|k| constant_time_eq(k, &state.api_key))
.unwrap_or(false);
if !valid {
return (
StatusCode::UNAUTHORIZED,
Json(json!({
"error": "unauthorized",
"message": "无效的 API Key"
})),
)
.into_response();
}
next.run(req).await
}
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()
}
}
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
}
}
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);
}
#[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 {
api_key: "secret-key".to_string(),
});
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 {
api_key: "secret-key".to_string(),
});
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 {
api_key: "secret-key".to_string(),
});
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 {
api_key: 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_constant_time_eq() {
assert!(constant_time_eq("abc", "abc"));
assert!(!constant_time_eq("abc", "abd"));
assert!(!constant_time_eq("abc", "ab"));
assert!(!constant_time_eq("abc", "abcd"));
assert!(constant_time_eq("", ""));
assert!(!constant_time_eq("", "a"));
assert!(!constant_time_eq("abcdefgh", "abcdefgx"));
}
#[test]
fn constant_time_eq_different_lengths_returns_false() {
assert!(!constant_time_eq("a", "ab"));
assert!(!constant_time_eq("ab", "a"));
assert!(!constant_time_eq("", "x"));
assert!(!constant_time_eq("x", ""));
assert!(!constant_time_eq("abc", "abcd"));
assert!(!constant_time_eq("abcd", "abc"));
assert!(!constant_time_eq("hello", "hello world"));
assert!(!constant_time_eq("0123456789abcdef", "0123456789abcdef0"));
}
#[test]
fn constant_time_eq_same_value_returns_true() {
assert!(constant_time_eq("", ""));
assert!(constant_time_eq("a", "a"));
assert!(constant_time_eq("abc", "abc"));
assert!(constant_time_eq("hello", "hello"));
assert!(constant_time_eq(
"sk-garrison-0123456789abcdef0123456789abcdef",
"sk-garrison-0123456789abcdef0123456789abcdef"
));
assert!(constant_time_eq("p@ssw0rd!#$%", "p@ssw0rd!#$%"));
}
#[test]
fn constant_time_eq_different_value_returns_false() {
assert!(!constant_time_eq("abc", "xbc"));
assert!(!constant_time_eq("abc", "abx"));
assert!(!constant_time_eq("abc", "axc"));
assert!(!constant_time_eq("a", "b"));
assert!(!constant_time_eq(
"sk-garrison-aaaaaaaaaaaaaaaaaaaaaaaa",
"sk-garrison-bbbbbbbbbbbbbbbbbbbbbbbb"
));
assert!(!constant_time_eq(
"sk-garrison-0123456789abcdef0123456789abcdef",
"sk-garrison-0123456789abcdef0123456789abcdeg"
));
}
#[test]
fn constant_time_eq_empty_strings_returns_true() {
assert!(constant_time_eq("", ""));
assert!(!constant_time_eq("", " "));
assert!(!constant_time_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_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 = "dynamic-active-timeout")]
dynamic_active_timeout: None,
#[cfg(feature = "anonymous-session")]
is_anon: false,
})
} 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);
}
}