Skip to main content

micromegas_auth/
log_sanitize.rs

1//! Sanitizing of caller-controlled text before it reaches a log line, and the shared
2//! auth-rejection log line.
3
4use 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
11/// Makes `value` safe to put in a log line: control and bidi override/isolate characters become
12/// `?`, so one line can't pretend to be two or render reordered in a terminal. Longer than
13/// `max_chars` characters is cut to `max_chars - 1` characters plus `…`.
14pub 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
38/// The sanitized properties shared by every authentication-rejection line.
39pub 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    /// Only the request path (never the query string) and the `user-agent` header are read, so a
49    /// credential has no way into the line.
50    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
64/// Logs an authentication rejection with the caller's network details as properties.
65pub 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}