yang_base/action/auth/
audit.rs1use async_trait::async_trait;
4
5#[derive(Debug, Clone)]
16#[non_exhaustive]
17pub struct AuthAuditEvent {
18 pub request_id: String,
20 pub action: &'static str,
22 pub subject: Option<String>,
24 pub error_code: Option<&'static str>,
26}
27
28pub fn token_fingerprint(token: &str) -> String {
33 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#[async_trait]
47pub trait AuthAuditHook: Send + Sync + 'static {
48 async fn on_success(&self, event: AuthAuditEvent);
50 async fn on_failure(&self, event: AuthAuditEvent);
52}
53
54#[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}