Redact Secrets From Log Lines

Fold str::replace over known secrets so log lines mask tokens before printing, then assert the masked output contains none of them.

RustSecurity Boundaries

Code

rustsnippet
21 lines
fn redact(secret: &str, text: &str) -> String {
    if secret.is_empty() {
        return text.to_string();
    }
    text.replace(secret, "***")
}

fn main() {
    let secrets = ["sk-live-9f2e1c", "user=42"];
    let log_line = "auth ok token=sk-live-9f2e1c user=42 ip=10.0.0.7";

    println!("raw : {log_line}");
    // log lines never leak the secrets after masking

    let mut safe = log_line.to_string();
    for secret in secrets {
        safe = redact(secret, &safe);
    }
    println!("safe: {safe}");
    println!("clean: {}", secrets.iter().all(|s| !safe.contains(s)));
}

How the snippet works

Read it this way: everything runs through the functions redact and main, doing all the work.

Iteration happens inside for secret in secrets — everything outside it runs once.

What to watch for

  • It carries its own context — no imports beyond the runtime’s own surface.

Using it

Signature: fn redact(secret: &str, text: &str) -> String

The run prints labeled output — raw :, safe:, clean: — when the file runs.

Launch the file; main takes over and steps through redact.

Key statements

fn redact(secret: &str, text: &str) -> String {
    if secret.is_empty() {
        return text.to_string();
    }
    text.replace(secret, "***")
}

Interactive Tools for This Topic

FAQ

What does Redact Secrets From Log Lines print when run?
Run it as a complete program — the output lines carry labels such as `raw :`, `safe:`, `clean:`.