Skip to main content

yang_base/action/auth/
audit.rs

1//! 认证审计钩子:登录/刷新/登出的成功与失败事件(可观测性 C4)。
2
3use async_trait::async_trait;
4
5// ──────────────────────────────────────────────────────────────────────────────
6// AuthAuditHook:认证审计钩子(可观测性 C4)
7// ──────────────────────────────────────────────────────────────────────────────
8
9/// 认证审计事件。
10///
11/// 描述一次认证相关操作(登录/刷新/登出)的结果。**绝不携带凭据明文或 Token
12/// 原文**:需要标识 Token 时只放指纹([`token_fingerprint`])。
13///
14/// 标注 `#[non_exhaustive]`:未来新增字段不构成破坏性变更。
15#[derive(Debug, Clone)]
16#[non_exhaustive]
17pub struct AuthAuditEvent {
18    /// 本次派发的 request_id(十六进制串)
19    pub request_id: String,
20    /// 操作名(`"login"` / `"refresh"` / `"logout"`,静态)
21    pub action: &'static str,
22    /// 主体标识(用户名或 sub);失败且未知时为 `None`
23    pub subject: Option<String>,
24    /// 失败时的错误码(`BaseError::code_str`,静态);成功时为 `None`
25    pub error_code: Option<&'static str>,
26}
27
28/// 计算 Token 的短指纹(SHA256 前若干字节的十六进制),用于审计日志而不泄漏原文。
29///
30/// 这里不引入额外哈希依赖,采用 FNV-1a 64 位哈希取十六进制——审计场景只需「同一
31/// Token 多次出现可对应」而非密码学强度,FNV 足够且零依赖。
32pub fn token_fingerprint(token: &str) -> String {
33    // FNV-1a 64-bit
34    let mut hash: u64 = 0xcbf29ce484222325;
35    for b in token.as_bytes() {
36        hash ^= *b as u64;
37        hash = hash.wrapping_mul(0x100000001b3);
38    }
39    format!("{:016x}", hash)
40}
41
42/// 认证审计钩子:在登录/刷新/登出的成功/失败处被调用。
43///
44/// object-safe,可经构造参数注入(与 [`CredentialVerifier`](super::CredentialVerifier) 注入同构)。默认实现
45/// [`TracingAuditHook`] 发 tracing event。实现者**绝不应**记录凭据明文/Token 原文。
46#[async_trait]
47pub trait AuthAuditHook: Send + Sync + 'static {
48    /// 认证成功事件。
49    async fn on_success(&self, event: AuthAuditEvent);
50    /// 认证失败事件。
51    async fn on_failure(&self, event: AuthAuditEvent);
52}
53
54/// 默认审计钩子:成功发 `tracing::info!`,失败发 `tracing::warn!`。
55#[derive(Debug, Clone, Default)]
56pub struct TracingAuditHook;
57
58#[async_trait]
59impl AuthAuditHook for TracingAuditHook {
60    async fn on_success(&self, event: AuthAuditEvent) {
61        tracing::info!(
62            request_id = %event.request_id,
63            action = event.action,
64            subject = event.subject.as_deref().unwrap_or("-"),
65            "认证成功",
66        );
67    }
68
69    async fn on_failure(&self, event: AuthAuditEvent) {
70        tracing::warn!(
71            request_id = %event.request_id,
72            action = event.action,
73            subject = event.subject.as_deref().unwrap_or("-"),
74            error_code = event.error_code.unwrap_or("-"),
75            "认证失败",
76        );
77    }
78}