pub fn extract_identity(
headers: &axum::http::HeaderMap,
peer: Option<std::net::SocketAddr>,
) -> String {
use axum::http::header;
if let Some(v) = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
&& let Some(tok) = v.strip_prefix("Bearer ")
{
let tok = tok.trim();
if !tok.is_empty() {
return format!("bearer:{}", hash_token(tok));
}
}
if let Some(xff) = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok())
&& let Some(first) = xff.split(',').next()
{
let first = first.trim();
if !first.is_empty() {
return format!("xff:{first}");
}
}
match peer {
Some(addr) => format!("peer:{}", addr.ip()),
None => "peer:unknown".to_string(),
}
}
fn hash_token(tok: &str) -> String {
let mut h: u64 = 0xcbf29ce484222325;
for b in tok.as_bytes() {
h ^= *b as u64;
h = h.wrapping_mul(0x100000001b3);
}
format!("{h:016x}")
}