use super::*;
use crate::context::token_extract::extract_token_from_headers;
use crate::error::GarrisonError;
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::http::header::{self, HeaderMap, HeaderValue};
use actix_web::http::StatusCode;
use actix_web::ResponseError;
#[test]
fn response_error_not_login_returns_401() {
let err = GarrisonError::NotLogin("test".to_string());
assert_eq!(err.status_code(), StatusCode::UNAUTHORIZED);
let resp = err.error_response();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[test]
fn response_error_not_permission_returns_403() {
let err = GarrisonError::NotPermission("test".to_string());
assert_eq!(err.status_code(), StatusCode::FORBIDDEN);
}
#[test]
fn response_error_not_role_returns_403() {
let err = GarrisonError::NotRole("test".to_string());
assert_eq!(err.status_code(), StatusCode::FORBIDDEN);
}
#[test]
fn response_error_invalid_token_returns_401() {
let err = GarrisonError::InvalidToken("test".to_string());
assert_eq!(err.status_code(), StatusCode::UNAUTHORIZED);
}
#[test]
fn response_error_not_implemented_returns_501() {
let err = GarrisonError::NotImplemented("test".to_string());
assert_eq!(err.status_code(), StatusCode::NOT_IMPLEMENTED);
}
#[test]
fn response_error_exception_code_minus1_returns_401() {
let ex = crate::exception::GarrisonException::new(-1, "未登录");
let err = GarrisonError::Exception(Box::new(ex));
assert_eq!(err.status_code(), StatusCode::UNAUTHORIZED);
}
#[test]
fn response_error_exception_code_minus2_returns_403() {
let ex = crate::exception::GarrisonException::new(-2, "无权限");
let err = GarrisonError::Exception(Box::new(ex));
assert_eq!(err.status_code(), StatusCode::FORBIDDEN);
}
#[test]
fn error_response_contains_json_body() {
let err = GarrisonError::NotLogin("internal detail".to_string());
let resp = err.error_response();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
assert_eq!(
resp.headers()
.get("content-type")
.and_then(|v| v.to_str().ok()),
Some("application/json")
);
}
#[test]
fn extract_token_from_bearer_header() {
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_static("Bearer my_token_123"),
);
let config = GarrisonConfig::default_config();
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("my_token_123".to_string()));
}
#[test]
fn extract_token_bearer_case_insensitive() {
let config = GarrisonConfig::default_config();
for prefix in &["Bearer", "bearer", "BEARER", "BeArEr"] {
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_str(&format!("{} tok_{}", prefix, prefix)).unwrap(),
);
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(
token,
Some(format!("tok_{}", prefix)),
"前缀 '{}' 应能提取 token",
prefix
);
}
}
#[test]
fn extract_token_from_cookie() {
let mut headers = HeaderMap::new();
headers.insert(
header::COOKIE,
HeaderValue::from_static("garrison_token=cookie_tok_456"),
);
let config = GarrisonConfig::default_config();
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("cookie_tok_456".to_string()));
}
#[test]
fn extract_token_returns_none_when_missing() {
let headers = HeaderMap::new();
let config = GarrisonConfig::default_config();
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, None);
}
#[test]
fn extract_token_header_priority_over_cookie() {
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_static("Bearer header_tok"),
);
headers.insert(
header::COOKIE,
HeaderValue::from_static("garrison_token=cookie_tok"),
);
let config = GarrisonConfig::default_config();
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("header_tok".to_string()));
}
#[test]
fn extract_token_skips_header_when_disabled() {
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_static("Bearer header_tok"),
);
let mut config = GarrisonConfig::default_config();
config.is_read_header = false;
config.is_read_cookie = false;
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, None);
}
#[test]
fn router_new_initializes_defaults() {
let router = GarrisonRouter::new(Arc::new(GarrisonConfig::default_config()));
assert!(router.rules.is_empty());
}
#[test]
fn router_route_protected_adds_rule() {
let router = GarrisonRouter::new(Arc::new(GarrisonConfig::default_config()))
.route_protected("/api/user", Annotation::CheckLogin)
.route_protected("/api/admin", Annotation::CheckRole("admin".to_string()));
assert_eq!(router.rules.len(), 2);
assert!(router.rules.contains_key("/api/user"));
assert!(router.rules.contains_key("/api/admin"));
}
#[test]
fn router_into_middleware_transfers_state() {
let router = GarrisonRouter::new(Arc::new(GarrisonConfig::default_config()))
.route_protected("/api", Annotation::CheckLogin);
let mw = router.into_middleware();
assert_eq!(mw.rules.len(), 1);
assert!(Arc::strong_count(&mw.rules) >= 1);
}
#[test]
fn router_default_impl() {
let router = GarrisonRouter::default();
assert!(router.rules.is_empty());
}
use super::mock::{MockDao, MockInterface};
use crate::context::tenant::with_default_tenant;
use crate::dao::GarrisonDao;
use crate::manager::GarrisonManager;
use crate::stp::{GarrisonInterface, GarrisonUtil};
use actix_web::{test, web, App};
use serial_test::serial;
fn make_config() -> GarrisonConfig {
let mut config = GarrisonConfig::default_config();
config.timeout = 3600;
config.active_timeout = -1;
config.throw_on_not_login = false;
config
}
async fn init_manager(permissions: &[(&str, &[&str])], roles: &[(&str, &[&str])]) {
GarrisonManager::reset_for_test();
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = Arc::new(make_config());
let mut interface = MockInterface::new();
for (id, perms) in permissions {
interface = interface.with_permission(id, perms);
}
for (id, roles) in roles {
interface = interface.with_role(id, roles);
}
let interface: Arc<dyn GarrisonInterface> = Arc::new(interface);
GarrisonManager::builder()
.dao(dao)
.config(config)
.interface(interface)
.build()
.await
.unwrap();
}
struct OkService;
impl Service<ServiceRequest> for OkService {
type Response = ServiceResponse;
type Error = actix_web::Error;
type Future = std::future::Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(
&self,
_ctx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
std::task::Poll::Ready(Ok(()))
}
fn call(&self, req: ServiceRequest) -> Self::Future {
std::future::ready(Ok(
req.into_response(actix_web::HttpResponse::Ok().body("ok"))
))
}
}
async fn make_middleware_service(
rules: &[(&str, Annotation)],
) -> GarrisonMiddlewareService<OkService> {
let mut router = GarrisonRouter::new(Arc::new(make_config()));
for (path, ann) in rules {
router = router.route_protected(path, ann.clone());
}
let middleware = router.into_middleware();
<GarrisonMiddleware as Transform<OkService, ServiceRequest>>::new_transform(
&middleware,
OkService,
)
.await
.unwrap()
}
#[tokio::test]
#[serial]
async fn middleware_allows_unprotected_path() {
init_manager(&[], &[]).await;
let service = make_middleware_service(&[("/protected", Annotation::CheckLogin)]).await;
let req = test::TestRequest::get()
.uri("/unprotected")
.to_srv_request();
let resp = service.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn middleware_blocks_protected_path_without_token() {
init_manager(&[], &[]).await;
let service = make_middleware_service(&[("/protected", Annotation::CheckLogin)]).await;
let req = test::TestRequest::get().uri("/protected").to_srv_request();
let resp = service.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn middleware_allows_protected_path_with_valid_token() {
init_manager(&[], &[]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let service = make_middleware_service(&[("/protected", Annotation::CheckLogin)]).await;
let req = test::TestRequest::get()
.uri("/protected")
.insert_header(("Authorization", format!("Bearer {}", token)))
.to_srv_request();
let resp = service.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn middleware_blocks_permission_denied() {
init_manager(&[], &[]).await; let token = GarrisonUtil::login_simple("1001").await.unwrap();
let service = make_middleware_service(&[(
"/admin",
Annotation::CheckPermission("admin:read".to_string()),
)])
.await;
let req = test::TestRequest::get()
.uri("/admin")
.insert_header(("Authorization", format!("Bearer {}", token)))
.to_srv_request();
let resp = with_default_tenant(async { service.call(req).await.unwrap() }).await;
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn middleware_allows_ignore_path_without_token() {
init_manager(&[], &[]).await;
let service = make_middleware_service(&[("/public", Annotation::Ignore)]).await;
let req = test::TestRequest::get().uri("/public").to_srv_request();
let resp = service.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn new_transform_returns_service() {
init_manager(&[], &[]).await;
let service = make_middleware_service(&[("/x", Annotation::CheckLogin)]).await;
assert_eq!(service.rules.len(), 1);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn middleware_works_in_real_app_chain() {
init_manager(&[], &[]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let config = Arc::new(make_config());
let router =
GarrisonRouter::new(config).route_protected("/api/protected", Annotation::CheckLogin);
let middleware = router.into_middleware();
let app = test::init_service(
App::new()
.wrap(middleware)
.route("/api/protected", web::get().to(|| async { "ok" })),
)
.await;
let req = test::TestRequest::get()
.uri("/api/protected")
.insert_header(("Authorization", format!("Bearer {}", token)))
.to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let req = test::TestRequest::get().uri("/api/protected").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
GarrisonManager::reset_for_test();
}
#[cfg(feature = "tenant-isolation")]
async fn make_middleware_service_with_header_tenant(
rules: &[(&str, Annotation)],
) -> GarrisonMiddlewareService<OkService> {
let mut router = GarrisonRouter::new(Arc::new(make_config())).with_header_tenant();
for (path, ann) in rules {
router = router.route_protected(path, ann.clone());
}
let middleware = router.into_middleware();
<GarrisonMiddleware as Transform<OkService, ServiceRequest>>::new_transform(
&middleware,
OkService,
)
.await
.unwrap()
}
#[cfg(feature = "tenant-isolation")]
#[tokio::test]
#[serial]
async fn middleware_without_tenant_resolver_fails_closed_on_permission() {
init_manager(&[("1001", &["data:read"])], &[]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let service = make_middleware_service(&[(
"/data",
Annotation::CheckPermission("data:read".to_string()),
)])
.await;
let req = test::TestRequest::get()
.uri("/data")
.insert_header(("Authorization", format!("Bearer {}", token)))
.to_srv_request();
let resp = service.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
GarrisonManager::reset_for_test();
}
#[cfg(feature = "tenant-isolation")]
#[tokio::test]
#[serial]
async fn middleware_with_header_tenant_allows_permission_with_tenant_header() {
init_manager(&[("1001", &["data:read"])], &[]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let service = make_middleware_service_with_header_tenant(&[(
"/data",
Annotation::CheckPermission("data:read".to_string()),
)])
.await;
let req = test::TestRequest::get()
.uri("/data")
.insert_header(("Authorization", format!("Bearer {}", token)))
.insert_header(("X-Tenant-Id", "42"))
.to_srv_request();
let resp = service.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
GarrisonManager::reset_for_test();
}
#[cfg(feature = "tenant-isolation")]
#[tokio::test]
#[serial]
async fn middleware_with_header_tenant_rejects_missing_tenant_header() {
init_manager(&[("1001", &["data:read"])], &[]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let service = make_middleware_service_with_header_tenant(&[(
"/data",
Annotation::CheckPermission("data:read".to_string()),
)])
.await;
let req = test::TestRequest::get()
.uri("/data")
.insert_header(("Authorization", format!("Bearer {}", token)))
.to_srv_request();
let resp = service.call(req).await.unwrap();
assert_ne!(resp.status(), StatusCode::OK);
GarrisonManager::reset_for_test();
}
#[cfg(feature = "tenant-isolation")]
#[tokio::test]
#[serial]
async fn middleware_with_header_tenant_rejects_invalid_tenant_header() {
init_manager(&[("1001", &["data:read"])], &[]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let service = make_middleware_service_with_header_tenant(&[(
"/data",
Annotation::CheckPermission("data:read".to_string()),
)])
.await;
let req = test::TestRequest::get()
.uri("/data")
.insert_header(("Authorization", format!("Bearer {}", token)))
.insert_header(("X-Tenant-Id", "not-a-number"))
.to_srv_request();
let resp = service.call(req).await.unwrap();
assert_ne!(resp.status(), StatusCode::OK);
GarrisonManager::reset_for_test();
}
#[cfg(feature = "tenant-isolation")]
#[tokio::test]
#[serial]
async fn middleware_with_header_tenant_allows_check_login() {
init_manager(&[], &[]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let service =
make_middleware_service_with_header_tenant(&[("/protected", Annotation::CheckLogin)]).await;
let req = test::TestRequest::get()
.uri("/protected")
.insert_header(("Authorization", format!("Bearer {}", token)))
.insert_header(("X-Tenant-Id", "42"))
.to_srv_request();
let resp = service.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn extractor_check_login_returns_401_without_token() {
init_manager(&[], &[]).await;
let config = Arc::new(make_config());
let app = test::init_service(
App::new()
.app_data(web::Data::new(config))
.route("/login", web::get().to(check_login_handler)),
)
.await;
let req = test::TestRequest::get().uri("/login").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn extractor_check_login_passes_with_valid_token() {
init_manager(&[], &[]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let config = Arc::new(make_config());
let app = test::init_service(
App::new()
.app_data(web::Data::new(config))
.route("/login", web::get().to(check_login_handler)),
)
.await;
let req = test::TestRequest::get()
.uri("/login")
.insert_header(("Authorization", format!("Bearer {}", token)))
.to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status(), StatusCode::OK);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn extractor_check_login_uses_default_config_without_app_data() {
init_manager(&[], &[]).await;
let app =
test::init_service(App::new().route("/login", web::get().to(check_login_handler))).await;
let req = test::TestRequest::get().uri("/login").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn extractor_check_role_returns_401_without_token() {
init_manager(&[], &[]).await;
let config = Arc::new(make_config());
let app = test::init_service(
App::new()
.app_data(web::Data::new(config))
.route("/role", web::get().to(check_role_handler)),
)
.await;
let req = test::TestRequest::get().uri("/role").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn extractor_check_role_returns_403_without_role() {
init_manager(&[], &[]).await; let token = GarrisonUtil::login_simple("1001").await.unwrap();
let config = Arc::new(make_config());
let app = test::init_service(
App::new()
.app_data(web::Data::new(config))
.app_data(web::Data::new(super::RequiredRole("admin".to_string())))
.route("/role", web::get().to(check_role_handler)),
)
.await;
let req = test::TestRequest::get()
.uri("/role")
.insert_header(("Authorization", format!("Bearer {}", token)))
.to_request();
let resp = with_default_tenant(async { test::call_service(&app, req).await }).await;
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn extractor_check_role_reads_role_from_server_config() {
init_manager(&[], &[("1001", &["admin"])]).await; let token = GarrisonUtil::login_simple("1001").await.unwrap();
let config = Arc::new(make_config());
let app = test::init_service(
App::new()
.app_data(web::Data::new(config))
.app_data(web::Data::new(super::RequiredRole("admin".to_string())))
.route("/role", web::get().to(check_role_handler)),
)
.await;
let req = test::TestRequest::get()
.uri("/role")
.insert_header(("Authorization", format!("Bearer {}", token)))
.to_request();
let resp = with_default_tenant(async { test::call_service(&app, req).await }).await;
assert_eq!(resp.status(), StatusCode::OK);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn extractor_check_role_ignores_client_role_header() {
init_manager(&[], &[]).await; let token = GarrisonUtil::login_simple("1001").await.unwrap();
let config = Arc::new(make_config());
let app = test::init_service(
App::new()
.app_data(web::Data::new(config))
.app_data(web::Data::new(super::RequiredRole("admin".to_string())))
.route("/role", web::get().to(check_role_handler)),
)
.await;
let req = test::TestRequest::get()
.uri("/role")
.insert_header(("Authorization", format!("Bearer {}", token)))
.insert_header(("X-Garrison-Role", "admin"))
.to_request();
let resp = with_default_tenant(async { test::call_service(&app, req).await }).await;
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn extractor_check_permission_returns_401_without_token() {
init_manager(&[], &[]).await;
let config = Arc::new(make_config());
let app = test::init_service(
App::new()
.app_data(web::Data::new(config))
.route("/perm", web::get().to(check_permission_handler)),
)
.await;
let req = test::TestRequest::get().uri("/perm").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn extractor_check_permission_returns_403_without_permission() {
init_manager(&[], &[]).await; let token = GarrisonUtil::login_simple("1001").await.unwrap();
let config = Arc::new(make_config());
let app = test::init_service(
App::new()
.app_data(web::Data::new(config))
.app_data(web::Data::new(super::RequiredPermission(
"user:read".to_string(),
)))
.route("/perm", web::get().to(check_permission_handler)),
)
.await;
let req = test::TestRequest::get()
.uri("/perm")
.insert_header(("Authorization", format!("Bearer {}", token)))
.to_request();
let resp = with_default_tenant(async { test::call_service(&app, req).await }).await;
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn extractor_check_permission_reads_from_server_config() {
init_manager(&[("1001", &["user:read"])], &[]).await; let token = GarrisonUtil::login_simple("1001").await.unwrap();
let config = Arc::new(make_config());
let app = test::init_service(
App::new()
.app_data(web::Data::new(config))
.app_data(web::Data::new(super::RequiredPermission(
"user:read".to_string(),
)))
.route("/perm", web::get().to(check_permission_handler)),
)
.await;
let req = test::TestRequest::get()
.uri("/perm")
.insert_header(("Authorization", format!("Bearer {}", token)))
.to_request();
let resp = with_default_tenant(async { test::call_service(&app, req).await }).await;
assert_eq!(resp.status(), StatusCode::OK);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn extractor_check_permission_ignores_client_query_param() {
init_manager(&[], &[]).await; let token = GarrisonUtil::login_simple("1001").await.unwrap();
let config = Arc::new(make_config());
let app = test::init_service(
App::new()
.app_data(web::Data::new(config))
.app_data(web::Data::new(super::RequiredPermission(
"admin:write".to_string(),
)))
.route("/perm", web::get().to(check_permission_handler)),
)
.await;
let req = test::TestRequest::get()
.uri("/perm?permission=admin:write")
.insert_header(("Authorization", format!("Bearer {}", token)))
.to_request();
let resp = with_default_tenant(async { test::call_service(&app, req).await }).await;
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
GarrisonManager::reset_for_test();
}
async fn check_login_handler(_auth: CheckLogin) -> &'static str {
"ok"
}
async fn check_role_handler(_auth: CheckRole) -> &'static str {
"ok"
}
async fn check_permission_handler(_auth: CheckPermission) -> &'static str {
"ok"
}
#[tokio::test]
#[serial]
async fn router_with_interceptor_invoked_on_protected_path() {
use crate::error::GarrisonResult;
use crate::router::GarrisonInterceptor;
use std::sync::Mutex as StdMutex;
struct RecordingInterceptor(std::sync::Arc<StdMutex<usize>>);
#[async_trait::async_trait]
impl GarrisonInterceptor for RecordingInterceptor {
async fn pre_handle(&self, _path: &str, _annotation: &Annotation) -> GarrisonResult<()> {
*self.0.lock().unwrap() += 1;
Ok(())
}
}
init_manager(&[], &[]).await;
let calls = std::sync::Arc::new(StdMutex::new(0usize));
let router = GarrisonRouter::new(Arc::new(make_config()))
.with_interceptor(RecordingInterceptor(calls.clone()))
.route_protected("/protected", Annotation::CheckLogin);
let middleware = router.into_middleware();
let service = <GarrisonMiddleware as Transform<OkService, ServiceRequest>>::new_transform(
&middleware,
OkService,
)
.await
.unwrap();
let req = test::TestRequest::get().uri("/protected").to_srv_request();
let resp = service.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
*calls.lock().unwrap(),
1,
"自定义拦截器应在鉴权阶段被调用一次"
);
GarrisonManager::reset_for_test();
}
#[tokio::test]
#[serial]
async fn router_with_tenant_resolver_states_none_and_some() {
init_manager(&[], &[]).await;
let service_none = make_middleware_service(&[]).await;
assert!(
service_none.tenant_resolver.is_none(),
"默认构造不应注入租户解析器"
);
let router = GarrisonRouter::new(Arc::new(make_config()))
.with_tenant_resolver(crate::context::tenant::HeaderTenantResolver);
let middleware = router.into_middleware();
let service = <GarrisonMiddleware as Transform<OkService, ServiceRequest>>::new_transform(
&middleware,
OkService,
)
.await
.unwrap();
assert!(
service.tenant_resolver.is_some(),
"with_tenant_resolver 后应注入租户解析器"
);
GarrisonManager::reset_for_test();
}
#[cfg(feature = "tenant-isolation")]
#[tokio::test]
#[serial]
async fn middleware_with_tenant_resolver_entry_allows_permission_with_tenant_header() {
init_manager(&[("1001", &["data:read"])], &[]).await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let router = GarrisonRouter::new(Arc::new(make_config()))
.with_tenant_resolver(crate::context::tenant::HeaderTenantResolver)
.route_protected(
"/data",
Annotation::CheckPermission("data:read".to_string()),
);
let middleware = router.into_middleware();
let service = <GarrisonMiddleware as Transform<OkService, ServiceRequest>>::new_transform(
&middleware,
OkService,
)
.await
.unwrap();
let req = test::TestRequest::get()
.uri("/data")
.insert_header(("Authorization", format!("Bearer {}", token)))
.insert_header(("X-Tenant-Id", "42"))
.to_srv_request();
let resp = service.call(req).await.unwrap();
assert_eq!(
resp.status(),
StatusCode::OK,
"with_tenant_resolver 入口注入的解析器应使租户上下文生效"
);
GarrisonManager::reset_for_test();
}