micromegas_auth/
log_sanitize.rs1use crate::types::RequestParts;
5use micromegas_tracing::prelude::*;
6
7fn is_bidi_control(c: char) -> bool {
8 matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
9}
10
11pub fn sanitize_for_log(value: &str, max_chars: usize) -> String {
15 let truncate = value.chars().nth(max_chars).is_some();
16 let kept = if truncate {
17 max_chars.saturating_sub(1)
18 } else {
19 max_chars
20 };
21 let mut out: String = value
22 .chars()
23 .take(kept)
24 .map(|c| {
25 if c.is_control() || is_bidi_control(c) {
26 '?'
27 } else {
28 c
29 }
30 })
31 .collect();
32 if truncate && max_chars > 0 {
33 out.push('…');
34 }
35 out
36}
37
38pub struct RejectionFields {
40 pub client_ip: String,
41 pub method: String,
42 pub path: String,
43 pub user_agent: String,
44 pub reason: String,
45}
46
47impl RejectionFields {
48 pub fn new(parts: &dyn RequestParts, err: &anyhow::Error) -> Self {
51 Self {
52 client_ip: parts
53 .client_ip()
54 .map(|ip| ip.to_string())
55 .unwrap_or_default(),
56 method: sanitize_for_log(parts.method().unwrap_or_default(), 16),
57 path: sanitize_for_log(parts.uri().unwrap_or_default(), 256),
58 user_agent: sanitize_for_log(parts.get_header("user-agent").unwrap_or_default(), 256),
59 reason: sanitize_for_log(&format!("{err}"), 1024),
60 }
61 }
62}
63
64pub fn warn_auth_rejection(prefix: &'static str, parts: &dyn RequestParts, err: &anyhow::Error) {
66 let f = RejectionFields::new(parts, err);
67 warn!(
68 client_ip = %f.client_ip,
69 method = %f.method,
70 path = %f.path,
71 user_agent = %f.user_agent,
72 "{} {}",
73 prefix,
74 f.reason
75 );
76}