garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
Documentation

Rust 2021 Rustc 1.97.1+ crates.io docs.rs downloads CI coverage license

中文 | English

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

✨ 功能特性 • 🚀 快速开始 • 📚 文档 • 💻 示例 • 🤝 参与贡献


🎯 注解声明保护点,静态 API 零状态调用

启动时向 GarrisonManager 注入一次依赖,此后从登录到登出交给框架接管:


📋 目录


✨ 功能特性

除上述核心能力外,其余能力(认证协议、防火墙、账号安全、多租户、可观测性、微服务组件等)也均以独立特性标志提供、按需编译;按能力域汇总的功能矩阵见 🎨 特性标志 一节(完整清单以 Cargo.toml 的 [features] 为准)。


🚀 快速开始

📦 安装

在 Cargo.toml 中添加依赖(development 聚合 = 内存缓存 DAO + SQLite + axum 适配):

[dependencies]
garrison = { version = "0.9", features = ["development"] }
async-trait = "0.1"
tokio = { version = "1", features = ["full"] }

要求 Rust 1.97.1 及以上(Cargo.toml 的 rust-version = "1.97.1"):依赖面中的兄弟生态 crate(confers / oxcache / dbnexus / sdforge / limiteron / inklog / trait-kit 的 rc 线)各自声明 rust-version = "1.97.1",这是依赖图可满足的最低工具链,低于该版本 cargo check 直接拒绝构建(rustc ... is not supported by the following packages);CI 测试矩阵按 1.97.1(MSRV 下限)/ stable / beta 三档显式验证。

预发布版本需显式写完整版本号,"0.9" 无法匹配 prerelease。如需启用全部协议层与安全模块:features = ["full"]。

预设 安装方式 适用场景
开发 features = ["development"] 内存缓存 + SQLite + axum,快速验证
生产 features = ["production"] 生产环境推荐组合
完整 features = ["full"] 全部能力

💡 最小示例

以下示例改编自 examples/src/bin/readme_quickstart.rs(完整业务场景:初始化管理器 → 执行登录 → 校验登录状态 → 登出):

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

// 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()])
    }
}

#[tokio::main]
async fn main() -> GarrisonResult<()> {
    // 2. 准备依赖
    let dao: Arc<dyn GarrisonDao> = Arc::new(GarrisonDaoOxcache::new().await?);
    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?;

    // 4. 在 task_local 上下文中执行登录
    let token = garrison::stp::with_current_token(
        String::new(), GarrisonUtil::login("1001", &LoginParams::default()),
    ).await?;
    println!("登录成功,token = {}", &token[..8.min(token.len())]);

    // 5. 校验登录状态
    garrison::stp::with_current_token(token.clone(), GarrisonUtil::check_login()).await?;

    // 6. 校验权限
    garrison::stp::with_current_token(
        token.clone(), GarrisonUtil::check_permission("user:read"),
    ).await?;

    // 7. 登出
    garrison::stp::with_current_token(token.clone(), GarrisonUtil::logout()).await?;
    Ok(())
}
cargo run -p garrison-examples --bin readme_quickstart --features "cache-memory"
# 输出: 登录成功,token = <8 位随机 token 前缀>

本示例已由 examples/tests/readme_quickstart.rs 持续验证(随 CI 运行),业务代码与 examples/src/web/readme_quickstart.rs 逐字对应。

🧭 核心概念

  • 全局单例 + 静态 API:GarrisonManager 启动时一次性注入 dao / config / interface,业务代码经 GarrisonUtil 静态 API 零状态调用。
  • token 上下文:token 经 task_local 上下文(garrison::stp::with_current_token)携带,Web 中间件自动绑定,静态 API 自动读取当前 token。
  • 双模会话:Account-Session(账号级)与 Token-Session(登录级)双会话由 is_share / is_concurrent 控制多端策略。
  • 特性门控:全部可选能力均为独立 feature,编译产物只包含启用的部分。

token 上下文、双抽象层存储等概念详解见 📖 用户指南 · 核心概念。


🎨 特性标志

📋 功能矩阵

下表按能力域汇总 Cargo.toml 的 [features] 主要特性(100+ 个 flag,完整清单以 Cargo.toml 的 [features] 为准),default = ["backend-embedded"]。

v0.9.0 Feature 改名映射:

旧名称 (≤0.8.x) 新名称 (≥0.9.0) 说明
secure-saml protocol-saml SAML 2.0 签名验证
secure-httpbasic protocol-httpbasic HTTP Basic 认证
secure-httpdigest protocol-httpdigest HTTP Digest 认证
observability-otlp otlp OpenTelemetry OTLP
decision-trace / permission-registry / safe-defaults core-advanced 核心增强合并
dynamic-active-timeout / login-token-map-persistence / anonymous-session / session-search session-extra 会话增强合并

📚 文档

文档 说明
📖 用户指南 从安装到进阶的完整使用教程
📘 API 参考 公开 API 与模块参考
🏗️ 架构文档 设计原则、模块划分与数据流
⚙️ 配置指南 三级配置源、完整配置项与热更新
⚡ 性能指南 性能目标、基准测试与优化建议
🧱 API 稳定性分级 v1.0 稳定性层级、冻结清单与公共面基线
🏭 参考生产案例 自托管参考部署案例与提交模板
🔎 安全审计就绪包 审计范围、证据矩阵与第三方 RFP 清单
🧪 测试场景矩阵 验收场景穷举、特性组合矩阵与质量门禁
🔒 安全文档 安全策略、漏洞报告流程
🛡️ 威胁模型 STRIDE 分析、框架防御与业务方责任边界
❓ FAQ 常见问题解答
🔧 问题排查 常见问题与解决方案
🛠️ 开发规范 TDD 工作流、代码规范与调试技巧
🚀 部署指南 生产部署注意事项
🗺️ 路线图 版本演进规划
📦 发布工作流 版本发布流程与门禁
🤝 贡献指南 如何参与项目开发
📋 更新日志 每个版本的变更记录
📦 在线 API 文档 docs.rs 自动生成的最新文档
📦 crates.io 发布页面

💻 示例

全部 65 个可运行示例位于 examples/ 目录(独立 workspace member,garrison-examples crate),每个示例配套 1:1 独立测试,按「登录 / 会话 / Token 基础、注解与 Web 集成、认证协议、安全防护、可观测性与基础设施」等主题分组,完整清单与各示例所需 feature 见 examples/README.md。

# 运行单个示例
cargo run -p garrison-examples --bin basic_login --features full

# 验证全部示例可编译
cargo build -p garrison-examples --features full

🏗️ 架构

Garrison 采用双抽象层 + 全局单例架构:GarrisonDao trait 统一屏蔽 dbnexus(SQLite / PostgreSQL / MySQL)+ oxcache(L1 内存 / L2 redis)存储后端差异,核心模块 always on、可选能力(protocol-*、secure-*、firewall-*、account-*、web-* 等)按 feature 独立门控,核心数据通路为「业务代码 → GarrisonUtil → GarrisonManager 单例 → GarrisonLogicDefault → GarrisonDao / GarrisonPermissionStrategy → 存储后端」。

模块分层、trait 关系与请求处理数据流的完整说明见 🏗️ 架构文档。


🧪 测试

🎯 测试策略

测试按「单元(src/ 内联 #[cfg(test)])→ 验收 / 集成(tests/acceptance/ 按域组织 + db 专用 target + trybuild UI 测试)→ 示例级集成(examples/tests/ 与示例 bin 一一对应)」三层组织,另有 Criterion 基准、文档测试与特性组合编译矩阵(ci.yml test-compile-guard + 每周 feature-matrix.yml)。场景穷举、真实服务矩阵(Redis / PostgreSQL / MySQL / Keycloak 26 / HIBP)与特性依赖分析见 🧪 测试场景矩阵。

▶️ 运行命令(与 CI 一致)

# 单元测试(CI test job 的两种特性面)
cargo test --no-default-features --features "default" --lib --locked
cargo test --features "full" --lib --locked

# 验收 / 集成测试(CI integration-test job;services 含 Redis 与 PostgreSQL)
cargo test --features "full" --tests --no-fail-fast

# 验收矩阵(full + testing 特性面)
cargo test --test acceptance --features "full testing"

# 性能基线(concurrency 域 #[ignore] 的 perf_* 用例)
cargo test --test acceptance --features "full testing" perf_ -- \
    --nocapture --test-threads=1 --ignored

# 文档测试(CI Linux/MSRV 腿)
cargo test --features "full" --doc --locked

# 一键 E2E(auth_server_serve 冒烟 + 全量验收 + 性能基线 + 报告聚合)
bash scripts/e2e_run.sh
# 本地全量流水线(compose 真服务自举 + 静态门禁 + 全部测试 + 特性矩阵 + 基准)
bash scripts/e2e_matrix.sh

# Lint 与格式门禁
cargo clippy --no-default-features --features "default" -- -D warnings
cargo clippy --features "full" -- -D warnings
cargo fmt --all -- --check

# 覆盖率门禁:行覆盖率不低于 95%
cargo llvm-cov --features "full" --fail-under-lines 95

# 依赖安全门禁
cargo deny --all-features --locked check

# 基准测试(--bench 限定 criterion 目标,避免连带 lib unittest)
cargo bench --bench garrison_benchmark --features full --locked -- --quick

构建依赖:protoc(sdforge build script 需要,CI 经 taiki-e/install-action 安装)。

📊 测试规模

约 5994 个测试(lib 单元 5454 + 验收 / 集成 416 + 示例级 116 + 过程宏 8;lib 与验收数为 cargo test --list 实测,示例与过程宏为属性静态计数,截至 2026-10-28)与 6 个 Criterion 基准场景;覆盖率门禁为行覆盖率不低于 95%(2026-10-14 实测约 95.15%)。统计口径与明细见 🧪 测试场景矩阵 · 测试规模统计。


📊 性能

基准场景与目标定义于 benches/garrison_benchmark.rs(login_flow / token_verify_stateless / permission_check / oxcache_backend_switch / convert_placeholders / circuit_execute_closed_passthrough 六个 Criterion 场景),以 cargo bench 在本机复现;验收层另有 HTTP 性能基线(P99 < 200ms / 1000 RPS),经 scripts/e2e_run.sh 采集并聚合报告。性能设计要点(单例无锁化、慢哈希 spawn_blocking 下沉、请求内快照复用、缓存 TTL 抖动、全量 feature 门控)与逐项优化建议见 ⚡ 性能指南。


🔒 安全

🛡️ 安全设计

Garrison 围绕身份认证全生命周期做纵深防护:Argon2id / Bcrypt 慢哈希经 spawn_blocking 下沉、Token 常量时间比较(secure-ct-eq,CWE-208)、API Key 哈希存储与 IP 级限速(CWE-916 / CWE-307)、多租户 IDOR 防护、审计事件 token 统一掩码(CWE-532)、外网登录端点 fail-closed 等。逐项机制的代码级细节见 🏗️ 架构文档 与 📖 用户指南 · 安全与防护,安全配置最佳实践与漏洞处理流程见 🔒 安全文档。

⛓️ 供应链与门禁

CI 与发布流程内置两道供应链门禁:cargo deny check(RustSec 公告 / 许可证 / 禁用依赖 / 来源校验,ci.yml 与 release.yml 均执行)与 gitleaks 私钥扫描(pre-commit 覆盖 staged,CI 全量 git history)。cargo audit 不在 CI 中——cargo-deny 已覆盖同等漏洞检查,避免维护两份忽略列表;它仅作为本地发布 precheck 由 scripts/release.sh 执行。门禁标准与处置细节见 🔒 安全文档 · 供应链与门禁。

🚨 报告安全漏洞

请勿通过公开 issue 报告安全漏洞。请优先使用 GitHub Security Advisories 私密披露通道提交报告(不可用时再发送邮件至 Kirky-X@outlook.com,受理人 Kirky.X)。项目承诺 48 小时内确认、7 天内给出初步评估。完整政策见 SECURITY.md。


🗺️ 开发路线图

完整规划见 docs/ROADMAP.md。


🤝 参与贡献

详细的贡献流程与代码规范请参阅 🤝 贡献指南。

🛠️ 开发环境

工具链为 Rust 1.97.1+(兄弟生态依赖 rc 线要求 ≥ 1.97.1;CI 按 1.97.1 / stable / beta 三档矩阵显式验证);提交前运行 cargo fmt --all -- --check 与 cargo clippy --features full --lib --tests -- -D warnings(不可用 --all-features:它同时启用 db-sqlite 与 db-postgres,而 dbnexus 禁止 embedded×server-side 驱动共存,必然 compile_error);提交信息遵循 Conventional Commits(feat、fix、docs 等)。完整环境搭建步骤见 🤝 贡献指南 · 开发环境搭建。

💖 贡献方式

🐛 报告 Bug

发现问题? 创建 Issue

💡 功能建议

有好想法? 提交功能建议

🔧 提交 PR

想贡献代码? Fork 并提交 PR


📋 更新日志

完整版本历史见 📋 更新日志(遵循 Keep a Changelog 格式,语义化版本)。

版本 日期 要点
0.9.0 2026-11-14 正式版定版:自研依赖面转稳定线(confers 0.6 / trait-kit 0.5 / oxcache 0.5 / dbnexus 0.6 / inklog 0.3 / sdforge 0.5 / limiteron 0.3)、i18n 归一 trait-kit 供给、单根 garrison 二进制、CI 供应链告警清零
0.9.0-rc.3 2026-10-14 安全审计整改 R01–R18:统一错误模型(request-id / Retry-After)/ 字段静态加密 / WebAuthn / 密码找回 / MFA 编排 / back-channel logout / 多租户强化 / garrison-cli
0.9.0-rc.2 2026-08-26 fail-closed 安全加固(check_api_key / check_abac)
0.9.0-rc.1 2026-08-25 验收测试体系 + DAO 原子契约收严 + gRPC async 鉴权层
0.8.1 2026-07-24 审计日志 token 泄漏修复(CWE-532)

📄 许可证

本项目基于 Apache-2.0 许可证开源。为何选择 Apache-2.0 而非 MIT:Apache-2.0 包含专利授权条款,更适合企业级框架使用。


🙏 致谢

🌟 核心依赖

Garrison 站在以下优秀开源项目的肩膀上:

依赖 用途
axum tokio 团队出品的 Rust Web 框架
oxcache Rust 多级缓存库(L1 内存 + L2 redis)
dbnexus Rust 数据库抽象层(SQLite / PostgreSQL / MySQL)
inventory David Tolnay 的编译期插件注册库
confers Rust 配置管理库(零样板代码)
sdforge 声明式 Web 框架
trait-kit trait 工具集

💝 特别感谢


📞 联系与支持


⭐ Star 历史

Star History Chart

如果这个项目对您有帮助,请考虑给它一个 ⭐️!

由 Kirky.X 构建


© 2026 Kirky.X. 保留所有权利。