use super::*;
use crate::backend::types::LoginParams;
use crate::error::GarrisonError;
#[cfg(feature = "oauth2-server")]
use crate::GarrisonDao;
use crate::GarrisonResult;
use async_trait::async_trait;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use tower::ServiceExt;
struct MockAuthBackend;
#[async_trait]
impl AuthBackend for MockAuthBackend {
async fn login(&self, login_id: &str, _params: &LoginParams) -> GarrisonResult<String> {
Ok(format!("token-{}", login_id))
}
async fn logout(&self, _token: &str) -> GarrisonResult<()> {
Ok(())
}
async fn check_login(&self, token: &str) -> GarrisonResult<bool> {
Ok(token.starts_with("token-"))
}
async fn check_permission(&self, _token: &str, _permission: &str) -> GarrisonResult<()> {
Ok(())
}
async fn check_role(&self, _token: &str, _role: &str) -> GarrisonResult<()> {
Ok(())
}
async fn check_safe(&self, _token: &str) -> GarrisonResult<bool> {
Ok(false)
}
async fn check_disable(&self, _token: &str) -> GarrisonResult<bool> {
Ok(false)
}
async fn check_api_key(&self, _api_key: &str, _namespace: &str) -> GarrisonResult<()> {
Ok(())
}
async fn get_token_info(
&self,
token: &str,
) -> 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) -> GarrisonResult<crate::backend::types::SessionData> {
Ok(crate::backend::types::SessionData {
token: token.to_string(),
login_id: "mock-user".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,
})
}
async fn kickout(&self, _login_id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn switch_to(&self, _token: &str, _target_login_id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn renew_to_equivalent(&self, token: &str) -> GarrisonResult<String> {
Ok(format!("renewed-{}", token))
}
}
fn make_server() -> GarrisonAuthServer {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
GarrisonAuthServer::new(backend)
.with_internal_api_key("test-api-key")
.with_rate_limit(100)
.with_external_login_enabled(true)
}
#[tokio::test]
async fn test_external_router_login_disabled_by_default() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_internal_api_key("test-api-key")
.with_rate_limit(100);
assert!(
!server.config.external_login_enabled,
"AuthServerConfig 默认应关闭外网 login"
);
let app = server.external_router();
let body = serde_json::json!({
"login_id": "user1",
"params": LoginParams::default()
});
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::NOT_FOUND,
"默认配置下外网 login 应返回 404(凭证校验由业务方注入后显式开启)"
);
}
#[tokio::test]
async fn test_external_router_logout_not_gated_by_login_flag() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_internal_api_key("test-api-key")
.with_rate_limit(100);
let app = server.external_router();
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/logout")
.header("content-type", "application/json")
.body(Body::from(r#"{"token":"token-user1"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::OK,
"logout 属凭证持有语义,不应被 login gate 拦截"
);
}
#[tokio::test]
async fn test_external_router_login_reachable_when_enabled() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_internal_api_key("test-api-key")
.with_rate_limit(100)
.with_external_login_enabled(true);
assert!(server.config.external_login_enabled);
let app = server.external_router();
let body = serde_json::json!({
"login_id": "user1",
"params": LoginParams::default()
});
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_external_router_handles_login() {
let server = make_server();
let app = server.external_router();
let body = serde_json::json!({
"login_id": "user1",
"params": LoginParams::default()
});
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let resp_json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(resp_json["data"], "token-user1");
}
#[tokio::test]
async fn test_internal_router_handles_health() {
let server = make_server();
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/api/v1/auth/health")
.header("x-api-key", "test-api-key")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let resp_json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(resp_json["data"], "ok");
}
#[tokio::test]
async fn test_internal_router_rejects_missing_api_key() {
let server = make_server();
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/api/v1/auth/health")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_external_router_rate_limit() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_internal_api_key("test-api-key")
.with_rate_limit(2)
.with_external_login_enabled(true);
let app = server.external_router();
let body = serde_json::json!({
"login_id": "user1",
"params": LoginParams::default()
});
for _ in 0..2 {
let resp = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
}
#[tokio::test]
async fn test_builder_methods() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(9000)
.with_internal_port(9001)
.with_rate_limit(50)
.with_internal_api_key("my-key");
assert_eq!(server.config.external_port, 9000);
assert_eq!(server.config.internal_port, 9001);
assert_eq!(server.config.external_rate_limit_per_ip, 50);
assert_eq!(server.config.internal_api_key, "my-key");
}
#[tokio::test]
async fn test_default_config() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend);
assert_eq!(server.config.external_port, 8080);
assert_eq!(server.config.internal_port, 8081);
assert_eq!(server.config.external_rate_limit_per_ip, 100);
assert!(
server.config.internal_api_key.is_empty(),
"Default internal_api_key 必须为空(fail-closed,M-SAST-1/M-5)"
);
}
#[cfg(feature = "backend-kit")]
#[tokio::test]
async fn test_new_with_kit_builds_server() {
use crate::backend::BackendModule;
use trait_kit::kit::AsyncKit;
let mut kit = AsyncKit::new();
kit.register::<BackendModule>()
.expect("register BackendModule failed");
let kit = kit.build().await.expect("kit build failed");
let server = GarrisonAuthServer::new_with_kit(kit)
.await
.expect("new_with_kit failed");
assert_eq!(server.config.external_port, 8080);
assert_eq!(server.config.internal_port, 8081);
}
#[cfg(feature = "backend-kit")]
#[tokio::test]
async fn test_new_with_kit_missing_module_fails() {
use trait_kit::kit::AsyncKit;
let kit = AsyncKit::new();
let kit = kit.build().await.expect("empty build should succeed");
let result = GarrisonAuthServer::new_with_kit(kit).await;
assert!(
result.is_err(),
"new_with_kit 应在 kit 未注册 BackendModule 时返回错误"
);
}
#[cfg(feature = "tls")]
#[tokio::test]
async fn test_with_tls_sets_config() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend).with_tls("/path/to/cert.pem", "/path/to/key.pem");
let tls_config = server
.tls_config
.as_ref()
.expect("with_tls 后 tls_config 必须为 Some");
assert_eq!(
tls_config.cert_path,
std::path::PathBuf::from("/path/to/cert.pem")
);
assert_eq!(
tls_config.key_path,
std::path::PathBuf::from("/path/to/key.pem")
);
}
#[cfg(feature = "tls")]
#[tokio::test]
async fn test_without_tls_config_is_none() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend);
assert!(
server.tls_config.is_none(),
"未调用 with_tls 时 tls_config 必须为 None"
);
}
#[cfg(feature = "tls")]
#[tokio::test]
async fn test_with_tls_chainable() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(9000)
.with_internal_port(9001)
.with_rate_limit(50)
.with_internal_api_key("my-key")
.with_tls("/cert.pem", "/key.pem");
assert_eq!(server.config.external_port, 9000);
assert_eq!(server.config.internal_port, 9001);
assert_eq!(server.config.external_rate_limit_per_ip, 50);
assert_eq!(server.config.internal_api_key, "my-key");
assert!(server.tls_config.is_some());
}
#[test]
fn test_to_api_response_ok() {
let result: Result<i32, GarrisonError> = Ok(42);
let resp = to_api_response(result);
assert_eq!(resp.data, Some(42));
assert!(resp.error_code.is_none());
assert!(resp.message.is_none());
}
#[test]
fn test_to_api_response_err() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> = Err(GarrisonError::Internal("test error".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("INTERNAL_ERROR"));
assert_eq!(resp.message.as_deref(), Some("Internal error"));
}
#[tokio::test]
async fn test_external_router_rejects_internal_path() {
let server = make_server();
let app = server.external_router();
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/api/v1/auth/check/login")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn test_internal_router_rejects_external_path() {
let server = make_server();
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.header("x-api-key", "test-api-key")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn test_internal_router_rejects_wrong_api_key() {
let server = make_server();
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/api/v1/auth/health")
.header("x-api-key", "wrong-api-key")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[test]
fn test_auth_server_config_default() {
let config = AuthServerConfig::default();
assert_eq!(config.external_port, 8080);
assert_eq!(config.internal_port, 8081);
assert_eq!(config.external_rate_limit_per_ip, 100);
assert!(
config.internal_api_key.is_empty(),
"Default internal_api_key 必须为空(fail-closed)"
);
assert_eq!(
config.external_bind,
std::net::IpAddr::from([0, 0, 0, 0]),
"默认外网绑定必须保持 0.0.0.0(向后兼容)"
);
assert_eq!(
config.internal_bind,
std::net::IpAddr::from([0, 0, 0, 0]),
"默认内网绑定必须保持 0.0.0.0(向后兼容)"
);
}
#[test]
fn test_auth_server_config_debug_redacts_internal_api_key() {
let secret = "0123456789abcdef0123456789abcdef";
let config = AuthServerConfig {
internal_api_key: secret.to_string(),
external_login_ack: Some(EXTERNAL_LOGIN_ACK.to_string()),
..AuthServerConfig::default()
};
let debug = format!("{:?}", config);
assert!(
debug.contains("[REDACTED]"),
"Debug 必须输出 [REDACTED] 占位,实际: {debug}"
);
assert!(
!debug.contains(secret),
"Debug 不得包含 internal_api_key 明文,实际: {debug}"
);
assert!(
debug.contains("AuthServerConfig") && debug.contains("external_port"),
"Debug 应保留非敏感字段,实际: {debug}"
);
}
#[test]
fn test_strict_security_tiers() {
let wildcard = std::net::IpAddr::from([0, 0, 0, 0]);
let loopback = std::net::IpAddr::from([127, 0, 0, 1]);
let strict_short = AuthServerConfig {
internal_api_key: "short-key-12".to_string(),
strict_security: true,
..AuthServerConfig::default()
};
assert!(
matches!(strict_short.validate(), Err(m) if m.contains("server-internal-api-key-too-short")),
"严格档短密钥应拒绝,实际: {:?}",
strict_short.validate()
);
let strict_unacked = AuthServerConfig {
internal_api_key: "0123456789abcdef0123456789abcdef".to_string(),
strict_security: true,
external_login_enabled: true,
external_bind: wildcard,
..AuthServerConfig::default()
};
assert!(
matches!(strict_unacked.validate(), Err(m) if m.contains("server-external-login-unacknowledged")),
"严格档未确认的外网登录暴露应拒绝,实际: {:?}",
strict_unacked.validate()
);
let strict_acked = AuthServerConfig {
external_login_ack: Some(EXTERNAL_LOGIN_ACK.to_string()),
..strict_unacked.clone()
};
assert!(
strict_acked.validate().is_ok(),
"严格档精确确认串应放行,实际: {:?}",
strict_acked.validate()
);
let strict_wildcard = AuthServerConfig {
internal_api_key: "0123456789abcdef0123456789abcdef".to_string(),
strict_security: true,
external_bind: wildcard,
internal_bind: wildcard,
..AuthServerConfig::default()
};
assert!(
strict_wildcard.validate().is_ok(),
"严格档通配绑定不应误伤,实际: {:?}",
strict_wildcard.validate()
);
for cfg in [
AuthServerConfig {
strict_security: false,
..strict_short.clone()
},
AuthServerConfig {
strict_security: false,
..strict_unacked.clone()
},
AuthServerConfig {
strict_security: false,
..strict_acked.clone()
},
AuthServerConfig {
strict_security: false,
..strict_wildcard.clone()
},
] {
assert!(
cfg.validate().is_ok(),
"非严格档应只告警不拒绝,实际: {:?}",
cfg.validate()
);
}
let _ = loopback;
}
#[derive(Clone)]
struct ServerLogCapture(Arc<std::sync::Mutex<Vec<String>>>);
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for ServerLogCapture {
type Writer = ServerLogCaptureWriter;
fn make_writer(&'a self) -> Self::Writer {
ServerLogCaptureWriter(self.0.clone())
}
}
struct ServerLogCaptureWriter(Arc<std::sync::Mutex<Vec<String>>>);
impl std::io::Write for ServerLogCaptureWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0
.lock()
.expect("日志缓冲锁应可用")
.push(String::from_utf8_lossy(buf).to_string());
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn count_warn(lines: &[String], needle: &str) -> usize {
lines
.iter()
.filter(|l| l.contains("WARN") && l.contains(needle))
.count()
}
#[test]
fn non_strict_tier_emits_each_warning_exactly_once() {
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let capture = ServerLogCapture(Arc::new(std::sync::Mutex::new(Vec::new())));
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(capture.clone()),
);
let _guard = subscriber.set_default();
let relaxed = AuthServerConfig {
internal_api_key: "short-key-12".to_string(),
strict_security: false,
external_login_enabled: true,
external_bind: std::net::IpAddr::from([0, 0, 0, 0]),
internal_bind: std::net::IpAddr::from([0, 0, 0, 0]),
external_login_ack: None,
..AuthServerConfig::default()
};
assert!(relaxed.validate().is_ok(), "非严格档应放行");
let lines = capture.0.lock().expect("日志缓冲锁应可用").clone();
assert_eq!(
count_warn(&lines, "server-internal-api-key-too-short"),
1,
"短密钥告警应恰好一次,实际捕获: {:?}",
lines
);
assert!(
lines
.iter()
.any(|l| l.contains("server-internal-api-key-too-short")
&& l.contains("1.0")
&& l.contains("min=32")),
"短密钥告警应含 1.0 迁移说明与下限,实际: {:?}",
lines
);
assert_eq!(
count_warn(&lines, "server-external-login-unacknowledged"),
1,
"外网登录未 ACK 告警应恰好一次,实际捕获: {:?}",
lines
);
assert!(
lines
.iter()
.any(|l| l.contains("server-external-login-unacknowledged")
&& l.contains("external_login_ack")
&& l.contains("1.0")),
"未 ACK 告警应含 external_login_ack 与 1.0 迁移说明,实际: {:?}",
lines
);
assert_eq!(
count_warn(&lines, "server-wildcard-bind-default"),
1,
"通配绑定告警应恰好一次(双端均通配也只一行),实际捕获: {:?}",
lines
);
assert!(
lines
.iter()
.any(|l| l.contains("server-wildcard-bind-default")
&& l.contains("with_external_bind")
&& l.contains("with_internal_bind")
&& l.contains("1.0")),
"通配绑定告警应同时给出 with_external_bind / with_internal_bind 与 1.0 迁移,实际: {:?}",
lines
);
let strict_lines_base = capture.0.lock().expect("日志缓冲锁应可用").len();
let strict = AuthServerConfig {
strict_security: true,
..relaxed.clone()
};
assert!(strict.validate().is_err(), "严格档应拒绝");
let lines_after = capture.0.lock().expect("日志缓冲锁应可用").clone();
assert_eq!(
lines_after.len(),
strict_lines_base,
"严格档不得追加告警(它走拒绝分支),新增: {:?}",
&lines_after[strict_lines_base..]
);
}
#[test]
fn test_with_bind_builders() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let loopback = std::net::IpAddr::from([127, 0, 0, 1]);
let v6_loopback = std::net::IpAddr::from([0, 0, 0, 0, 0, 0, 0, 1]);
let server = GarrisonAuthServer::new(backend)
.with_external_bind(loopback)
.with_internal_bind(v6_loopback);
assert_eq!(server.config.external_bind, loopback);
assert_eq!(server.config.internal_bind, v6_loopback);
}
#[tokio::test]
async fn test_listen_validates_config_first_external() {
let external_listener = tokio::net::TcpListener::bind("0.0.0.0:0")
.await
.expect("绑定测试端口应成功");
let external_port = external_listener
.local_addr()
.expect("获取端口应成功")
.port();
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(external_port)
.with_internal_port(0);
let result = server.listen().await;
assert!(
matches!(&result, Err(GarrisonError::Config(msg)) if msg.contains("server-internal-api-key-missing")),
"未配置 internal_api_key 时 listen 应返回 Config 错误(validate 短路),实际: {:?}",
result
);
}
#[tokio::test]
async fn test_listen_validates_config_first_internal() {
let internal_listener = tokio::net::TcpListener::bind("0.0.0.0:0")
.await
.expect("绑定测试端口应成功");
let internal_port = internal_listener
.local_addr()
.expect("获取端口应成功")
.port();
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(0) .with_internal_port(internal_port);
let result = server.listen().await;
assert!(
matches!(&result, Err(GarrisonError::Config(msg)) if msg.contains("server-internal-api-key-missing")),
"未配置 internal_api_key 时 listen 应返回 Config 错误(validate 短路),实际: {:?}",
result
);
}
#[tokio::test]
async fn test_listen_starts_and_runs() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(0)
.with_internal_port(0)
.with_internal_api_key("test-api-key");
tokio::select! {
result = server.listen() => {
panic!("listen 不应在 300ms 内返回: {:?}", result);
},
_ = tokio::time::sleep(std::time::Duration::from_millis(300)) => {
},
}
}
#[cfg_attr(
target_os = "macos",
ignore = "macOS lo0 默认仅含 127.0.0.1,无法绑定 127.0.0.2(平台能力差异,非缺陷)"
)]
#[tokio::test]
async fn test_listen_uses_configured_external_bind() {
let occupier = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("绑定 127.0.0.1 应成功");
let port = occupier.local_addr().expect("读取端口应成功").port();
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(port)
.with_external_bind(std::net::IpAddr::from([127, 0, 0, 2]))
.with_internal_port(0)
.with_internal_api_key("test-api-key");
tokio::select! {
result = server.listen() => {
panic!("配置 127.0.0.2 绑定应成功启动(不受 127.0.0.1 占用影响): {:?}", result);
},
_ = tokio::time::sleep(std::time::Duration::from_millis(300)) => {
},
}
}
#[tokio::test]
async fn test_listen_bind_failure_on_configured_external_bind() {
let occupier = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("绑定 127.0.0.1 应成功");
let port = occupier.local_addr().expect("读取端口应成功").port();
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(port)
.with_external_bind(std::net::IpAddr::from([127, 0, 0, 1]))
.with_internal_port(0)
.with_internal_api_key("test-api-key");
let result = server.listen().await;
assert!(
matches!(&result, Err(GarrisonError::Internal(msg)) if msg.contains("server-external-bind")),
"同地址端口冲突应返回 server-external-bind 错误,实际: {:?}",
result
);
}
#[cfg(feature = "tls")]
#[tokio::test]
async fn test_listen_tls_returns_error_when_cert_not_found() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(0)
.with_internal_port(0)
.with_tls("/nonexistent/cert.pem", "/nonexistent/key.pem");
let result = server.listen().await;
assert!(result.is_err(), "TLS 证书不存在时 listen 应返回错误");
}
#[test]
fn test_to_api_response_with_not_login_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> =
Err(GarrisonError::NotLogin("not logged in".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("NOT_LOGIN"));
assert_eq!(resp.message.as_deref(), Some("Not logged in"));
}
#[test]
fn test_to_api_response_with_dao_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> =
Err(GarrisonError::Dao("db connection failed".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("DAO_ERROR"));
assert_eq!(resp.message.as_deref(), Some("Data access error"));
}
#[test]
fn test_to_api_response_with_invalid_param_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> =
Err(GarrisonError::InvalidParam("missing field".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("INVALID_PARAM"));
assert_eq!(resp.message.as_deref(), Some("Invalid parameter"));
}
#[test]
fn test_to_api_response_with_not_permission_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> =
Err(GarrisonError::NotPermission("admin:read".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("NOT_PERMISSION"));
assert_eq!(resp.message.as_deref(), Some("Permission denied"));
}
#[test]
fn test_to_api_response_with_expired_token_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> =
Err(GarrisonError::ExpiredToken("token-abc".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("EXPIRED_TOKEN"));
assert_eq!(resp.message.as_deref(), Some("Token expired"));
}
#[test]
fn test_to_api_response_with_not_role_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> = Err(GarrisonError::NotRole("admin".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("NOT_ROLE"));
assert_eq!(resp.message.as_deref(), Some("Role required"));
}
#[test]
fn test_to_api_response_with_invalid_token_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> =
Err(GarrisonError::InvalidToken("bad-format".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("INVALID_TOKEN"));
assert_eq!(resp.message.as_deref(), Some("Invalid token"));
}
#[test]
fn test_to_api_response_with_token_revoked_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> =
Err(GarrisonError::TokenRevoked("revoked-token".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("TOKEN_REVOKED"));
assert_eq!(resp.message.as_deref(), Some("Token revoked"));
}
#[test]
fn test_to_api_response_with_config_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> =
Err(GarrisonError::Config("invalid config".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("CONFIG_ERROR"));
assert_eq!(resp.message.as_deref(), Some("Configuration error"));
}
#[test]
fn test_to_api_response_with_session_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> =
Err(GarrisonError::Session("session expired".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("SESSION_ERROR"));
assert_eq!(resp.message.as_deref(), Some("Session error"));
}
#[test]
fn test_to_api_response_with_network_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> = Err(GarrisonError::Network("timeout".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("NETWORK_ERROR"));
assert_eq!(resp.message.as_deref(), Some("Network error"));
}
#[test]
fn test_to_api_response_with_not_implemented_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> =
Err(GarrisonError::NotImplemented("not yet".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("NOT_IMPLEMENTED"));
assert_eq!(resp.message.as_deref(), Some("Not implemented"));
}
#[test]
fn test_to_api_response_with_firewall_blocked_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> =
Err(GarrisonError::FirewallBlocked("bruteforce".to_string()));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("FIREWALL_BLOCKED"));
assert_eq!(resp.message.as_deref(), Some("Firewall blocked"));
}
#[test]
fn test_to_api_response_with_disable_service_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> = Err(GarrisonError::DisableService {
service: "default".to_string(),
until: None,
});
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("DISABLE_SERVICE"));
assert_eq!(resp.message.as_deref(), Some("Account disabled"));
}
#[test]
fn test_to_api_response_with_not_safe_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> = Err(GarrisonError::NotSafe {
reason: "MFA_REQUIRED".to_string(),
});
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("NOT_SAFE"));
assert_eq!(
resp.message.as_deref(),
Some("Two-factor authentication required")
);
}
#[test]
fn test_to_api_response_with_sms_rate_limit_exceeded_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> = Err(GarrisonError::SmsRateLimitExceeded {
window: "hourly".to_string(),
});
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("SMS_RATE_LIMIT_EXCEEDED"));
assert_eq!(resp.message.as_deref(), Some("SMS rate limit exceeded"));
}
#[test]
fn test_to_api_response_with_sms_verify_max_attempts_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> = Err(GarrisonError::SmsVerifyMaxAttempts);
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("SMS_VERIFY_MAX_ATTEMPTS"));
assert_eq!(
resp.message.as_deref(),
Some("Verification code attempts exceeded")
);
}
#[test]
fn test_to_api_response_with_sms_code_not_found_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> = Err(GarrisonError::SmsCodeNotFound);
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("SMS_CODE_NOT_FOUND"));
assert_eq!(
resp.message.as_deref(),
Some("Verification code not found or expired")
);
}
#[test]
fn test_to_api_response_with_sms_channel_recycled_error() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let result: Result<i32, GarrisonError> = Err(GarrisonError::SmsChannelRecycled);
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("SMS_CHANNEL_RECYCLED"));
assert_eq!(resp.message.as_deref(), Some("SMS channel recycled"));
}
#[test]
fn test_to_api_response_with_exception_not_login() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
use crate::exception::GarrisonException;
let result: Result<i32, GarrisonError> = Err(GarrisonError::Exception(Box::new(
GarrisonException::new(-1, "请先登录"),
)));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("NOT_LOGIN"));
assert_eq!(resp.message.as_deref(), Some("Not logged in"));
}
#[test]
fn test_to_api_response_with_exception_not_permission() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
use crate::exception::GarrisonException;
let result: Result<i32, GarrisonError> = Err(GarrisonError::Exception(Box::new(
GarrisonException::new(-2, "无权限"),
)));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("NOT_PERMISSION"));
assert_eq!(resp.message.as_deref(), Some("Permission denied"));
}
#[test]
fn test_to_api_response_with_exception_other_code() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
use crate::exception::GarrisonException;
let result: Result<i32, GarrisonError> = Err(GarrisonError::Exception(Box::new(
GarrisonException::new(1001, "业务异常"),
)));
let resp = to_api_response(result);
assert!(resp.data.is_none());
assert_eq!(resp.error_code.as_deref(), Some("EXCEPTION"));
assert_eq!(resp.message.as_deref(), Some("Business exception"));
}
#[tokio::test]
async fn test_rate_limit_zero_rejects_all_requests() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_internal_api_key("test-api-key")
.with_rate_limit(0);
let app = server.external_router();
let body = serde_json::json!({
"login_id": "user1",
"params": LoginParams::default()
});
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::TOO_MANY_REQUESTS,
"rate_limit=0 时所有请求应被限速"
);
}
#[tokio::test]
async fn test_empty_internal_api_key_rejects_all() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_internal_api_key("")
.with_rate_limit(100);
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/api/v1/auth/health")
.header("x-api-key", "")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::UNAUTHORIZED,
"空 API Key 应拒绝所有内网请求"
);
}
#[cfg(feature = "oauth2-server")]
struct SimpleMockDao;
#[cfg(feature = "oauth2-server")]
#[async_trait]
impl GarrisonDao for SimpleMockDao {
async fn get(&self, _key: &str) -> GarrisonResult<Option<String>> {
Ok(None)
}
async fn set(&self, _key: &str, _value: &str, _ttl_seconds: u64) -> GarrisonResult<()> {
Ok(())
}
async fn update(&self, _key: &str, _value: &str) -> GarrisonResult<()> {
Ok(())
}
async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
Ok(())
}
async fn delete(&self, _key: &str) -> GarrisonResult<()> {
Ok(())
}
crate::atomic_test_fallback!();
}
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn simple_mock_dao_atomic_and_default_methods_coverage() {
let dao = SimpleMockDao;
let _ = dao.set_if_absent("a", "v", 60).await;
let _ = dao.get_and_delete("a").await;
let _ = dao.incr("c", 60).await;
let _ = dao.decr("c").await;
let _ = dao.rename("a", "b").await;
let _ = dao.compare_and_swap("b", Some("v"), "v2", 60).await;
let _ = dao.set_permanent("p", "v").await;
let _ = dao.get_timeout("k").await;
let _ = dao.get_with_ttl("k").await;
let _ = dao.keys("*").await;
let _ = dao.find_social_binding(0, "w", "o").await;
let _ = dao.insert_social_binding(0, "u", "w", "o", None, 0).await;
let _ = dao.compare_and_update_if_greater("k", 1, 60).await;
let _ = dao.eval_lua("r", vec![], vec![]).await;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
{
let _ = dao.insert_credit_consumption(0, "r", 1, 1, 1, 0).await;
let _ = dao.query_credit_consumption(0, 0, 0).await;
let _ = dao.query_role_hierarchy_edges(0).await;
let _ = dao.insert_role_hierarchy_edge(0, "c", "p").await;
let _ = dao.delete_role_hierarchy_edge(0, "c", "p").await;
}
}
#[cfg(feature = "oauth2-server")]
struct SimpleMockClientStore;
#[cfg(feature = "oauth2-server")]
#[async_trait]
impl crate::oauth2_server::client::OAuth2ClientStore for SimpleMockClientStore {
async fn create(
&self,
_client: crate::oauth2_server::client::OAuth2Client,
) -> GarrisonResult<()> {
Ok(())
}
async fn get(
&self,
_client_id: &str,
) -> GarrisonResult<Option<crate::oauth2_server::client::OAuth2Client>> {
Ok(None)
}
async fn update(
&self,
_client: crate::oauth2_server::client::OAuth2Client,
) -> GarrisonResult<()> {
Ok(())
}
async fn delete(&self, _client_id: &str) -> GarrisonResult<()> {
Ok(())
}
async fn list(&self) -> GarrisonResult<Vec<crate::oauth2_server::client::OAuth2Client>> {
Ok(Vec::new())
}
}
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn test_external_router_includes_oauth2_routes_when_set() {
let dao: Arc<dyn GarrisonDao> = Arc::new(SimpleMockDao);
let store: Arc<dyn crate::oauth2_server::client::OAuth2ClientStore> =
Arc::new(SimpleMockClientStore);
let oauth2_state = Arc::new(oauth2_routes::OAuth2State::new(
store,
dao,
"http://localhost/login".to_string(),
));
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_internal_api_key("test-api-key")
.with_rate_limit(100)
.with_oauth2(oauth2_state);
let app = server.external_router();
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/oauth2/authorize?response_type=code&client_id=test&redirect_uri=http://localhost/cb&code_challenge=test&code_challenge_method=S256&state=xyz")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_ne!(
resp.status(),
StatusCode::NOT_FOUND,
"with_oauth2 设置后 /oauth2/authorize 端点应存在"
);
}
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn test_internal_router_includes_oauth2_routes_when_set() {
let dao: Arc<dyn GarrisonDao> = Arc::new(SimpleMockDao);
let store: Arc<dyn crate::oauth2_server::client::OAuth2ClientStore> =
Arc::new(SimpleMockClientStore);
let oauth2_state = Arc::new(oauth2_routes::OAuth2State::new(
store,
dao,
"http://localhost/login".to_string(),
));
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_internal_api_key("test-api-key")
.with_rate_limit(100)
.with_oauth2(oauth2_state);
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/oauth2/introspect")
.header("x-api-key", "test-api-key")
.header("content-type", "application/x-www-form-urlencoded")
.body(Body::from("token=test"))
.unwrap(),
)
.await
.unwrap();
assert_ne!(
resp.status(),
StatusCode::NOT_FOUND,
"with_oauth2 设置后 /oauth2/introspect 端点应存在"
);
}
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn test_external_router_excludes_oauth2_routes_when_not_set() {
let server = make_server();
let app = server.external_router();
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/oauth2/authorize")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::NOT_FOUND,
"未设置 oauth2_state 时 /oauth2/authorize 应返回 404"
);
}
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn test_internal_router_excludes_oauth2_routes_when_not_set() {
let server = make_server();
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/oauth2/introspect")
.header("x-api-key", "test-api-key")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::NOT_FOUND,
"未设置 oauth2_state 时 /oauth2/introspect 应返回 404"
);
}
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn test_with_oauth2_chainable() {
let dao: Arc<dyn GarrisonDao> = Arc::new(SimpleMockDao);
let store: Arc<dyn crate::oauth2_server::client::OAuth2ClientStore> =
Arc::new(SimpleMockClientStore);
let oauth2_state = Arc::new(oauth2_routes::OAuth2State::new(
store,
dao,
"http://localhost/login".to_string(),
));
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(9000)
.with_internal_port(9001)
.with_rate_limit(50)
.with_internal_api_key("my-key")
.with_oauth2(oauth2_state);
assert_eq!(server.config.external_port, 9000);
assert_eq!(server.config.internal_port, 9001);
assert_eq!(server.config.external_rate_limit_per_ip, 50);
assert_eq!(server.config.internal_api_key, "my-key");
assert!(
server.oauth2_state.is_some(),
"with_oauth2 后 oauth2_state 必须为 Some"
);
}
#[tokio::test]
async fn test_with_rate_limit_large_value() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_internal_api_key("test-api-key")
.with_rate_limit(u32::MAX);
assert_eq!(server.config.external_rate_limit_per_ip, u32::MAX);
}
#[tokio::test]
async fn test_with_internal_api_key_accepts_str_and_string() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server1 = GarrisonAuthServer::new(backend.clone()).with_internal_api_key("str-key");
assert_eq!(server1.config.internal_api_key, "str-key");
let server2 = GarrisonAuthServer::new(backend).with_internal_api_key("string-key".to_string());
assert_eq!(server2.config.internal_api_key, "string-key");
}
#[tokio::test]
async fn test_default_body_limits() {
let config = AuthServerConfig::default();
assert_eq!(config.external_body_limit, 256 * 1024, "外网默认应为 256KB");
assert_eq!(config.internal_body_limit, 1024 * 1024, "内网默认应为 1MB");
}
#[tokio::test]
async fn test_with_body_limits() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_body_limit(512 * 1024)
.with_internal_body_limits(2 * 1024 * 1024);
assert_eq!(server.config.external_body_limit, 512 * 1024);
assert_eq!(server.config.internal_body_limit, 2 * 1024 * 1024);
}
#[tokio::test]
async fn test_listen_validate_fails_when_internal_api_key_empty() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(0)
.with_internal_port(0);
let result = server.listen().await;
assert!(
matches!(result, Err(GarrisonError::Config(ref msg)) if msg.contains("server-internal-api-key-missing")),
"空 internal_api_key 时 listen 应返回 Config 错误,实际: {:?}",
result
);
}
#[tokio::test]
async fn test_listen_bind_failure_external_port_with_valid_config() {
let external_listener = tokio::net::TcpListener::bind("0.0.0.0:0")
.await
.expect("占用测试端口应成功");
let external_port = external_listener.local_addr().unwrap().port();
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(external_port)
.with_internal_port(0)
.with_internal_api_key("test-api-key");
let result = server.listen().await;
assert!(
matches!(result, Err(GarrisonError::Internal(ref msg)) if msg.contains("server-external-bind")),
"外网端口被占用应返回 server-external-bind 错误,实际: {:?}",
result
);
}
#[tokio::test]
async fn test_listen_bind_failure_internal_port_with_valid_config() {
let internal_listener = tokio::net::TcpListener::bind("0.0.0.0:0")
.await
.expect("占用测试端口应成功");
let internal_port = internal_listener.local_addr().unwrap().port();
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_external_port(0)
.with_internal_port(internal_port)
.with_internal_api_key("test-api-key");
let result = server.listen().await;
assert!(
matches!(result, Err(GarrisonError::Internal(ref msg)) if msg.contains("server-internal-bind")),
"内网端口被占用应返回 server-internal-bind 错误,实际: {:?}",
result
);
}
#[tokio::test]
async fn test_with_trusted_proxies_and_rate_limit_max_entries() {
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let proxies = ["127.0.0.1".parse::<std::net::IpAddr>().unwrap()].to_vec();
let server = GarrisonAuthServer::new(backend)
.with_trusted_proxies(proxies.clone())
.with_rate_limit_max_entries(1234);
assert_eq!(server.config.rate_limit_trusted_proxies, proxies);
assert_eq!(server.config.rate_limit_max_entries, 1234);
}
#[cfg(feature = "tenant-isolation")]
#[tokio::test]
async fn test_with_tenant_resolver_states_none_and_some() {
use crate::context::tenant::HeaderTenantResolver;
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server_none = GarrisonAuthServer::new(backend.clone())
.with_internal_api_key("test-api-key")
.with_rate_limit(100);
assert!(
server_none.tenant_resolver.is_none(),
"默认不应注入租户解析器"
);
let _ = server_none.external_router();
let _ = server_none.internal_router();
let server_some = GarrisonAuthServer::new(backend)
.with_internal_api_key("test-api-key")
.with_rate_limit(100)
.with_tenant_resolver(Some(Arc::new(HeaderTenantResolver)));
assert!(
server_some.tenant_resolver.is_some(),
"with_tenant_resolver(Some(..)) 后应持有解析器"
);
let _ = server_some.external_router();
let _ = server_some.internal_router();
}
#[cfg(all(feature = "tenant-isolation", feature = "oauth2-server"))]
#[tokio::test]
async fn test_oauth2_with_tenant_resolver_routes_reachable() {
use crate::context::tenant::HeaderTenantResolver;
let dao: Arc<dyn GarrisonDao> = Arc::new(SimpleMockDao);
let store: Arc<dyn crate::oauth2_server::client::OAuth2ClientStore> =
Arc::new(SimpleMockClientStore);
let oauth2_state = Arc::new(oauth2_routes::OAuth2State::new(
store,
dao,
"http://localhost/login".to_string(),
));
let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
let server = GarrisonAuthServer::new(backend)
.with_internal_api_key("test-api-key")
.with_rate_limit(100)
.with_tenant_resolver(Some(Arc::new(HeaderTenantResolver)))
.with_oauth2(oauth2_state);
let external_app = server.external_router();
let internal_app = server.internal_router();
let resp = external_app
.oneshot(
Request::builder()
.method("GET")
.uri("/oauth2/authorize?response_type=code&client_id=test")
.header("x-tenant-id", "1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let status = resp.status();
assert_ne!(
status,
StatusCode::NOT_FOUND,
"oauth2 + 租户中间件组合下 /oauth2/authorize 应存在"
);
assert_ne!(
status,
StatusCode::INTERNAL_SERVER_ERROR,
"合法租户头不应被租户中间件拒绝(500),实际: {status}"
);
assert_ne!(
status,
StatusCode::UNAUTHORIZED,
"合法租户头不应触发 401,实际: {status}"
);
let resp = internal_app
.oneshot(
Request::builder()
.method("POST")
.uri("/oauth2/introspect")
.header("x-tenant-id", "1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_ne!(
resp.status(),
StatusCode::NOT_FOUND,
"oauth2 + 租户中间件组合下 /oauth2/introspect 应存在"
);
}
#[cfg(feature = "server-health-check")]
#[serial_test::serial]
#[tokio::test]
async fn test_health_probes_bypass_middleware() {
sdforge::health::clear_readiness_checks();
let server = make_server();
let app = server.external_router();
let resp = app
.clone()
.oneshot(
Request::builder()
.uri("/healthz")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK, "/healthz 外网端口应返回 200");
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(
json,
serde_json::json!({"status": "healthy"}),
"GAR-14: 外网 healthz 仅含 status,不回显版本号"
);
let app = server.external_router();
let resp = app
.oneshot(
Request::builder()
.uri("/readyz")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::NOT_FOUND,
"GAR-14: 外网端口不应暴露 /readyz"
);
let app = server.internal_router();
for uri in ["/healthz", "/readyz"] {
let resp = app
.clone()
.oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::OK,
"{uri} 内网端口应绕过 api_key_auth 返回 200"
);
}
}
#[cfg(feature = "server-health-check")]
#[serial_test::serial]
#[tokio::test]
async fn test_internal_readyz_details_gated_by_config() {
sdforge::health::register_readiness_check_fn("primary-db", || sdforge::health::CheckOutcome {
name: "primary-db".to_string(),
healthy: true,
details: Some(serde_json::json!({"host": "db.internal:5432", "latency_ms": 3})),
});
let server = make_server();
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.uri("/readyz")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let check = &json["checks"][0];
assert_eq!(check["name"], "primary-db");
assert!(
check.get("details").is_none(),
"默认应剥离 details,实际: {check}"
);
let server = make_server().with_health_details(true);
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.uri("/readyz")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(
json["checks"][0]["details"]["host"], "db.internal:5432",
"开启后 details 应透传"
);
sdforge::health::clear_readiness_checks();
}
#[cfg(feature = "server-health-check")]
#[serial_test::serial]
#[tokio::test]
async fn test_internal_readyz_failure_returns_503() {
sdforge::health::register_readiness_check_fn("downstream", || {
sdforge::health::CheckOutcome::unhealthy("downstream", "connection refused")
});
let server = make_server();
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.uri("/readyz")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(json["status"], "unavailable");
assert!(
json["checks"][0].get("details").is_none(),
"默认剥离 details(失败原因同样不外泄)"
);
sdforge::health::clear_readiness_checks();
}
#[tokio::test]
async fn test_external_router_sanitizes_422_type_leak() {
let server = make_server();
let app = server.external_router();
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.header("content-type", "application/json")
.body(Body::from("[1,2,3]".to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::UNPROCESSABLE_ENTITY,
"状态码保持 4xx"
);
assert_eq!(
resp.headers().get("content-type").unwrap(),
"application/json"
);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let text = std::str::from_utf8(&bytes).unwrap();
for leaked in [
"LoginRequest",
"LoginParams",
"struct",
"expected",
"line",
"column",
"login_id",
] {
assert!(
!text.contains(leaked),
"响应不得泄露 {leaked},实际: {text}"
);
}
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(json["error"], "bad_request");
}
#[tokio::test]
async fn test_external_router_oversize_body_returns_413() {
let server = make_server();
let app = server.external_router();
let oversize = vec![b'x'; 256 * 1024 + 1];
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.header("content-type", "application/json")
.extension(axum::extract::ConnectInfo(std::net::SocketAddr::new(
std::net::IpAddr::V4(std::net::Ipv4Addr::new(203, 0, 113, 1)),
40000,
)))
.body(Body::from(oversize))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::PAYLOAD_TOO_LARGE,
"超限 body 应返回 413 而非误导性 400/断连"
);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(json["error"], "payload_too_large");
}
#[tokio::test]
async fn test_internal_router_rejects_duplicate_api_key_header() {
let server = make_server().with_api_key_lockout(0, 300);
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/api/v1/auth/health")
.header("x-api-key", "test-api-key")
.header("x-api-key", "wrong-key")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::UNAUTHORIZED,
"重复 X-API-Key 头应 fail-closed 拒绝"
);
}
#[tokio::test]
async fn test_internal_router_get_session_without_caller_rejected() {
let server = make_server();
let app = server.internal_router();
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/get-session")
.header("content-type", "application/json")
.header("x-api-key", "test-api-key")
.body(Body::from(r#"{"token":"token-user1"}"#.to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.status(),
StatusCode::BAD_REQUEST,
"caller_login_id 缺失应 4xx fail-closed"
);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(json.get("data").is_none(), "拒绝响应不得携带会话数据");
}
#[cfg(feature = "web-security-headers")]
#[tokio::test]
async fn test_external_router_response_has_security_headers() {
let server = make_server();
let app = server.external_router();
let body = serde_json::json!({
"login_id": "user1",
"params": LoginParams::default()
});
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/auth/login")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers()
.get("cache-control")
.map(|v| v.to_str().unwrap()),
Some("no-store"),
"GAR-13: token 承载端点应带 Cache-Control: no-store(CWE-525)"
);
assert_eq!(
resp.headers()
.get("x-content-type-options")
.map(|v| v.to_str().unwrap()),
Some("nosniff")
);
assert_eq!(
resp.headers()
.get("x-frame-options")
.map(|v| v.to_str().unwrap()),
Some("DENY")
);
}