Skip to main content

sanitize_path

Function sanitize_path 

Source
pub fn sanitize_path(raw: &str) -> Cow<'_, str>
Expand description

Render a request path as a bounded, log-safe string for use as a tracing span attribute.

The path is attacker-controlled (it flows out of the request URI after axum’s routing layer), so we apply three defences:

  1. Truncate to MAX_PATH_LEN bytes with a ellipsis suffix when the input is longer. Truncation lands on a UTF-8 char boundary so we never emit invalid UTF-8 to the tracing layer. The ellipsis is one Unicode code point (U+2026, three UTF-8 bytes) so the returned Cow::Owned is at most MAX_PATH_LEN + 3 bytes — the test in tests/trace_sanitization_test.rs asserts MAX_PATH_LEN + 4 to give a one-byte margin against future ellipsis tweaks.
  2. Replace non-printable / non-ASCII bytes with ?. Anything outside 0x20..=0x7E (printable ASCII) is collapsed to a single ? so terminal-escape sequences cannot smuggle out of a log viewer and multi-byte UTF-8 sequences (e.g. é0xC3 0xA9) cannot be reconstructed downstream.
  3. Strip CR / LF / NUL specifically. The printable-byte filter above already catches these, but we apply the explicit strip as defence in depth: a future relaxation of the printable filter must NOT re-open the CRLF-injection channel (forging fake JSON log lines) or the NUL channel (terminating C-string consumers).

When the input is already a clean ASCII-printable string short enough to fit, we return Cow::Borrowed to avoid the allocation.