garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
Documentation
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 请求对象式授权器:提供以 [`AuthRequest`] 为入参、返回 [`Decision`] 的公开授权 trait
//! [`Authorizer`]。与内部 trait [`PermissionChecker`](绑定具体数据源)的区别:`Authorizer`
//! 不假设实现,任何授权引擎均可实现;blanket impl 让所有 `PermissionChecker` 自动获得实现。
//!
//! [`PermissionChecker`]: crate::core::permission::PermissionChecker

use async_trait::async_trait;

use crate::error::GarrisonResult;

use super::decision::{AuthRequest, Decision};
use super::PermissionChecker;

/// 请求对象式授权器 trait(公开 API,不假设实现,任何授权引擎可接入);blanket impl 让所有
/// [`PermissionChecker`] 自动实现并委托其 `authorize`。`Authorizer: Send + Sync` 且签名兼容
/// trait object,可用 `Box<dyn Authorizer>`。
///
/// # 使用示例
///
/// ```ignore
/// use garrison::prelude::*;
/// use std::sync::Arc;
///
/// // 任何 PermissionChecker 自动实现 Authorizer
/// let checker: Arc<dyn PermissionChecker> = ...;
/// let req = AuthRequest::new("1001", "user:read");
/// let decision: Decision = Authorizer::authorize(&*checker, &req).await?;
/// ```
///
/// [`PermissionChecker`]: crate::core::permission::PermissionChecker
#[async_trait]
pub trait Authorizer: Send + Sync {
    /// 鉴权决策:校验过程出错(如 DAO 故障、参数无效)返回 `Err(GarrisonError)`;
    /// "未持有权限"不是错误,返回 `Ok(Decision { allowed: false, .. })`。
    async fn authorize(&self, req: &AuthRequest) -> GarrisonResult<Decision>;
}

/// Blanket impl:任何 [`PermissionChecker`] 自动实现 [`Authorizer`](行为委托其 `authorize`),
/// 现有实现(如 `PermissionCheckerDefault`)无需重复实现。
///
/// [`PermissionChecker::authorize`]: crate::core::permission::PermissionChecker::authorize
#[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};

    /// Mock 行为枚举,控制 MockAuthorizer 返回的决策或错误。
    enum MockOutcome {
        Allow,
        DenyNoMatch,
        InvalidParam,
    }

    /// 测试用 MockAuthorizer:返回固定 Decision / Error 并捕获传入的 AuthRequest
    ///(隔离测试 trait 契约,不依赖 GarrisonLogicDefault)。
    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(),
                )),
            }
        }
    }

    // Authorizer trait 测试

    /// Authorizer::authorize 在允许场景返回 allowed=true 的 Decision。
    #[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);
    }

    /// Authorizer::authorize 在拒绝场景返回 allowed=false + NoMatchingPermission。
    #[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);
    }

    /// Authorizer::authorize 在参数无效时返回 InvalidParam 错误。
    #[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),
        }
    }

    /// Authorizer::authorize 完整传递 AuthRequest 的 login_id/action/resource 字段。
    #[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"));
    }

    /// Authorizer::authorize 正确传递 context 字段(serde_json::Value)。
    #[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"));
    }

    /// Authorizer::authorize 正确传递 tenant_id 字段。
    #[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);
    }

    /// blanket impl:PermissionCheckerDefault 自动实现 Authorizer,行为与 PermissionChecker::authorize
    /// 一致。
    #[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");

        // 两条路径应行为一致:内部 trait 与 blanket impl 的 Authorizer。
        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);
    }

    /// Authorizer 可作为 dyn trait(`Box<dyn Authorizer>`)构造并调用。
    #[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);
    }

    // 测试用 MockInterface(GarrisonInterface 实现,用于 blanket impl 测试)

    /// 测试用 mock GarrisonInterface(仅提供 permission/role 数据,供 PermissionCheckerDefault 使用)。
    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())
        }
    }
}