garrison 0.9.0

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

//! actix-web 框架适配模块:GarrisonRouter + FromRequest extractor + GarrisonMiddleware 完整集成。
//!
//! 模块拆分(接口隔离):`router.rs` 路由构建器、`middleware.rs` Transform/Service、
//! `extractor.rs` per-handler 鉴权、`error.rs` HeaderLookup + ResponseError、`mock.rs`/`tests.rs` 测试。
//!
//! ## 使用示例
//!
//! ```ignore
//! use garrison::prelude::*;
//! use garrison::web_actix::{GarrisonRouter, CheckLogin};
//! use actix_web::{App, HttpServer, web};
//!
//! async fn protected_handler(_auth: CheckLogin) -> &'static str {
//! "authenticated"
//! }
//!
//! let router = GarrisonRouter::new(std::sync::Arc::new(GarrisonConfig::default_config()))
//! .route_protected("/api/user", Annotation::CheckLogin);
//!
//! App::new()
//! .route("/api/user", web::get().to(protected_handler))
//! .wrap(router.into_middleware());
//! ```

use crate::annotation::Annotation;
use crate::config::GarrisonConfig;
use crate::context::tenant::TenantResolver;
use crate::router::GarrisonInterceptor;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;

pub mod error;
pub mod extractor;
pub mod middleware;
pub mod request_id;
pub mod router;

/// 登录主体 extractor(从 Authorization: Bearer `<token>` 解析 login_id)。
pub use extractor::GarrisonPrincipal;
/// X-Request-ID 中间件(Transform):提取 / 生成 / 回传请求标识。
pub use request_id::{RequestIdMiddleware, RequestIdService};

// 路由规则 + 路由器 struct 声明(impl 见 router.rs)

/// 路由规则:路径 → 注解映射。
#[derive(Clone)]
pub struct RouteRule {
    /// 路由路径
    pub path: String,
    /// 关联注解
    pub annotation: Annotation,
}

/// actix-web 路由器,收集鉴权路由规则并生成 middleware。
///
/// 对应 axum 版 `GarrisonRouter`,API 对齐。
pub struct GarrisonRouter {
    rules: HashMap<String, Annotation>,
    interceptor: Arc<dyn GarrisonInterceptor>,
    config: Arc<GarrisonConfig>,
    /// 租户解析器(None = 不启用租户提取)。
    tenant_resolver: Option<Arc<dyn TenantResolver>>,
    /// 鉴权通过后内层 handler 的可选超时(None = 不设超时,默认;
    /// 经 `with_handler_timeout` 配置,防挂起 handler 无限占用连接)。
    handler_timeout: Option<std::time::Duration>,
}

// GarrisonMiddleware struct 声明(impl Transform/Service 见 middleware.rs)

/// actix-web middleware:提取 token + 解析租户 + 调用 interceptor + 设置 task_local。
///
/// 配置 [`TenantResolver`]([`GarrisonRouter::with_tenant_resolver`])时先解析 `TenantContext` 并进入
/// `TENANT.scope`,使 tenant-isolation 下的 `check_permission`/`check_role` 拿到租户上下文(避免 fail-closed 拒绝)。
pub struct GarrisonMiddleware {
    rules: Arc<HashMap<String, Annotation>>,
    interceptor: Arc<dyn GarrisonInterceptor>,
    config: Arc<GarrisonConfig>,
    tenant_resolver: Option<Arc<dyn TenantResolver>>,
    /// 内层 handler 可选超时(None = 不设超时,默认)。
    pub(crate) handler_timeout: Option<std::time::Duration>,
}

/// middleware service(Transform 生成的中间层)。
pub struct GarrisonMiddlewareService<S> {
    /// 内部 service(Rc 包装以便在 async block 中 clone,无需 S: Clone)
    pub inner: Rc<S>,
    /// 路由规则
    pub rules: Arc<HashMap<String, Annotation>>,
    /// 拦截器
    pub interceptor: Arc<dyn GarrisonInterceptor>,
    /// 配置
    pub config: Arc<GarrisonConfig>,
    /// 租户解析器(None = 不启用租户提取)。
    pub tenant_resolver: Option<Arc<dyn TenantResolver>>,
    /// 内层 handler 可选超时(None = 不设超时,默认)。
    pub handler_timeout: Option<std::time::Duration>,
}

// FromRequest Extractor struct 声明(impl FromRequest 见 extractor.rs)

/// CheckLogin extractor:验证用户已登录。
///
/// 在 handler 参数中使用:
/// ```ignore
/// async fn handler(_auth: CheckLogin) -> &'static str { "ok" }
/// ```
pub struct CheckLogin;

/// CheckRole extractor:验证用户持有指定角色。
///
/// 角色名通过 `web::Data<RequiredRole>` 服务端配置。
pub struct CheckRole(pub String);

/// CheckPermission extractor:验证用户持有指定权限。
///
/// 权限名通过 `web::Data<RequiredPermission>` 服务端配置。
pub struct CheckPermission(pub String);

/// CheckRole 服务端配置:路由注册时声明所需角色。
///
/// 通过 `web::Data::new(RequiredRole("admin".into()))` 注入,角色名禁止客户端控制。
///
/// # 使用
///
/// ```ignore
/// use garrison::web_actix::RequiredRole;
/// App::new()
/// .app_data(web::Data::new(RequiredRole("admin".to_string())))
/// .route("/admin", web::get().to(admin_handler))
/// ```
pub struct RequiredRole(pub String);

/// CheckPermission 服务端配置:路由注册时声明所需权限。
///
/// 通过 `web::Data::new(RequiredPermission("user:read".into()))` 注入,权限名禁止客户端控制。
///
/// # 使用
///
/// ```ignore
/// use garrison::web_actix::RequiredPermission;
/// App::new()
/// .app_data(web::Data::new(RequiredPermission("user:read".to_string())))
/// .route("/data", web::get().to(data_handler))
/// ```
pub struct RequiredPermission(pub String);

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;