Skip to main content

dre_core/
secrets.rs

1//! Secret masking. The value of every environment variable named `DRE_SECRET_*` is replaced by
2//! `*****` in everything DRE writes for people to read: the console, `logs/dre.log`, JSON events,
3//! `run_results.json` and the compiled SQL in `target/compiled/`. The SQL actually sent to the
4//! database is unchanged. `mask_secrets: false` in `dre_project.yml` turns masking off.
5//!
6//! Values shorter than 4 characters aren't masked: replacing every `a` or `12` in a log would
7//! make it unreadable, and a value that short isn't a secret anyway.
8
9use std::borrow::Cow;
10use std::sync::LazyLock;
11use std::sync::atomic::{AtomicBool, Ordering};
12
13pub const PREFIX: &str = "DRE_SECRET_";
14pub const MASK: &str = "*****";
15const MIN_LEN: usize = 4;
16
17static ENABLED: AtomicBool = AtomicBool::new(true);
18
19/// Secret values, longest first so a secret containing another is masked whole.
20static SECRETS: LazyLock<Vec<String>> = LazyLock::new(|| {
21    let mut v: Vec<String> = std::env::vars()
22        .filter(|(k, v)| k.starts_with(PREFIX) && v.chars().count() >= MIN_LEN)
23        .map(|(_, v)| v)
24        .collect();
25    v.sort_by_key(|s| std::cmp::Reverse(s.len()));
26    v.dedup();
27    v
28});
29
30pub fn set_enabled(on: bool) {
31    ENABLED.store(on, Ordering::Relaxed);
32}
33
34/// `s` with every secret value replaced by `*****`.
35pub fn mask(s: &str) -> Cow<'_, str> {
36    if !ENABLED.load(Ordering::Relaxed) || !SECRETS.iter().any(|x| s.contains(x.as_str())) {
37        return Cow::Borrowed(s);
38    }
39    let mut out = s.to_string();
40    for x in SECRETS.iter() {
41        out = out.replace(x.as_str(), MASK);
42    }
43    Cow::Owned(out)
44}