use async_trait::async_trait;
use crate::error::GarrisonResult;
use super::decision::{AuthRequest, Decision};
use super::PermissionChecker;
#[async_trait]
pub trait Authorizer: Send + Sync {
async fn authorize(&self, req: &AuthRequest) -> GarrisonResult<Decision>;
}
#[async_trait]
impl<T: PermissionChecker> Authorizer for T {
async fn authorize(&self, req: &AuthRequest) -> GarrisonResult<Decision> {
PermissionChecker::authorize(self, req).await
}
}
#[cfg(test)]
mod tests {
use super::Authorizer;
use crate::core::permission::{
AuthRequest, Decision, DecisionReason, PermissionChecker, PermissionCheckerDefault,
};
use crate::error::{GarrisonError, GarrisonResult};
use crate::stp::GarrisonInterface;
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
enum MockOutcome {
Allow,
DenyNoMatch,
InvalidParam,
}
struct MockAuthorizer {
outcome: MockOutcome,
captured: Mutex<Option<AuthRequest>>,
}
impl MockAuthorizer {
fn new(outcome: MockOutcome) -> Self {
Self {
outcome,
captured: Mutex::new(None),
}
}
fn captured_request(&self) -> Option<AuthRequest> {
self.captured.lock().unwrap().clone()
}
}
#[async_trait]
impl Authorizer for MockAuthorizer {
async fn authorize(&self, req: &AuthRequest) -> GarrisonResult<Decision> {
*self.captured.lock().unwrap() = Some(req.clone());
match &self.outcome {
MockOutcome::Allow => Ok(Decision::allow()),
MockOutcome::DenyNoMatch => {
Ok(Decision::deny(DecisionReason::NoMatchingPermission))
},
MockOutcome::InvalidParam => Err(GarrisonError::InvalidParam(
"mock invalid param".to_string(),
)),
}
}
}
#[tokio::test]
async fn authorizer_allows_when_permission_held() {
let authorizer = MockAuthorizer::new(MockOutcome::Allow);
let req = AuthRequest::new("1001", "user:read");
let decision = authorizer.authorize(&req).await.expect("authorize ok");
assert!(decision.allowed);
assert_eq!(decision.reason, DecisionReason::ExplicitAllow);
}
#[tokio::test]
async fn authorizer_denies_when_permission_not_held() {
let authorizer = MockAuthorizer::new(MockOutcome::DenyNoMatch);
let req = AuthRequest::new("1001", "user:delete");
let decision = authorizer.authorize(&req).await.expect("authorize ok");
assert!(!decision.allowed);
assert_eq!(decision.reason, DecisionReason::NoMatchingPermission);
}
#[tokio::test]
async fn authorizer_returns_error_on_invalid_param() {
let authorizer = MockAuthorizer::new(MockOutcome::InvalidParam);
let req = AuthRequest::new("1001", "");
let result = authorizer.authorize(&req).await;
assert!(result.is_err());
match result.err() {
Some(GarrisonError::InvalidParam(_)) => {},
other => panic!("期望 InvalidParam,实际: {:?}", other),
}
}
#[tokio::test]
async fn authorizer_passes_auth_request_intact() {
let authorizer = MockAuthorizer::new(MockOutcome::Allow);
let req = AuthRequest {
login_id: "2002".to_string(),
tenant_id: 0,
action: "doc:write".to_string(),
resource: Some("doc:42".to_string()),
context: serde_json::Value::Null,
};
authorizer.authorize(&req).await.expect("authorize ok");
let captured = authorizer
.captured_request()
.expect("request should be captured");
assert_eq!(captured.login_id, "2002");
assert_eq!(captured.action, "doc:write");
assert_eq!(captured.resource.as_deref(), Some("doc:42"));
}
#[tokio::test]
async fn authorizer_passes_context_field() {
let authorizer = MockAuthorizer::new(MockOutcome::Allow);
let ctx = serde_json::json!({"ip": "10.0.0.1", "device": "mobile"});
let req = AuthRequest {
login_id: "1".to_string(),
tenant_id: 0,
action: "test".to_string(),
resource: None,
context: ctx.clone(),
};
authorizer.authorize(&req).await.expect("authorize ok");
let captured = authorizer
.captured_request()
.expect("request should be captured");
assert_eq!(captured.context, ctx);
assert_eq!(captured.context["ip"], serde_json::json!("10.0.0.1"));
assert_eq!(captured.context["device"], serde_json::json!("mobile"));
}
#[tokio::test]
async fn authorizer_passes_tenant_id() {
let authorizer = MockAuthorizer::new(MockOutcome::Allow);
let req = AuthRequest {
login_id: "1".to_string(),
tenant_id: 42,
action: "test".to_string(),
resource: None,
context: serde_json::Value::Null,
};
authorizer.authorize(&req).await.expect("authorize ok");
let captured = authorizer
.captured_request()
.expect("request should be captured");
assert_eq!(captured.tenant_id, 42);
}
#[tokio::test]
async fn authorizer_blanket_impl_works_with_permission_checker() {
let interface = MockInterface::new().with_perms("1001", vec!["user:read"]);
let interface_arc: Arc<dyn GarrisonInterface> = Arc::new(interface);
let checker = PermissionCheckerDefault::new(interface_arc);
let req = AuthRequest::new("1001", "user:read");
let decision_pc = PermissionChecker::authorize(&checker, &req)
.await
.expect("PermissionChecker::authorize ok");
let decision_auth = Authorizer::authorize(&checker, &req)
.await
.expect("Authorizer::authorize ok");
assert_eq!(decision_pc.allowed, decision_auth.allowed);
assert_eq!(decision_pc.reason, decision_auth.reason);
assert!(decision_auth.allowed);
assert_eq!(decision_auth.reason, DecisionReason::ExplicitAllow);
}
#[tokio::test]
async fn authorizer_can_be_used_as_dyn_trait() {
let authorizer: Box<dyn Authorizer> = Box::new(MockAuthorizer::new(MockOutcome::Allow));
let req = AuthRequest::new("1001", "user:read");
let decision = authorizer.authorize(&req).await.expect("authorize ok");
assert!(decision.allowed);
assert_eq!(decision.reason, DecisionReason::ExplicitAllow);
}
struct MockInterface {
permissions: HashMap<String, Vec<String>>,
roles: HashMap<String, Vec<String>>,
}
impl MockInterface {
fn new() -> Self {
Self {
permissions: HashMap::new(),
roles: HashMap::new(),
}
}
fn with_perms(mut self, login_id: &str, perms: Vec<&str>) -> Self {
self.permissions.insert(
login_id.to_string(),
perms.iter().map(|s| s.to_string()).collect(),
);
self
}
}
#[async_trait]
impl GarrisonInterface for MockInterface {
async fn get_permission_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(self.permissions.get(login_id).cloned().unwrap_or_default())
}
async fn get_role_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(self.roles.get(login_id).cloned().unwrap_or_default())
}
}
}