fix: escape control chars in logged URI and headers (#691)

This commit is contained in:
sigoden
2026-04-25 18:51:21 +08:00
committed by GitHub
parent 19dc2c205a
commit 1af66d6744
+16 -2
View File
@@ -30,7 +30,9 @@ impl HttpLogger {
LogElement::Variable(name) => match name.as_str() { LogElement::Variable(name) => match name.as_str() {
"request" => { "request" => {
let uri = req.uri().to_string(); let uri = req.uri().to_string();
let uri = decode_uri(&uri).map(|s| s.to_string()).unwrap_or(uri); let uri = decode_uri(&uri)
.map(|s| sanitize_log_value(&s))
.unwrap_or(uri);
data.insert(name.to_string(), format!("{} {uri}", req.method())); data.insert(name.to_string(), format!("{} {uri}", req.method()));
} }
"remote_user" => { "remote_user" => {
@@ -44,7 +46,7 @@ impl HttpLogger {
}, },
LogElement::Header(name) => { LogElement::Header(name) => {
if let Some(value) = req.headers().get(name).and_then(|v| v.to_str().ok()) { if let Some(value) = req.headers().get(name).and_then(|v| v.to_str().ok()) {
data.insert(name.to_string(), value.to_string()); data.insert(name.to_string(), sanitize_log_value(value));
} }
} }
LogElement::Literal(_) => {} LogElement::Literal(_) => {}
@@ -104,3 +106,15 @@ impl FromStr for HttpLogger {
Ok(Self { elements }) Ok(Self { elements })
} }
} }
fn sanitize_log_value(s: &str) -> String {
s.chars()
.flat_map(|c| {
if c.is_control() {
format!("\\x{:02x}", c as u32).chars().collect::<Vec<_>>()
} else {
vec![c]
}
})
.collect()
}