use url::Url;
#[allow(dead_code)] const MAX_URL_LOG_LEN: usize = 200;
#[must_use]
#[allow(dead_code)] pub(crate) fn redact_url_for_log(url: &str) -> String {
match Url::parse(url) {
Ok(mut parsed) => {
parsed.set_query(None);
parsed.set_fragment(None);
if parsed.username() != "" {
let _ = parsed.set_username("");
}
if parsed.password().is_some() {
parsed.set_password(None).ok();
}
let redacted = parsed.to_string();
if redacted.len() > MAX_URL_LOG_LEN {
let truncated: String = redacted.chars().take(MAX_URL_LOG_LEN).collect();
format!("{}...", truncated)
} else {
redacted
}
}
Err(_) => "[invalid-url]".to_string(),
}
}
#[must_use]
#[allow(dead_code)] pub(crate) fn redact_webhook_url_for_log(url: &str) -> String {
match Url::parse(url) {
Ok(mut parsed) => {
parsed.set_query(None);
parsed.set_fragment(None);
parsed.set_path("");
if parsed.username() != "" {
let _ = parsed.set_username("");
}
if parsed.password().is_some() {
parsed.set_password(None).ok();
}
format!(
"{}/[redacted-webhook-path]",
parsed.as_str().trim_end_matches('/')
)
}
Err(_) => "[invalid-webhook-url]".to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_query_and_fragment() {
let url = "https://example.com/path?token=secret&api_key=abc#fragment";
let redacted = redact_url_for_log(url);
assert_eq!(redacted, "https://example.com/path");
assert!(!redacted.contains("secret"));
assert!(!redacted.contains("abc"));
}
#[test]
fn strips_empty_query_only() {
let url = "https://example.com?token=secret";
let redacted = redact_url_for_log(url);
assert_eq!(redacted, "https://example.com/");
assert!(!redacted.contains("secret"));
}
#[test]
fn webhook_redaction_drops_path_secret() {
let url = "https://hooks.slack.com/services/T000/B000/SECRET";
let redacted = redact_webhook_url_for_log(url);
assert_eq!(redacted, "https://hooks.slack.com/[redacted-webhook-path]");
assert!(!redacted.contains("SECRET"));
}
#[test]
fn strips_userinfo_credentials() {
let url = "https://user:password@example.com/path?token=secret"; let redacted = redact_url_for_log(url);
assert_eq!(redacted, "https://example.com/path");
assert!(!redacted.contains("user"));
assert!(!redacted.contains("password"));
}
#[test]
fn preserves_path_and_port() {
assert_eq!(
redact_url_for_log("https://example.com/deep/nested/path"),
"https://example.com/deep/nested/path"
);
assert_eq!(
redact_url_for_log("http://localhost:8080/api"),
"http://localhost:8080/api"
);
}
#[test]
fn invalid_url_returns_placeholder() {
assert_eq!(redact_url_for_log("not a url"), "[invalid-url]");
}
#[test]
fn truncates_long_url() {
let long_path = "a".repeat(300);
let url = format!("https://example.com/{}", long_path);
let redacted = redact_url_for_log(&url);
assert!(redacted.ends_with("..."));
assert!(redacted.len() <= MAX_URL_LOG_LEN + 3); }
}