use async_trait::async_trait;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AuthAuditEvent {
pub request_id: String,
pub action: &'static str,
pub subject: Option<String>,
pub error_code: Option<&'static str>,
}
pub fn token_fingerprint(token: &str) -> String {
let mut hash: u64 = 0xcbf29ce484222325;
for b in token.as_bytes() {
hash ^= *b as u64;
hash = hash.wrapping_mul(0x100000001b3);
}
format!("{:016x}", hash)
}
#[async_trait]
pub trait AuthAuditHook: Send + Sync + 'static {
async fn on_success(&self, event: AuthAuditEvent);
async fn on_failure(&self, event: AuthAuditEvent);
}
#[derive(Debug, Clone, Default)]
pub struct TracingAuditHook;
#[async_trait]
impl AuthAuditHook for TracingAuditHook {
async fn on_success(&self, event: AuthAuditEvent) {
tracing::info!(
request_id = %event.request_id,
action = event.action,
subject = event.subject.as_deref().unwrap_or("-"),
"认证成功",
);
}
async fn on_failure(&self, event: AuthAuditEvent) {
tracing::warn!(
request_id = %event.request_id,
action = event.action,
subject = event.subject.as_deref().unwrap_or("-"),
error_code = event.error_code.unwrap_or("-"),
"认证失败",
);
}
}