garrison 0.9.0

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

//! 密码策略套件子模块(吸收 Keycloak PasswordPolicyRule):可插拔规则 + 统一引擎执行。
//!
//! # 核心类型
//!
//! `PasswordPolicyRule` trait 为规则抽象(同步纯函数,`name` + `validate`),`PolicyContext` 为校验上下文,
//! `PasswordPolicyEngine` 为规则引擎(FirstError/AllErrors),`PolicyError` 为校验错误。
//!
//! # 设计
//!
//! 规则为同步纯函数(无 IO/await),参数由构造器注入(支持 `GarrisonConfig` 加载);引擎按 `ErrorMode`
//! 执行:`FirstError` 短路,`AllErrors` 收集全部。

pub mod engine;
mod error;
pub mod rules;

pub use error::PolicyError;
#[cfg(feature = "metrics-prometheus")]
use std::sync::Arc;
/// 密码策略规则 trait:同步纯函数(不执行 IO/await,无 `#[async_trait]`),对象安全,可作
/// `Box<dyn PasswordPolicyRule>` / `Vec<Box<dyn PasswordPolicyRule>>` 使用。
///
/// # 示例
///
/// ```ignore
/// use garrison::account::policy::{PasswordPolicyRule, PolicyContext, PolicyError};
///
/// struct AlwaysPassRule;
/// impl PasswordPolicyRule for AlwaysPassRule {
/// fn name(&self) -> &'static str { "always_pass" }
/// fn validate(&self, _ctx: &PolicyContext, _password: &str) -> Result<(), PolicyError> {
/// Ok(())
/// }
/// }
/// ```
pub trait PasswordPolicyRule: Send + Sync {
    /// 返回规则名称(编译期常量,如 `"length"` / `"complexity"`)。
    fn name(&self) -> &'static str;

    /// 校验密码是否符合规则;`Err.rule_name` 应与 [`name()`](Self::name) 一致。
    fn validate(&self, ctx: &PolicyContext, password: &str) -> Result<(), PolicyError>;
}

/// 策略校验上下文(6 字段 schema 锁定,pre-1.0 起字段不可增删)。
#[derive(Debug, Clone)]
pub struct PolicyContext {
    /// 用户 ID。
    pub user_id: String,
    /// 租户 ID(可选,多租户场景使用)。
    pub tenant_id: Option<String>,
    /// 用户名(可选,用于 `NotUsernameRule` 相似度检测)。
    pub username: Option<String>,
    /// 邮箱(可选,用于 `NotEmailRule` 检测)。
    pub email: Option<String>,
    /// 密码历史(hash 列表,非明文,用于 `HistoryRule` 检测)。
    pub password_history: Vec<String>,
    /// 密码创建时间(Unix 秒);`None`(未提供)时 `MaxAgeRule` fail-open(跳过过期检查,不阻塞改密)。
    pub password_created_at: Option<i64>,
}

/// 引擎错误返回模式。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorMode {
    /// 首条失败即返回并短路(不执行后续规则)。
    FirstError,
    /// 执行所有规则,收集全部错误。
    AllErrors,
}

/// 密码策略引擎:持规则列表 + 错误模式,按 `mode` 执行规则校验。
///
/// # 示例
///
/// ```ignore
/// use garrison::account::policy::{ErrorMode, PasswordPolicyEngine, PolicyContext};
/// // 实现具体规则后注入
/// let engine = PasswordPolicyEngine::new(Vec::new(), ErrorMode::FirstError);
/// let ctx = PolicyContext {
/// user_id: "alice".into(),
/// tenant_id: None,
/// username: None,
/// email: None,
/// password_history: Vec::new(),
/// password_created_at: None,
/// };
/// assert!(engine.validate(&ctx, "password").is_ok()); // 空规则集 → Ok
/// ```
pub struct PasswordPolicyEngine {
    /// 规则列表(按注册顺序执行)。
    rules: Vec<Box<dyn PasswordPolicyRule>>,
    mode: ErrorMode,
    /// 账号安全指标(可选,注入后每条规则校验后调用 `observe_policy_validate`)。
    #[cfg(feature = "metrics-prometheus")]
    metrics: Option<Arc<crate::account::metrics::AccountMetrics>>,
}

#[cfg(test)]
mod tests;