garrison 0.9.0

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

//! 邀请码防爆破尝试锁定器。
//!
//! 委托 limiteron `DistributedLimiter` 适配器([`GarrisonDaoDistributedLimiter`],
//! 与 `BruteForceStrategy` 同构的原子计数路径)按来源标识(如 IP)计数,超过
//! 阈值后拒绝后续尝试,直至窗口过期或显式 `reset`。
//!
//! 仅在启用 `protocol-invitation` 特性时编译。

use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::limiteron::GarrisonDaoDistributedLimiter;
use limiteron::limiters::DistributedLimiter;
use std::sync::Arc;
use std::time::Duration;

/// 尝试计数键前缀。
const ATTEMPT_KEY_PREFIX: &str = "garrison:invitation:attempt:";

/// 防爆破尝试锁定器(默认 10 次 / 600 秒窗口)。
pub struct InvitationAttemptLimiter {
    /// limiteron 分布式限流适配器(原子计数 + 窗口 TTL)。
    pub(crate) limiter: GarrisonDaoDistributedLimiter,
    /// 窗口内允许的最大尝试次数。
    pub(crate) max_attempts: u32,
    /// 计数窗口秒数。
    pub(crate) window_seconds: u64,
}

impl InvitationAttemptLimiter {
    /// 以默认阈值(10 次 / 600 秒窗口)创建。
    pub fn new(dao: Arc<dyn GarrisonDao>) -> Self {
        Self::with_config(dao, 10, 600)
    }

    /// 自定义阈值与窗口创建。
    pub fn with_config(dao: Arc<dyn GarrisonDao>, max_attempts: u32, window_seconds: u64) -> Self {
        Self {
            limiter: GarrisonDaoDistributedLimiter::new(dao),
            max_attempts,
            window_seconds,
        }
    }

    /// 记录一次尝试并判断是否超限。
    ///
    /// 经 limiteron `DistributedLimiter::incr_with_ttl` 原子计数(键不存在时以
    /// `window_seconds` 建键);计数超过 `max_attempts` 返回
    /// `InvalidParam`(`invitation-too-many-attempts::<source>`)。每次调用都
    /// 计数——无论调用方后续成败。
    pub async fn check(&self, source: &str) -> GarrisonResult<()> {
        let key = format!("{}{}", ATTEMPT_KEY_PREFIX, source_digest_hex(source));
        let count = self
            .limiter
            .incr_with_ttl(&key, 1, Duration::from_secs(self.window_seconds))
            .await
            .map_err(|e| GarrisonError::Dao(format!("invitation-incr-ttl::{}", e)))?;
        if count > self.max_attempts as u64 {
            return Err(GarrisonError::InvalidParam(format!(
                "invitation-too-many-attempts::{}",
                source
            )));
        }
        Ok(())
    }

    /// 清除来源的尝试计数(redeem 成功后调用;对无计数来源幂等)。
    pub async fn reset(&self, source: &str) -> GarrisonResult<()> {
        let key = format!("{}{}", ATTEMPT_KEY_PREFIX, source_digest_hex(source));
        self.limiter
            .reset(&key)
            .await
            .map_err(|e| GarrisonError::Dao(format!("invitation-reset::{}", e)))
    }
}

/// source 的 SHA-256 十六进制摘要(防超长/特殊字符进入存储键)。
///
/// 取 SHA-256 而非 MD5:source 为攻击者可控输入(如 IP),MD5 存在实用
/// chosen-prefix 碰撞攻击,可被用于污染他人计数键。
fn source_digest_hex(source: &str) -> String {
    use sha2::{Digest, Sha256};
    use std::fmt::Write;
    let mut hasher = Sha256::new();
    hasher.update(source.as_bytes());
    let digest = hasher.finalize();
    let mut out = String::with_capacity(64);
    for byte in digest {
        let _ = write!(out, "{:02x}", byte);
    }
    out
}