Skip to main content

dre_core/
secrets.rs

1//! Secret masking. The value of every environment variable named `DRE_SECRET_*`, and of every
2//! environment variable `profiles.yml` reads through `env_var()` into a secret field (one the
3//! plugin declares secret, or named like `password`, `token`, `api_key`), is replaced by
4//! `*****` in everything DRE writes for people to read: the console, `logs/dre.log`, JSON events,
5//! `run_results.json` and the compiled SQL in `target/compiled/`. The SQL actually sent to the
6//! database is unchanged. `mask_secrets: false` in `dre_project.yml` turns masking off.
7//!
8//! JSON is redacted structurally, before it is serialized: serializing escapes `"`, `\` and
9//! control characters, so masking the finished text would miss a secret that contains them. Use
10//! [`to_json_pretty`] / [`to_json_line`] for every JSON surface, never `mask` on JSON text.
11//!
12//! Values shorter than 4 characters aren't masked: replacing every `a` or `12` in a log would
13//! make it unreadable, and a value that short isn't a secret anyway.
14
15use std::borrow::Cow;
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::sync::{Arc, LazyLock, RwLock};
18
19pub const PREFIX: &str = "DRE_SECRET_";
20pub const MASK: &str = "*****";
21pub const MASKED_SOURCE_ERROR: &str =
22    "source error details omitted because the request contains a masked secret";
23const MIN_LEN: usize = 4;
24
25static ENABLED: AtomicBool = AtomicBool::new(true);
26
27fn eligible(value: &str) -> bool {
28    value.chars().count() >= MIN_LEN
29}
30
31/// Secret values, longest first so a secret containing another is masked whole. Starts with
32/// `DRE_SECRET_*`; [`register_secret_field`] adds the variables secret profile fields read.
33static SECRETS: LazyLock<RwLock<Arc<Secrets>>> = LazyLock::new(|| {
34    RwLock::new(Arc::new(Secrets::new(sorted(
35        std::env::vars()
36            .filter(|(k, _)| k.starts_with(PREFIX))
37            .map(|(_, v)| v),
38    ))))
39});
40
41/// The secret values, and the forms they take in Markdown and in collapsed titles.
42struct Secrets {
43    plain: Vec<String>,
44    markdown: Vec<String>,
45    title: Vec<String>,
46}
47
48impl Secrets {
49    fn new(plain: Vec<String>) -> Secrets {
50        let markdown = sorted(
51            plain
52                .iter()
53                .flat_map(|s| [s.clone(), dre_protocol::markdown::escape(s)]),
54        );
55        let title = sorted(
56            plain
57                .iter()
58                .flat_map(|s| [s.clone(), s.split_whitespace().collect::<Vec<_>>().join(" ")]),
59        );
60        Secrets {
61            plain,
62            markdown,
63            title,
64        }
65    }
66}
67
68fn sorted(values: impl IntoIterator<Item = String>) -> Vec<String> {
69    let mut v: Vec<String> = values.into_iter().filter(|v| eligible(v)).collect();
70    v.sort_by_key(|s| std::cmp::Reverse(s.len()));
71    v.dedup();
72    v
73}
74
75fn secrets() -> Arc<Secrets> {
76    SECRETS.read().unwrap_or_else(|e| e.into_inner()).clone()
77}
78
79/// The environment variables a template reads through `env_var('NAME')` (either quote).
80pub fn env_references(text: &str) -> Vec<String> {
81    static CALL: LazyLock<regex::Regex> =
82        LazyLock::new(|| regex::Regex::new(r#"env_var\(\s*(?:'([^']+)'|"([^"]+)")"#).unwrap());
83    CALL.captures_iter(text)
84        .filter_map(|c| c.get(1).or_else(|| c.get(2)))
85        .map(|m| m.as_str().to_owned())
86        .collect()
87}
88
89/// Whether a profile field's name says it holds a secret. Paths, hosts and fingerprints don't
90/// count (`private_key_path`, `host_key_fingerprint`): masking them would hide what a message is
91/// about, and they aren't secrets.
92pub fn secret_field_name(name: &str) -> bool {
93    let name = name.to_ascii_lowercase();
94    ["password", "passphrase", "secret", "token", "credential"]
95        .iter()
96        .any(|w| name.contains(w))
97        || name == "key"
98        || name.ends_with("_key")
99        || name == "apikey"
100}
101
102/// Mask the values of the environment variables a secret profile field reads through
103/// `env_var()`, at any depth of `value`.
104pub fn register_secret_field(value: &serde_json::Value) {
105    let mut text = Vec::new();
106    collect_strings(value, &mut text);
107    register(text.iter().flat_map(|s| env_references(s)))
108}
109
110/// Mask the `env_var()` values that the secret fields of `fields` (a profile target) read,
111/// nested blocks (`ssh:`) included. `secret` adds names a plugin declares secret.
112pub fn register_secret_fields(fields: &serde_json::Map<String, serde_json::Value>, secret: &[String]) {
113    for (name, value) in fields {
114        if secret_field_name(name) || secret.contains(name) {
115            register_secret_field(value);
116        } else if let serde_json::Value::Object(nested) = value {
117            register_secret_fields(nested, &[]);
118        }
119    }
120}
121
122fn collect_strings<'a>(value: &'a serde_json::Value, out: &mut Vec<&'a str>) {
123    match value {
124        serde_json::Value::String(s) => out.push(s),
125        serde_json::Value::Array(a) => a.iter().for_each(|v| collect_strings(v, out)),
126        serde_json::Value::Object(o) => o.values().for_each(|v| collect_strings(v, out)),
127        _ => {}
128    }
129}
130
131fn register(names: impl Iterator<Item = String>) {
132    let values: Vec<String> = names
133        .into_iter()
134        .filter_map(|name| std::env::var(name).ok())
135        .collect();
136    if values.is_empty() {
137        return;
138    }
139    let mut guard = SECRETS.write().unwrap_or_else(|e| e.into_inner());
140    let merged = sorted(guard.plain.iter().cloned().chain(values));
141    *guard = Arc::new(Secrets::new(merged));
142}
143
144pub fn set_enabled(on: bool) {
145    ENABLED.store(on, Ordering::Relaxed);
146}
147
148pub(crate) fn enabled() -> bool {
149    ENABLED.load(Ordering::Relaxed)
150}
151
152fn mask_with<'a>(s: &'a str, secrets: &[String]) -> Cow<'a, str> {
153    if !secrets.iter().any(|x| s.contains(x.as_str())) {
154        return Cow::Borrowed(s);
155    }
156    let mut out = s.to_string();
157    for x in secrets {
158        out = out.replace(x.as_str(), MASK);
159    }
160    Cow::Owned(out)
161}
162
163/// `s` with every secret value replaced by `*****`.
164pub fn mask(s: &str) -> Cow<'_, str> {
165    if !ENABLED.load(Ordering::Relaxed) {
166        return Cow::Borrowed(s);
167    }
168    mask_with(s, &secrets().plain)
169}
170
171/// Mask a rendered message without changing the report payload. Markdown interpolation has
172/// already escaped punctuation, so both literal and escaped secret values must be matched.
173pub(crate) fn mask_markdown(s: &str) -> Cow<'_, str> {
174    if !ENABLED.load(Ordering::Relaxed) {
175        return Cow::Borrowed(s);
176    }
177    mask_with(s, &secrets().markdown)
178}
179
180/// Message titles collapse whitespace before delivery. Match that representation as well as
181/// the literal secret when protecting a title in logs and run metadata.
182pub(crate) fn mask_message_title(s: &str) -> Cow<'_, str> {
183    if !ENABLED.load(Ordering::Relaxed) {
184        return Cow::Borrowed(s);
185    }
186    mask_with(s, &secrets().title)
187}
188
189/// Whether masking is enabled and `s` contains a complete registered secret.
190pub fn contains_secret(s: &str) -> bool {
191    ENABLED.load(Ordering::Relaxed) && secrets().plain.iter().any(|secret| s.contains(secret.as_str()))
192}
193
194fn mask_source_error_with<'a>(error: &'a str, sensitive: bool, secrets: &[String]) -> Cow<'a, str> {
195    if sensitive {
196        Cow::Borrowed(MASKED_SOURCE_ERROR)
197    } else {
198        mask_with(error, secrets)
199    }
200}
201
202/// Mask a source error before it reaches logs or output. Source plugins can transform or truncate
203/// a request in their diagnostics, so exact replacement is not sufficient for a secret-bearing
204/// request. In that case the opaque detail is omitted instead.
205pub fn mask_source_error(error: &str, sensitive: bool) -> Cow<'_, str> {
206    if !ENABLED.load(Ordering::Relaxed) {
207        return Cow::Borrowed(error);
208    }
209    mask_source_error_with(error, sensitive, &secrets().plain)
210}
211
212fn unique_masked_names_with(names: &[String], secrets: &[String]) -> Vec<String> {
213    use std::collections::BTreeSet;
214
215    let masked: Vec<String> = names
216        .iter()
217        .map(|name| mask_with(name, secrets).into_owned())
218        .collect();
219    if names == masked {
220        return names.to_vec();
221    }
222    let mut used = BTreeSet::new();
223    let mut output = vec![String::new(); names.len()];
224    let mut pending = Vec::new();
225
226    // Literal names keep their public identity and reserve every suffix they already occupy.
227    for (index, (original, protected)) in names.iter().zip(&masked).enumerate() {
228        if original == protected {
229            used.insert(original.clone());
230            output[index].clone_from(original);
231        } else {
232            pending.push((protected.clone(), original.clone(), index));
233        }
234    }
235
236    // Original names make the assignment stable when source ordering changes.
237    pending.sort();
238    for (base, _, index) in pending {
239        let mut candidate = base.clone();
240        let mut suffix = 2;
241        while !used.insert(candidate.clone()) {
242            candidate = format!("{base}#{suffix}");
243            suffix += 1;
244        }
245        output[index] = candidate;
246    }
247    output
248}
249
250fn redact_json_with(v: &mut serde_json::Value, secrets: &[String]) {
251    use serde_json::Value;
252    match v {
253        Value::String(s) => {
254            if let Cow::Owned(m) = mask_with(s, secrets) {
255                *s = m;
256            }
257        }
258        Value::Array(a) => a.iter_mut().for_each(|v| redact_json_with(v, secrets)),
259        Value::Object(o) => {
260            let entries = std::mem::take(o);
261            let keys: Vec<String> = entries.keys().cloned().collect();
262            let protected_keys = unique_masked_names_with(&keys, secrets);
263            for ((_, mut val), protected_key) in entries.into_iter().zip(protected_keys) {
264                redact_json_with(&mut val, secrets);
265                o.insert(protected_key, val);
266            }
267        }
268        _ => {}
269    }
270}
271
272/// `v` with every secret value replaced by `*****` in all strings and object keys. Colliding
273/// masked keys receive `#2`, `#3`, and so on rather than silently replacing another entry.
274pub fn redact_json(v: &mut serde_json::Value) {
275    if ENABLED.load(Ordering::Relaxed) {
276        redact_json_with(v, &secrets().plain);
277    }
278}
279
280fn redacted<T: serde::Serialize>(v: &T) -> serde_json::Result<serde_json::Value> {
281    let mut v = serde_json::to_value(v)?;
282    redact_json(&mut v);
283    Ok(v)
284}
285
286/// Pretty JSON of `v` with secrets redacted first.
287pub fn to_json_pretty<T: serde::Serialize>(v: &T) -> serde_json::Result<String> {
288    serde_json::to_string_pretty(&redacted(v)?)
289}
290
291/// One-line JSON of `v` with secrets redacted first.
292pub fn to_json_line<T: serde::Serialize>(v: &T) -> serde_json::Result<String> {
293    serde_json::to_string(&redacted(v)?)
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299    use serde_json::json;
300
301    fn secrets(values: &[&str]) -> Vec<String> {
302        let mut values: Vec<String> = values.iter().map(|v| (*v).to_string()).collect();
303        values.sort_by_key(|s| std::cmp::Reverse(s.len()));
304        values
305    }
306
307    #[test]
308    fn redacts_nested_values_longest_first() {
309        let secrets = secrets(&["nested-secret", "nested-secret-and-more"]);
310        let mut value = json!({"items": ["nested-secret-and-more", {"value": "x nested-secret y"}]});
311        redact_json_with(&mut value, &secrets);
312        assert_eq!(value, json!({"items": ["*****", {"value": "x ***** y"}]}));
313    }
314
315    #[test]
316    fn preserves_entries_when_masked_keys_collide() {
317        let secrets = secrets(&["alpha-secret-key", "bravo-secret-key"]);
318        let mut value = json!({
319            "alpha-secret-key": 1,
320            "bravo-secret-key": 2,
321            "*****": 3,
322            "*****#2": 4,
323        });
324        redact_json_with(&mut value, &secrets);
325        assert_eq!(
326            value,
327            json!({
328                "*****": 3,
329                "*****#2": 4,
330                "*****#3": 1,
331                "*****#4": 2,
332            })
333        );
334    }
335
336    #[test]
337    fn masking_one_name_does_not_rename_duplicate_literal_names() {
338        let secrets = secrets(&["secret-column"]);
339        let names = ["a", "a", "secret-column"].map(str::to_string);
340        assert_eq!(unique_masked_names_with(&names, &secrets), ["a", "a", "*****"]);
341    }
342
343    #[test]
344    fn suppresses_transformed_source_errors_only_for_secret_requests() {
345        let secrets = secrets(&["long-secret-value-that-a-source-truncated"]);
346        let error = "LINE 1: select * from long-secret-value-that-a-source...";
347        assert_eq!(mask_source_error_with(error, true, &secrets), MASKED_SOURCE_ERROR);
348        assert_eq!(
349            mask_source_error_with("ordinary syntax error", false, &secrets),
350            "ordinary syntax error"
351        );
352    }
353
354    #[test]
355    fn finds_env_var_references_with_either_quote() {
356        assert_eq!(
357            env_references(
358                "password: \"{{ env_var('PG_PASSWORD') }}\"\ntoken: '{{ env_var(\"WAREHOUSE_TOKEN\", \"x\") }}'"
359            ),
360            ["PG_PASSWORD", "WAREHOUSE_TOKEN"]
361        );
362    }
363
364    #[test]
365    fn secret_field_names_leave_paths_and_fingerprints_alone() {
366        for name in [
367            "password",
368            "client_secret",
369            "token",
370            "api_key",
371            "private_key",
372            "key",
373            "passphrase",
374        ] {
375            assert!(secret_field_name(name), "{name}");
376        }
377        for name in [
378            "path",
379            "host",
380            "private_key_path",
381            "host_key_fingerprint",
382            "key_id",
383            "keyspace",
384            "schema",
385        ] {
386            assert!(!secret_field_name(name), "{name}");
387        }
388    }
389
390    #[test]
391    fn minimum_length_counts_unicode_characters() {
392        assert!(!eligible("ééé"));
393        assert!(eligible("éééé"));
394    }
395}