garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

#![doc(html_root_url = "https://docs.rs/garrison/latest")]
#![allow(rustdoc::invalid_rust_codeblocks)]

//! # Garrison
//!
//! Garrison 是一个面向 Rust 生态的一站式身份认证鉴权框架。
//!
//! ## 快速开始
//!
//! 最小可用示例:初始化管理器 → 登录 → 校验登录状态 → 校验权限 → 登出。
//! 以下 doctest 随 `cargo test --doc` 持续验证,可直接复制使用;`InMemoryDao` 为进程内实现,
//! 生产请换 `GarrisonDaoOxcache` / `GarrisonDaoDbnexus` 等持久化后端。
//!
//! ```rust
//! 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()])
//! }
//! }
//!
//! # fn main() -> GarrisonResult<()> {
//! # tokio::runtime::Builder::new_current_thread()
//! # .enable_all()
//! # .build()
//! # .expect("runtime 初始化恒成功")
//! # .block_on(run())?;
//! # Ok(())
//! # }
//!
//! # async fn run() -> GarrisonResult<()> {
//! 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?;
//! # Ok::<(), GarrisonError>(())
//! # })
//! # .await
//! # }
//! ```
//!
//! ## 特性
//!
//! Garrison 通过 Cargo feature flags 控制各能力域的编译:
//!
//! | 类别 | Feature | 说明 |
//! |:---|:---|:---|
//! | 默认 | `default` | `backend-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-httpdigest` | TOTP / 签名 / 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`] 静态方法委托全局单例。
//!
//! ## 使用示例
//!
//! ```toml
//! [dependencies]
//! garrison = { version = "0.9", features = ["web-axum", "protocol-jwt"] }
//! ```
//!
//! ```rust
//! use garrison::prelude::*;
//!
//! // 通过 prelude 引入核心类型(LoginParams / GarrisonDaoOxcache /
//! // Annotation / with_current_token / current_token 均已入 prelude)
//! let _config: GarrisonConfig = GarrisonConfig::default_config();
//! ```

#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_docs)]

// 核心模块(always on,无 feature flag)

/// 常量定义模块,提供 DAO key 前缀等类型安全枚举。
pub mod constants;

/// 核心模块,包含认证、权限、Token 的核心抽象。
pub mod core;

/// Stp 模块,提供 GarrisonLogicDefault / GarrisonInterface / GarrisonUtil + 5 个子 trait。
pub mod stp;

/// 注解模块,定义鉴权注解枚举。
pub mod annotation;

/// 路由模块,提供路由器与拦截器抽象。
pub mod router;

/// DAO 模块,定义持久化数据访问抽象层。
pub mod dao;

/// limiteron 适配器模块,将 GarrisonDao 桥接到 limiteron Storage/BanStorage/DistributedLimiter trait。
///
/// 无条件编译:`GarrisonDaoDistributedLimiter` 是防爆破计数公共基座(invitation 锁定器在任意 feature
/// 面下均委托它),`limiteron` 为非 optional 依赖;子模块各自门控(ban → `firewall-ddos`,
/// circuit/fallback → `backend-remote`)。`firewall` / `oauth2-server` 传递启用 `dep:limiteron`,
/// 防火墙与密码限流统一走 limiteron(禁止手写限流实现)。
pub mod limiteron;

/// 策略模块,提供鉴权策略与防火墙策略。
pub mod strategy;

/// 会话模块,提供 GarrisonSession 会话模型。
pub mod session;

/// 数据合规模块(GDPR / 个保法数据主体权利编排);启用 `data-erasure` 时编译,提供按主体
/// (login_id / IP)擦除框架管辖内数据的 [`compliance::erasure::DataErasureService`] 与擦除报告,
/// 数据清单与责任边界见 `docs/DATA_COMPLIANCE.md`。
#[cfg(feature = "data-erasure")]
pub mod compliance;

/// 缓存模块,提供三层缓存架构(L1 oxcache 内存 + L2 DAO + L3 interface);启用 `three-tier-cache`
/// 时编译,提供 [`UserCacheService`] 加速权限 / 角色 / 用户信息查询。
///
/// [`UserCacheService`]: crate::cache::three_tier::UserCacheService
#[cfg(feature = "three-tier-cache")]
pub mod cache;

/// 状态机模块,提供 [`state::TokenState`](5 状态 + 6 条合法转换)与 [`state::UserStatus`]
/// (5 状态 + 9 条合法转换);独立于 Session / User 模块,不集成。
pub mod state;

/// 配置模块,提供 GarrisonConfig 全局配置。
pub mod config;

/// 健康检查模块,提供 liveness/readiness 探针与依赖项健康检测。
pub mod health;

/// 单根二进制的 CLI 面(sdforge CliBuilder + inventory 注册 + dispatch):
/// `healthcheck`(无条件)/ `serve`(auth-server)/ 运维命令组(cli-ops)。
pub mod cli;

/// 上下文模块,提供请求/响应/存储上下文抽象。
pub mod context;

/// JSON 模块,提供 JSON 模板与序列化抽象。
pub mod json;

/// 异常模块,定义框架异常类型。
pub mod exception;

/// 管理器模块,提供全局管理器单例。
pub mod manager;

/// 插件模块,定义插件 trait 与编译期注册。
pub mod plugin;

/// 可观测性模块,提供 Prometheus 指标 / 结构化 JSON 日志 / OpenTelemetry 分布式追踪;对应 feature
/// (`metrics-prometheus` / `otlp` / `tracing-log`)未启用时模块仍可导入但 API 为 no-op。
#[cfg(any(
    feature = "metrics-prometheus",
    feature = "otlp",
    feature = "tracing-log"
))]
pub mod observability;

/// gRPC 鉴权拦截器模块(`grpc` feature):`tonic::Interceptor` 实现,从 gRPC 请求 metadata
/// 提取 Authorization Bearer token 并执行鉴权。
#[cfg(feature = "grpc")]
pub mod grpc;

/// 国际化模块(fluent-rs):异常消息中英文切换,默认 `Zh`,经 `set_locale(GarrisonLocale::En)`
/// 切至英文。
pub mod i18n;

/// 声明式 JSON 测试套件模块(`garrison-testing` feature):提供 [`JsonTestSuite`] / [`JsonTestCase`] /
/// [`TestReport`],从 JSON 文件加载用例并运行 [`Authorizer`] trait(依赖 `authorize-api`)。
///
/// [`JsonTestSuite`]: crate::testing::JsonTestSuite
/// [`JsonTestCase`]: crate::testing::JsonTestCase
/// [`TestReport`]: crate::testing::TestReport
/// [`Authorizer`]: crate::core::permission::Authorizer
/// [`AuthRequest`]: crate::core::permission::AuthRequest
/// [`Decision`]: crate::core::permission::Decision
#[cfg(feature = "garrison-testing")]
pub mod testing;

/// actix-web 框架适配模块(`web-actix` feature):GarrisonRouter + FromRequest extractor +
/// GarrisonMiddleware 完整集成,与 axum 适配对齐。
#[cfg(feature = "web-actix")]
pub mod web_actix;

/// warp 框架适配模块(`web-warp` feature):GarrisonRouter + Filter extractor + GarrisonRejection
/// 完整集成,与 axum/actix-web 适配对齐。
#[cfg(feature = "web-warp")]
pub mod web_warp;

/// Web 安全中间件模块,提供 WAF / CORS / CSRF / 安全响应头等能力;子模块独立 feature-gated:
/// `web-cors`(CORS)/ `web-csrf`(CSRF)/ `web-security-headers`(HTTP 安全响应头)/ `web-axum`(X-Request-ID)。
#[cfg(any(
    feature = "web-axum",
    feature = "firewall-waf",
    feature = "web-cors",
    feature = "web-csrf",
    feature = "web-security-headers",
    feature = "firewall-waf"
))]
pub mod web;

// 可选模块(特性门控)

/// 监听器模块,提供事件监听抽象。
#[cfg(feature = "listener")]
pub mod listener;

/// Credit 计量模块(多租户配额消费统计、告警、周期重置)。
#[cfg(feature = "credit-metering")]
pub mod credit;

/// 安全模块,提供 TOTP / 签名 / Basic / Digest / Unicode 同形异义字检测 / 敏感数据脱敏 验证。
#[cfg(any(
    feature = "secure-totp",
    feature = "secure-sign",
    feature = "protocol-httpbasic",
    feature = "protocol-httpdigest",
    feature = "secure-confusable",
    feature = "secure-masking",
    feature = "secure-xss",
    feature = "secure-sanitize",
    feature = "secure-ct-eq",
    feature = "sms-rate-limit",
    feature = "email-verification",
    feature = "field-encryption",
))]
pub mod secure;

/// 账号安全引擎模块:凭证模型 SPI / 密码策略套件 / 用户级双态锁定 / AuthenticationFlow DSL
/// (分别经 `account-credential` / `account-policy` / `account-lockout` / `account-authflow` 门控);
/// 与 `secure/`(密码学原语)互补,提供账号生命周期安全能力。
pub mod account;

/// 协议层模块,包含各协议插件子模块;重依赖子模块(oauth2/sso/jwt/sign/apikey/temp)在
/// `protocol/mod.rs` 内自行按 feature 门控,`protocol::social`(扩展点契约类型)无 feature 依赖,始终编译。
pub mod protocol;

/// 认证后端抽象模块(`backend-embedded` / `backend-remote` 任一):`AuthBackend` trait +
/// `BackendEmbedded`(进程内认证,委托 GarrisonManager)或 `BackendRemote`(HTTP 客户端连远程 Auth Server)。
#[cfg(any(feature = "backend-embedded", feature = "backend-remote"))]
pub mod backend;

/// ABAC 策略引擎模块(`abac` feature,依赖 `cedar-policy`):`AbacEngine` 基于 Cedar 策略语言。
///
/// feature 关闭时提供 `check_abac_with_policy` fail-closed stub(无 abac attr:no-op allow;
/// 有 abac attr 但 feature 关闭:`Err(Config)`),保证宏 `#[check_permission(permission = "...", abac = "...")]`
/// 生成的代码在任意 feature 组合下均可编译。ABAC 是 RBAC 的增量校验层:RBAC 通过后再检查,不替换 RBAC。
pub mod abac;

/// Auth Server 模块(`auth-server` feature):双端口 axum 服务器,外网端口 login / logout / refresh
/// (面向用户),内网端口 check-* / get-* / kickout 等(服务间调用,需 X-API-Key)。
#[cfg(feature = "auth-server")]
pub mod server;

/// OAuth2 Server 模块(`oauth2-server` feature):授权服务器(AS)实现,4 端点 + 4 种 grant type +
/// PKCE;与 `protocol::oauth2`(OAuth2 客户端 / RP 角色,向外部 AS 请求 token)互补。
#[cfg(feature = "oauth2-server")]
pub mod oauth2_server;

// 公共入口

/// 预导出模块,包含最常用的类型与 trait。
pub mod prelude;

/// 错误类型定义模块。
pub mod error;

pub use prelude::*;

// 多租户隔离类型 re-export

/// 多租户上下文类型与解析器。
pub use context::tenant::{
    HeaderTenantResolver, SubdomainTenantResolver, TenantContext, TenantResolver, TenantSource,
    TENANT,
};

/// JWT claim 租户解析器(需 `protocol-jwt` feature)。
#[cfg(feature = "protocol-jwt")]
pub use context::tenant::ClaimTenantResolver;

/// 登录主体(携带 login_id,由 web 框架 extractor 填充)。
pub use context::GarrisonPrincipal;

// 状态机类型 re-export
// `Mode`(AnnotationMode)位于 annotation 模块而非 state,故此处仅 re-export 两个状态类型。

/// Token 生命周期状态(Issued / Active / Expired / Revoked / Refreshed)。
pub use state::TokenState;

/// 用户账号状态(Pending / Active / Suspended / Inactive / Deleted)。
pub use state::UserStatus;

// 角色层级

/// 角色层级表行结构(child_role → parent_role + tenant_id)。
pub use dao::repository::role_hierarchy::RoleHierarchyRecord;

/// 角色层级服务(TC 预计算 + 缓存 + 增量失效,需任一 db 后端 feature)。
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dao::repository::role_hierarchy::RoleHierarchyService;

// Dbnexus Repository re-export

/// 用户表 Repository(app_user)。
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dao::repository::sqlite::DbnexusUserRepository;

/// 角色表 Repository(app_role)。
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dao::repository::sqlite::DbnexusRoleRepository;

/// 权限表 Repository(app_permission,全局表无 tenant_id)。
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dao::repository::sqlite::DbnexusPermissionRepository;

/// 用户-角色关联表 Repository(app_user_role)。
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dao::repository::sqlite::DbnexusUserRoleRepository;

/// 角色-权限关联表 Repository(app_role_permission)。
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dao::repository::sqlite::DbnexusRolePermissionRepository;

/// 认证方式表 Repository(app_auth_method)。
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dao::repository::sqlite::DbnexusAuthMethodRepository;

/// 会话表 Repository(app_session)。
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dao::repository::sqlite::DbnexusSessionRepository;

/// 登录日志表 Repository(app_login_log)。
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dao::repository::sqlite::DbnexusLoginLogRepository;

/// 用户扩展信息表 Repository(app_user_ext)。
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dao::repository::sqlite::DbnexusUserExtRepository;

// 事件派发事务绑定(OnCommit 语义)
// `DispatchOutcome` 不入根 re-export,经 `garrison::listener::DispatchOutcome` 访问(同 `GarrisonEvent` 策略)。

/// 事件派发事务 guard(OnCommit 语义:数据库事务 commit 成功后才按 FIFO 派发缓冲事件;rollback/丢弃 guard 时事件不派发)。
#[cfg(all(
    feature = "listener",
    any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql")
))]
pub use dao::GarrisonEventTx;

// JWT RefreshToken Rotation

/// RefreshToken 表行结构(hash chain:token_hash + parent_token_hash)。
#[cfg(feature = "protocol-jwt")]
pub use protocol::jwt::refresh::RefreshTokenRecord;

/// Refresh token 重用三级分类(RecentPrev / OrphanedBranch / StaleLineage)。
#[cfg(feature = "protocol-jwt")]
pub use protocol::jwt::refresh::RefreshTokenReuseSubtype;

/// RefreshToken Rotation 服务(rotate + detect_reuse + revoke_chain,需 `protocol-jwt` + `db-sqlite`)。
#[cfg(all(feature = "protocol-jwt", feature = "db-sqlite"))]
pub use protocol::jwt::refresh::RefreshTokenRotation;

// 审计日志

/// 审计日志配置(掩码字段 + 保留天数 + 异步写入开关)。
#[cfg(feature = "audit-log")]
pub use listener::audit::AuditConfig;

/// `audit_logs` 表行结构(tenant_id / event_type / login_id / metadata / success / created_at)。
#[cfg(all(feature = "audit-log", feature = "db-sqlite"))]
pub use listener::audit::AuditEntry;

/// 审计日志查询条件(tenant_id / event_type / from / to,全 Option 复合过滤)。
#[cfg(all(feature = "audit-log", feature = "db-sqlite"))]
pub use listener::audit::AuditQuery;

/// 审计日志监听器(实现 `GarrisonListener`,持久化 `GarrisonEvent` 到 `audit_logs` 表)。
#[cfg(all(feature = "audit-log", feature = "db-sqlite"))]
pub use listener::audit::AuditLogListener;

/// 审计事件防篡改 HMAC 链(吸收自 inklog `ArchiveChain`;随机盐链首,
/// 任一事件篡改/删除/重排/伪造即校验失败)。
#[cfg(feature = "audit-log")]
pub use listener::audit_chain::{AuditChainEntry, AuditEventChain};

// 社交登录

/// 社交登录服务提供方 trait(get_authorization_url / exchange_token / get_user_info)。
pub use protocol::social::SocialLoginProvider;

/// 社交用户信息(provider + provider_user_id + union_id + raw JSON)。
pub use protocol::social::SocialUserInfo;

/// 内置社交登录平台名称常量模块(WECHAT / ALIPAY / WECHAT_MINI_APP);外部 crate 自定义
/// provider 应使用自己的常量(如 `pub const HUAWEI: &str = "huawei"`),避免与内置 provider 冲突。
pub use protocol::social::provider_names;

/// 社交登录注册中心(register / unregister / get / list + 委托调用 + SocialProviderResolver 实现);
/// 允许外部 crate 注册自定义 `SocialLoginProvider` 实现(如华为 Account Kit),扩展点契约类型
/// 无 feature 门控,内置 provider 实现(`WechatProvider` / `AlipayProvider`)仍需对应 feature。
pub use protocol::social::registry::SocialLoginService;

/// 微信扫码登录 provider(需 `social-wechat` feature)。
#[cfg(feature = "social-wechat")]
pub use protocol::social::wechat::WechatProvider;

/// 微信小程序登录 provider(需 `social-wechat` feature)。
#[cfg(feature = "social-wechat")]
pub use protocol::social::wechat::WechatMiniAppProvider;

/// 支付宝授权登录 provider(需 `social-alipay` feature)。
#[cfg(feature = "social-alipay")]
pub use protocol::social::alipay::AlipayProvider;

/// 社交账号绑定服务(find_or_create,需 `db-sqlite`/`db-postgres`/`db-mysql` 任一 +
/// `social-wechat`/`social-alipay` 任一 feature)。
#[cfg(all(
    any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"),
    any(feature = "social-wechat", feature = "social-alipay")
))]
pub use protocol::social::SocialBindingService;

// Keycloak OIDC RP

/// Keycloak OIDC RP 配置(base_url / client_id / client_secret / redirect_uri)。
#[cfg(feature = "keycloak-oidc")]
pub use protocol::oauth2::keycloak::KeycloakConfig;

/// Keycloak OIDC 依赖方(discover / verify_id_token / exchange_code)。
#[cfg(feature = "keycloak-oidc")]
pub use protocol::oauth2::keycloak::KeycloakProvider;

/// Keycloak id_token 的 claims(sub / exp / realm_access / resource_access / tenant_id)。
#[cfg(feature = "keycloak-oidc")]
pub use protocol::oauth2::keycloak::KeycloakClaims;

/// Keycloak token endpoint 响应(access_token / refresh_token / id_token / expires_in)。
#[cfg(feature = "keycloak-oidc")]
pub use protocol::oauth2::keycloak::KeycloakTokenSet;

/// Keycloak realm 访问信息(roles 列表)。
#[cfg(feature = "keycloak-oidc")]
pub use protocol::oauth2::keycloak::RealmAccess;

// 安全防护套件

/// 防火墙策略 trait(IP 级安全检查契约)。
#[cfg(feature = "firewall")]
pub use strategy::firewall::GarrisonFirewallStrategy;

/// 防火墙上下文(IP / login_id / tenant_id)。
#[cfg(feature = "firewall")]
pub use strategy::firewall::FirewallContext;

/// 防火墙策略注册条目(inventory 收集,仅含 name)。
#[cfg(feature = "firewall")]
pub use strategy::firewall::StrategyRegistration;

/// 暴力破解防护策略 + 配置。
#[cfg(feature = "firewall-bruteforce")]
pub use strategy::firewall::{BruteForceConfig, BruteForceStrategy};

/// 速率限制策略 + 配置 + 作用域枚举。
#[cfg(feature = "firewall-ratelimit")]
pub use strategy::firewall::{RateLimitConfig, RateLimitScope, RateLimitStrategy};

/// 异地登录检测策略 + 配置。
#[cfg(feature = "firewall-anomalous")]
pub use strategy::firewall::{AnomalousConfig, AnomalousLoginStrategy};

/// DDoS 防护策略 + 配置。
#[cfg(feature = "firewall-ddos")]
pub use strategy::firewall::{DDoSConfig, DDoSStrategy};

/// GeoIP 地理位置拦截策略 + 配置。
#[cfg(feature = "firewall-geoip")]
pub use strategy::firewall::{GeoIPConfig, GeoIPStrategy};

/// 地理坐标 + GeoLookup / CountryLookup trait(anomalous / geoip 共享)。
#[cfg(any(feature = "firewall-anomalous", feature = "firewall-geoip"))]
pub use strategy::firewall::{CountryLookup, GeoCoord, GeoLookup};

// 过程宏注解

/// 过程宏注解模块(`annotation-macros` feature):re-export `garrison-macros` 的
/// `#[proc_macro_attribute]` 宏(check_login / check_permission / check_role / check_access_token /
/// check_client_token / check_temp_token / check_api_key / check_mfa / check_abac / check_disable 等)。
/// 宏将 async fn 包装为 wrapper,在 body 前插入 `GarrisonUtil::check_*()` 调用,
/// 失败时返回 `axum::response::Response`(401/403)。
///
/// # 示例
///
/// ```ignore
/// use garrison::check_login;
/// use axum::response::IntoResponse;
///
/// #[check_login]
/// async fn handler() -> impl IntoResponse {
/// "hello"
/// }
/// ```
#[cfg(feature = "annotation-macros")]
pub use garrison_macros::{
    check_abac, check_access_token, check_api_key, check_client_token, check_disable, check_login,
    check_login_forge, check_mfa, check_permission, check_permission_forge, check_role,
    check_role_forge, check_temp_token,
};

// MSRV 元数据守卫(仅测试)

/// `rust-version` 单一事实源守卫:该字段是发布契约,仓库内四处编码同一数值,任一处漂移即
/// 复现「声明 1.85、依赖面需 1.97.1」型矛盾——cargo 以 `rustc ... is not supported by the
/// following packages` 拒绝低于依赖面要求的工具链,故声明值必须是依赖图可满足的最低工具链:
/// 根清单 `[package]` / `[workspace.package]`(macros、examples 经前者继承)、`clippy.toml`
/// 的 `msrv`(lint 据此判定 API 可用性)、CI 测试矩阵的 MSRV 腿及其门控步骤(以声明值编译
/// 锁定依赖图,是声明与依赖面一致性的实测门禁)、README 双语徽章(用户侧口径)。
#[cfg(test)]
mod msrv_guard {
    /// 按路径取 TOML 字符串值(缺键返回 `None`,由调用方给出可读失败信息)。
    fn toml_str<'a>(value: &'a toml::Value, path: &[&str]) -> Option<&'a str> {
        let mut cur = value;
        for key in path {
            cur = cur.get(*key)?;
        }
        cur.as_str()
    }

    fn cargo_toml() -> toml::Value {
        toml::from_str(include_str!("../Cargo.toml")).expect("根 Cargo.toml 应为合法 TOML")
    }

    fn declared_msrv() -> String {
        toml_str(&cargo_toml(), &["package", "rust-version"])
            .expect("根 Cargo.toml 的 [package] 应声明 rust-version")
            .to_string()
    }

    /// 枚举 `text` 中全部「`prefix` 之后到下一处 `delimiter`」片段,用于比对同一标记的多处取值。
    fn extract_values<'a>(text: &'a str, prefix: &str, delimiter: &str) -> Vec<&'a str> {
        let mut out = Vec::new();
        let mut rest = text;
        while let Some(idx) = rest.find(prefix) {
            let tail = &rest[idx + prefix.len()..];
            let Some(end) = tail.find(delimiter) else {
                break;
            };
            out.push(&tail[..end]);
            rest = &tail[end..];
        }
        out
    }

    #[test]
    fn msrv_single_source_of_truth_manifest_and_clippy() {
        let msrv = declared_msrv();
        assert_eq!(
            toml_str(&cargo_toml(), &["workspace", "package", "rust-version"]),
            Some(msrv.as_str()),
            "[workspace.package].rust-version 必须与 [package].rust-version 一致(macros/examples 经此继承)"
        );
        let clippy: toml::Value =
            toml::from_str(include_str!("../clippy.toml")).expect("clippy.toml 应为合法 TOML");
        assert_eq!(
            toml_str(&clippy, &["msrv"]),
            Some(msrv.as_str()),
            "clippy.toml 的 msrv 必须与 Cargo.toml 的 rust-version 一致,否则 lint 按错误 MSRV 判定 API 可用性"
        );
    }

    #[test]
    fn msrv_single_source_of_truth_ci_and_badge() {
        let msrv = declared_msrv();
        let ci = include_str!("../.github/workflows/ci.yml");
        let matrix = format!("rust: [{msrv}, stable, beta]");
        assert!(
            ci.contains(&matrix),
            "ci.yml 测试矩阵的 MSRV 腿未钉在声明值(期望 `{matrix}`):该腿以声明值编译锁定依赖图,声明与依赖面不一致时先在此暴露"
        );
        // 门控步骤(Linux 独占的 run 维度补齐)必须整体切到声明值:只改矩阵行会留下旧值门控
        let gates = extract_values(ci, "matrix.rust == '", "'");
        assert!(
            !gates.is_empty(),
            "ci.yml 未找到 MSRV 腿门控步骤(`matrix.rust == '<版本>'`)"
        );
        let stale: Vec<&str> = gates.iter().copied().filter(|v| *v != msrv).collect();
        assert!(
            stale.is_empty(),
            "ci.yml 的 MSRV 腿门控步骤仍钉在旧值 {stale:?}(声明值为 {msrv})"
        );
        for (name, text) in [
            ("README.md", include_str!("../README.md")),
            ("README_EN.md", include_str!("../README_EN.md")),
        ] {
            let badges = extract_values(text, "badge/rust-", "%2B");
            assert_eq!(
                badges,
                vec![msrv.as_str()],
                "{name} 的 Rust 徽章必须唯一且等于 Cargo.toml 的 rust-version(实际 {badges:?},声明值 {msrv})"
            );
        }
    }
}