Skip to main content

Crate garrison

Crate garrison 

Source
Expand description

§Garrison

Garrison 是一个面向 Rust 生态的一站式身份认证鉴权框架。

§快速开始

最小可用示例:初始化管理器 → 登录 → 校验登录状态 → 校验权限 → 登出。 以下 doctest 随 cargo test --doc 持续验证,可直接复制使用;InMemoryDao 为进程内实现, 生产请换 GarrisonDaoOxcache / GarrisonDaoDbnexus 等持久化后端。

use async_trait::async_trait;
use garrison::prelude::*;
use std::sync::Arc;

// 1. 业务方实现 GarrisonInterface(提供权限/角色数据)
struct MyInterface;

#[async_trait]
impl GarrisonInterface for MyInterface {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec!["user:read".into(), "user:write".into()])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec!["user".into()])
}
}


use garrison::context::tenant::{TenantContext, TenantSource, TENANT};

// 2. 准备依赖(dao / config / interface)
let dao: Arc<dyn GarrisonDao> = Arc::new(garrison::dao::InMemoryDao::new());
let config = Arc::new(GarrisonConfig::default_config());
let interface: Arc<dyn GarrisonInterface> = Arc::new(MyInterface);

// 3. 初始化全局管理器
GarrisonManager::builder()
.dao(dao)
.config(config)
.interface(interface)
.build()
.await?;

// 租户上下文:tenant-isolation feature 启用时必需;单租户部署用 tenant_id=0
let tenant = TenantContext {
tenant_id: 0,
resolved_from: TenantSource::Header,
};

TENANT.scope(tenant, async {
// 4. 执行登录:生成 token 并写入会话
// 注意:login / check_login 依赖 task_local 上下文中的当前 token,
// 通常由 web 中间件(如 axum middleware)设置。
let token = with_current_token(
String::new(),
GarrisonUtil::login("1001", &LoginParams::default()),
)
.await?;

// 5. 校验登录状态
with_current_token(token.clone(), async {
assert!(GarrisonUtil::check_login().await?);

// 6. 读取当前登录主体 / 校验权限
let login_id = GarrisonUtil::get_login_id().await?;
assert_eq!(login_id.as_deref(), Some("1001"));
GarrisonUtil::check_permission("user:read").await?;

// 7. 登出
GarrisonUtil::logout().await?;
Ok::<(), GarrisonError>(())
})
.await?;

§特性

Garrison 通过 Cargo feature flags 控制各能力域的编译:

类别Feature说明
默认defaultbackend-embedded(仅启用进程内认证后端;development 可一键启用常用组合)
缓存cache-memory / cache-redis基于 oxcache 的 L1(内存) + L2(redis),均启用 oxcache(语义别名)
数据库db-sqlite基于 dbnexus + auto-migrate
Web 框架web-axum / web-actix / web-warp路由拦截器与 extractor 适配
协议层protocol-jwt / protocol-oauth2 / protocol-sso / protocol-sign / protocol-apikey / protocol-temp / protocol-qrlogin鉴权协议插件
安全模块secure-totp / secure-sign / protocol-httpbasic / protocol-httpdigestTOTP / 签名 / Basic / Digest
可观测性listener / tracing-log / metrics-prometheus事件监听 / 日志 / 指标
聚合full / production / development一键启用一组特性

§模块概览

  • 核心扩展(always on):core::token(Token trait + TokenStyleFactory)、core::auth(AuthLogic + DefaultAuthLogic)、core::permission(PermissionChecker + 默认实现)、plugin(编译期插件注册)、strategy(权限策略扩展)、session(SSO / OAuth2 / 临时凭证关联)
  • 协议层(特性门控):jwt(HS256/HS512)/ oauth2(Authorization Code / Client Credentials / Password)/ sso(一次性 60s ticket)/ sign(HMAC-SHA256 + 防重放窗口)/ apikey / temp
  • 安全模块(特性门控):totp(RFC 6238,±1 窗口)/ sign / httpbasic / httpdigest
  • 可观测性:listener(GarrisonEvent + Listener,Login / Logout / PermissionCheck / Kickout 事件)

§特性域

100+ feature flag 分域:登录认证 / 权限认证(RBAC + ABAC)/ Session / 协议层(OAuth2 / SSO / JWT / Sign / API Key / Temp / OIDC / SAML)/ 安全模块(TOTP / 签名 / Basic / Digest / Unicode 检测 / 脱敏 / XSS / 常量时间比较)/ 账号安全引擎 / Web 适配 / 安全防护套件 / 可观测性 / 服务器层 / 社交与扫码登录 / 插件化扩展。

§架构

双抽象层 + 全局单例:dbnexus(GarrisonDao 屏蔽 SQLite / PostgreSQL / MySQL 差异)与 oxcache (L1 内存 + L2 redis,承载 Token-Session 与 Account-Session);GarrisonManager 持全局 Arc<GarrisonLogicDefault>(arc_swap::ArcSwapOption,读路径无锁、支持覆盖式重建),启动时经 GarrisonManager::builder 链式注入 dao / config / interface,GarrisonLogicFactory 经 inventory 编译期注册、运行时选取,GarrisonUtil 静态方法委托全局单例。

§使用示例

[dependencies]
garrison = { version = "0.9", features = ["web-axum", "protocol-jwt"] }
use garrison::prelude::*;

// 通过 prelude 引入核心类型(LoginParams / GarrisonDaoOxcache /
// Annotation / with_current_token / current_token 均已入 prelude)
let _config: GarrisonConfig = GarrisonConfig::default_config();

Re-exports§

pub use context::tenant::HeaderTenantResolver;
pub use context::tenant::SubdomainTenantResolver;
pub use context::tenant::TenantContext;
pub use context::tenant::TenantResolver;
pub use context::tenant::TenantSource;
pub use context::tenant::TENANT;
pub use context::GarrisonPrincipal;
pub use state::TokenState;
pub use state::UserStatus;
pub use dao::repository::role_hierarchy::RoleHierarchyRecord;
pub use protocol::social::SocialLoginProvider;
pub use protocol::social::SocialUserInfo;
pub use protocol::social::provider_names;
pub use protocol::social::registry::SocialLoginService;
pub use prelude::*;

Modules§

abac
ABAC 策略引擎模块(abac feature,依赖 cedar-policy):AbacEngine 基于 Cedar 策略语言。
account
账号安全引擎模块:凭证模型 SPI / 密码策略套件 / 用户级双态锁定 / AuthenticationFlow DSL (分别经 account-credential / account-policy / account-lockout / account-authflow 门控); 与 secure/(密码学原语)互补,提供账号生命周期安全能力。 账号安全引擎模块(吸收 Keycloak 安全能力):与 secure/(密码学原语:TOTP/签名/Basic/Digest) 互补,提供账号生命周期安全能力。
annotation
注解模块,定义鉴权注解枚举。 注解模块,定义鉴权注解枚举(用于 router 中间件配置) 与 axum extractor(CheckLogin 等,用于 handler 参数提取)。
backendbackend-embedded or backend-remote
认证后端抽象模块(backend-embedded / backend-remote 任一):AuthBackend trait + BackendEmbedded(进程内认证,委托 GarrisonManager)或 BackendRemote(HTTP 客户端连远程 Auth Server)。 AuthBackend — 认证后端统一抽象。
cli
单根二进制的 CLI 面(sdforge CliBuilder + inventory 注册 + dispatch): healthcheck(无条件)/ serve(auth-server)/ 运维命令组(cli-ops)。 garrison 单根二进制的 CLI 面(sdforge CliBuilder + inventory 注册 + dispatch)。
config
配置模块,提供 GarrisonConfig 全局配置。 配置模块,提供 GarrisonConfig 全局配置。
constants
常量定义模块,提供 DAO key 前缀等类型安全枚举。 常量模块,提供框架共享的枚举与常量定义。
context
上下文模块,提供请求/响应/存储上下文抽象。 上下文模块,提供请求 / 响应 / 存储上下文抽象。
core
核心模块,包含认证、权限、Token 的核心抽象。 核心模块(stp 的子模块),提供认证、权限、Token 的基础抽象。
dao
DAO 模块,定义持久化数据访问抽象层。 DAO 模块:经 oxcache / dbnexus 提供多后端(缓存 / 关系型数据库)持久化抽象。
error
错误类型定义模块。 错误类型定义模块:定义框架统一错误类型与 GarrisonResult 别名。
exception
异常模块,定义框架异常类型。 异常模块,提供细化异常类型与统一错误枚举。
health
健康检查模块,提供 liveness/readiness 探针与依赖项健康检测。 健康检查模块,提供 liveness/readiness 探针与依赖项健康检测。
i18n
国际化模块(fluent-rs):异常消息中英文切换,默认 Zh,经 set_locale(GarrisonLocale::En) 切至英文。 国际化模块,提供异常消息多语言切换(中英文)。
json
JSON 模块,提供 JSON 模板与序列化抽象。 JSON 模块,隔离具体 JSON 库(serde_json / simd-json 等)。
limiteron
limiteron 适配器模块,将 GarrisonDao 桥接到 limiteron Storage/BanStorage/DistributedLimiter trait。
manager
管理器模块,提供全局管理器单例。 管理器模块,提供全局管理器单例与编译期工厂注册。
plugin
插件模块,定义插件 trait 与编译期注册。 插件模块,定义插件 trait 与编译期注册(inventory 实现:submit! 注册、iter! 收集,替代 Java SPI)。 生命周期钩子 on_login/on_logout/on_permission_check;插件失败仅记录 tracing::warn!,不中断主流程。
prelude
预导出模块,包含最常用的类型与 trait。 预导出模块,包含最常用的类型与 trait。
protocol
协议层模块,包含各协议插件子模块;重依赖子模块(oauth2/sso/jwt/sign/apikey/temp)在 protocol/mod.rs 内自行按 feature 门控,protocol::social(扩展点契约类型)无 feature 依赖,始终编译。 协议层模块:OAuth2、SSO、JWT、签名、API Key、临时凭证、邀请码、扫码登录、WebAuthn、社交登录等协议插件,各子模块按 feature 门控编译。
router
路由模块,提供路由器与拦截器抽象。 路由模块:GarrisonInterceptor 预处理 hook(按 annotation 调用 GarrisonUtil), DefaultGarrisonInterceptor 默认实现,GarrisonRouter 包装 axum::Router(cfg web-axum), GarrisonLayer middleware 自动从 header/cookie 提取 token 并设置 task_local。
session
会话模块,提供 GarrisonSession 会话模型。 会话模块,提供双模会话管理(Account-Session + Token-Session)。
state
状态机模块,提供 state::TokenState(5 状态 + 6 条合法转换)与 state::UserStatus (5 状态 + 9 条合法转换);独立于 Session / User 模块,不集成。 状态机模块,定义 TokenState 与 UserStatus 显式状态机;转换路径以本模块定义为准,不混合其他文档。
stp
Stp 模块,提供 GarrisonLogicDefault / GarrisonInterface / GarrisonUtil + 5 个子 trait。 Stp 模块,提供核心认证逻辑与工具入口。
strategy
策略模块,提供鉴权策略与防火墙策略。 策略模块,提供鉴权策略与可插拔权限策略。

Macros§

loc
构造本地化错误文案:按 key 查 FTL 翻译,缺 key 或格式化失败回退 $fallback,$fallback 为空串时返回 key 本身(既有调用点传 "" 时输出与旧行为一致)。