Skip to main content

schedr_config/
masked.rs

1//! A configuration as it may be shown or sent (decision 122, the user's requirement of
2//! 2026-10-31): masked by the node itself before it leaves the process, so no secret is stored
3//! or sent in clear.
4//!
5//! Secrets come only from environment variables, never the configuration file; the masking is
6//! the second line, for what a URL or a setting carries anyway. It works on the serialized
7//! configuration, every string of it, so a field added later is covered without being named:
8//!
9//! - **A value under a key naming a secret** is `****` whole, whatever it is (text, a number,
10//!   a list, an object). A name is compared without case and separators (`api_key`, `apiKey`
11//!   and `API-KEY` alike); a path to a secret file (`token_file`, `[tls] key` holding a path)
12//!   is shown: it is not the secret.
13//! - **In any text, a password before `@`** is `****`, the user, host, port and path kept
14//!   (`postgres://schedr:****@db:5432/schedr`): with a scheme or `//` or none (`u:p@db`),
15//!   several in one text, a password holding `@`, `:`, `/`, `'` or parentheses.
16//! - **In any text, a value after a name naming a secret** and `=` or `:` is `****`: a URL's
17//!   query (`?password=…`, the name percent-decoded: `%70assword`), a DSN
18//!   (`host=db password=…`), a message (`token: …`).
19//!
20//! Masking errs towards hiding: a port before `@` may be hidden with a password, an email's
21//! name after `mailto:` too. Never the other way.
22
23use serde_json::Value;
24
25#[cfg(test)]
26mod tests;
27
28/// What a masked secret is shown as.
29pub const MASK: &str = "****";
30
31/// `config` serialized and masked (see the module documentation).
32#[must_use]
33pub fn masked(config: &crate::Config) -> Value {
34    let mut value = serde_json::to_value(config).unwrap_or(Value::Null);
35    mask(&mut value);
36    mask_channels(&mut value);
37    value
38}
39
40/// A server webhook's URL may be its secret (a Slack or Teams webhook URL is the credential to
41/// post): only its scheme and host are shown. Its body may carry a service's key: hidden whole
42/// (Codex's review of M4.13a).
43fn mask_channels(value: &mut Value) {
44    let Some(channels) = value
45        .pointer_mut("/notifications/channels")
46        .and_then(Value::as_object_mut)
47    else {
48        return;
49    };
50    for channel in channels.values_mut() {
51        if let Some(Value::String(url)) = channel.get_mut("url") {
52            *url = origin(url);
53        }
54        if let Some(body) = channel.get_mut("body") {
55            *body = Value::String(MASK.to_owned());
56        }
57    }
58}
59
60/// `https://hooks.slack.com/****` for `https://hooks.slack.com/services/T/B/x`.
61fn origin(url: &str) -> String {
62    let (scheme, rest) = url.split_once("://").unwrap_or(("", url));
63    let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
64    // Userinfo is a secret too: what follows the last `@` is the host.
65    let host = host.rsplit_once('@').map_or(host, |(_, host)| host);
66    format!("{scheme}://{host}/{MASK}")
67}
68
69/// Masks every secret in `value`, in place.
70pub fn mask(value: &mut Value) {
71    mask_under(value, "");
72}
73
74/// Masks the secrets in `value`, a task's own data (its output), in place: every text as in a
75/// configuration, and a field whose name has a word naming a secret (`password`, `api_key`,
76/// `clientSecret`, `access_token`), by whole words, so `partition_key` or `sort_key` is
77/// shown: a task names its fields as it likes (decision 131).
78pub fn mask_data(value: &mut Value) {
79    match value {
80        Value::String(text) => *text = mask_text(text),
81        Value::Array(items) => items.iter_mut().for_each(mask_data),
82        Value::Object(fields) => {
83            for (name, field) in fields.iter_mut() {
84                let empty = field.is_null() || field.as_str().is_some_and(str::is_empty);
85                if !empty && names_secret_in_words(name) {
86                    *field = Value::String(MASK.to_owned());
87                } else {
88                    mask_data(field);
89                }
90            }
91            mask_keys(fields);
92        }
93        Value::Null | Value::Bool(_) | Value::Number(_) => {}
94    }
95}
96
97/// Masks each of `fields`' names as a text (a task may key its output by an address with
98/// its password). Two names masked alike stay apart: the second is `<name> (2)`, and so on.
99fn mask_keys(fields: &mut serde_json::Map<String, Value>) {
100    if !fields.keys().any(|name| mask_text(name) != *name) {
101        return;
102    }
103    let mut masked = serde_json::Map::new();
104    for (name, field) in std::mem::take(fields) {
105        let shown = mask_text(&name);
106        let mut unique = shown.clone();
107        let mut n = 1;
108        while masked.contains_key(&unique) {
109            n += 1;
110            unique = format!("{shown} ({n})");
111        }
112        masked.insert(unique, field);
113    }
114    *fields = masked;
115}
116
117/// Whether a word of `name` names a secret: its words split at anything but a letter or a
118/// digit, before an upper-case letter following a lower-case one or a digit (`apiKey`: `api`,
119/// `key`), and before the last of a run of upper-case letters followed by a lower-case one
120/// (`HTTPPassword`: `http`, `password`; `AWSAccessKeyId`: `aws`, `access`, `key`, `id`).
121#[must_use]
122pub fn names_secret_in_words(name: &str) -> bool {
123    let chars: Vec<char> = name.chars().collect();
124    let mut words: Vec<String> = Vec::new();
125    let mut word = String::new();
126    for (at, &c) in chars.iter().enumerate() {
127        if !c.is_alphanumeric() {
128            words.push(std::mem::take(&mut word));
129            continue;
130        }
131        let previous = at.checked_sub(1).map(|p| chars[p]);
132        let next_lower = chars.get(at + 1).is_some_and(|n| n.is_lowercase());
133        let starts_word = c.is_uppercase()
134            && previous.is_some_and(|p| {
135                p.is_lowercase() || p.is_ascii_digit() || (p.is_uppercase() && next_lower)
136            });
137        if starts_word {
138            words.push(std::mem::take(&mut word));
139        }
140        word.extend(c.to_lowercase());
141    }
142    words.push(word);
143    words.retain(|w| !w.is_empty());
144    let alone = [
145        "password",
146        "passwords",
147        "passwd",
148        "pwd",
149        "passphrase",
150        "secret",
151        "secrets",
152        "token",
153        "tokens",
154        "credential",
155        "credentials",
156        "apikey",
157        "privatekey",
158        "accesskey",
159        "secretkey",
160    ];
161    words.iter().any(|w| alone.contains(&w.as_str()))
162        || words.windows(2).any(|pair| {
163            pair[1] == "key" && matches!(pair[0].as_str(), "api" | "private" | "access" | "secret")
164        })
165}
166
167/// `text` masked; a URL as its client reads it, when that hides more. A URL parser drops tabs
168/// and line breaks (sqlx's: `pass\nword=\thunter2` is `password=hunter2`, `postgres:\n//`
169/// is `postgres://`; B216's reviews), so read without them its password's name and value are
170/// each one token. Only one URL is read so (no spaces, a scheme first); other text keeps its
171/// lines, where a line break ends a token.
172pub(crate) fn mask_url(text: &str) -> String {
173    let read = url_as_read(text);
174    if read.len() != text.len() && looks_like_url(&read) {
175        let masked = mask_text(&read);
176        if masked != read {
177            return masked;
178        }
179    }
180    mask_text(text)
181}
182
183/// `url` without the tabs and line breaks a URL parser drops.
184pub(crate) fn url_as_read(url: &str) -> String {
185    url.chars()
186        .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
187        .collect()
188}
189
190/// Whether `text` is one URL: a scheme, `://`, and no whitespace.
191fn looks_like_url(text: &str) -> bool {
192    text.split_once("://").is_some_and(|(scheme, _)| {
193        scheme.starts_with(|c: char| c.is_ascii_alphabetic())
194            && scheme
195                .chars()
196                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
197    }) && !text.contains(char::is_whitespace)
198}
199
200/// Masks `value`, the field of the table named `table` (`""`: none).
201fn mask_under(value: &mut Value, table: &str) {
202    match value {
203        Value::String(text) => *text = mask_url(text),
204        Value::Array(items) => items.iter_mut().for_each(|item| mask_under(item, table)),
205        Value::Object(fields) => {
206            for (name, field) in fields.iter_mut() {
207                if holds_secret(table, name, field) {
208                    *field = Value::String(MASK.to_owned());
209                } else {
210                    mask_under(field, name);
211                }
212            }
213            mask_keys(fields);
214        }
215        Value::Null | Value::Bool(_) | Value::Number(_) => {}
216    }
217}
218
219/// Whether the setting `name` of the table `table` holds a secret as `value` (not a file,
220/// path or header naming one; nothing to hide in an empty or unset one).
221fn holds_secret(table: &str, name: &str, value: &Value) -> bool {
222    let empty = match value {
223        Value::Null => true,
224        Value::String(text) => text.is_empty(),
225        _ => false,
226    };
227    if empty {
228        return false;
229    }
230    let name = compact(name);
231    let points_elsewhere = ["file", "files", "path", "paths", "dir", "header", "env"]
232        .iter()
233        .any(|end| name.ends_with(end));
234    if points_elsewhere {
235        return false;
236    }
237    // `[tls] key`: a path to the key (schedr's setting), shown. Elsewhere a `key` holding a
238    // `/` may be a secret (Base64).
239    if name == "key" {
240        return !(table == "tls" && value.as_str().is_some_and(looks_like_path));
241    }
242    names_secret(&name)
243}
244
245/// `name` lowercased, without `_`, `-`, `.` and spaces.
246fn compact(name: &str) -> String {
247    name.chars()
248        .filter(|c| !matches!(c, '_' | '-' | '.' | ' '))
249        .flat_map(char::to_lowercase)
250        .collect()
251}
252
253/// Whether a compacted name names a secret.
254fn names_secret(name: &str) -> bool {
255    [
256        "password",
257        "passwd",
258        "pwd",
259        "secret",
260        "token",
261        "credential",
262        "apikey",
263        "privatekey",
264        "accesskey",
265    ]
266    .iter()
267    .any(|word| name.contains(word))
268        || name == "key"
269        || (name.len() > 3 && name.ends_with("key"))
270}
271
272fn looks_like_path(text: &str) -> bool {
273    text.contains('/')
274        || text.contains('\\')
275        || std::path::Path::new(text)
276            .extension()
277            .is_some_and(|ext| ext.eq_ignore_ascii_case("pem") || ext.eq_ignore_ascii_case("key"))
278}
279
280/// `text` with every secret in it masked: passwords before `@`, and values after a name
281/// naming a secret (see the module documentation). Its time grows with the text's length,
282/// never faster.
283#[must_use]
284pub fn mask_text(text: &str) -> String {
285    mask_text_after("", text)
286}
287
288/// `text` masked as [`mask_text`] masks it, read after `before`, the text just before it,
289/// which is masked with it but not shown: a value begun in `before` (a quoted one going on
290/// over lines, a password whose name is there) is hidden in `text` too. A part of a log is
291/// masked so, the bytes before it as `before`.
292#[must_use]
293pub fn mask_text_after(before: &str, text: &str) -> String {
294    let chars: Vec<char> = before.chars().chain(text.chars()).collect();
295    let mut hidden = vec![false; chars.len()];
296    hide_passwords(&chars, &mut hidden);
297    for at in 0..chars.len() {
298        // A `=` inside a value already hidden is part of it.
299        if matches!(chars[at], '=' | ':') && !hidden[at] {
300            hide_value_after(&chars, at, &mut hidden);
301        }
302    }
303    let skip = before.chars().count();
304    let mut out = String::with_capacity(text.len());
305    let mut in_mask = false;
306    for (c, hide) in chars.iter().zip(&hidden).skip(skip) {
307        if *hide {
308            if !in_mask {
309                out.push_str(MASK);
310                in_mask = true;
311            }
312        } else {
313            out.push(*c);
314            in_mask = false;
315        }
316    }
317    out
318}
319
320/// Where a token ends: no password or value runs past it. Not `'`, `(` or `)`, which a
321/// password may hold.
322fn ends_token(c: char) -> bool {
323    c.is_whitespace() || matches!(c, '"' | '<' | '>' | '`')
324}
325
326/// Hides every password before `@`. A text's tokens are split at each `://` into user infos'
327/// segments; in a segment with an `@`, everything from its first `:` to its last `@` is
328/// hidden (a password may hold `@`, `:`, `/`, `,`; a segment holding two user infos without
329/// a scheme is hidden from the first one's password to the second one's host).
330fn hide_passwords(chars: &[char], hidden: &mut [bool]) {
331    let ahead = at_ahead(chars);
332    let mut start = 0;
333    let mut colon: Option<usize> = None;
334    let mut last_at: Option<usize> = None;
335    let mut i = 0;
336    while i < chars.len() {
337        let c = chars[i];
338        let scheme_end =
339            c == ':' && chars.get(i + 1) == Some(&'/') && chars.get(i + 2) == Some(&'/');
340        let network_path = c == '/' && chars.get(i + 1) == Some(&'/') && i == start;
341        // A `"` in a password (after its `:`, an `@` still to come in the token, whether one
342        // came before it or not) is the password's, not the end of a quoted value (B202).
343        let in_password = c == '"' && colon.is_some() && ahead[i];
344        if (ends_token(c) && !in_password) || scheme_end || network_path {
345            end_segment(colon, last_at, hidden);
346            (colon, last_at) = (None, None);
347            i += if scheme_end {
348                3
349            } else if network_path {
350                2
351            } else {
352                1
353            };
354            start = i;
355            continue;
356        }
357        match c {
358            ':' if colon.is_none() => colon = Some(i),
359            '@' => last_at = Some(i),
360            _ => {}
361        }
362        i += 1;
363    }
364    end_segment(colon, last_at, hidden);
365}
366
367/// For each place, whether an `@` comes after it before the token ends at something other
368/// than `"`: one pass from the end, so masking stays linear however many quotes a text has.
369fn at_ahead(chars: &[char]) -> Vec<bool> {
370    let mut ahead = vec![false; chars.len()];
371    let mut seen = false;
372    for (i, c) in chars.iter().enumerate().rev() {
373        ahead[i] = seen;
374        if *c == '@' {
375            seen = true;
376        } else if *c != '"' && ends_token(*c) {
377            seen = false;
378        }
379    }
380    ahead
381}
382
383/// Hides a segment's password: from its first `:` to its last `@`.
384fn end_segment(colon: Option<usize>, last_at: Option<usize>, hidden: &mut [bool]) {
385    if let (Some(colon), Some(at)) = (colon, last_at)
386        && colon < at
387    {
388        hidden[colon + 1..at]
389            .iter_mut()
390            .for_each(|flag| *flag = true);
391    }
392}
393
394/// Hides the value after `=` or `:` (`at`) when the name before it names a secret: to the
395/// end of its token (or `&`, `;`, `#` in a query), or its closing quote (a `\` escaping the
396/// next character).
397fn hide_value_after(chars: &[char], at: usize, hidden: &mut [bool]) {
398    // The name: letters, digits, `_ - . %` right before (a quote and spaces allowed between).
399    let mut end = at;
400    while end > 0 && chars[end - 1] == ' ' {
401        end -= 1;
402    }
403    if end > 0 && matches!(chars[end - 1], '"' | '\'') {
404        end -= 1;
405    }
406    let name_char = |c: char| c.is_alphanumeric() || matches!(c, '_' | '-' | '.' | '%');
407    let mut start = end;
408    while start > 0 && name_char(chars[start - 1]) {
409        start -= 1;
410    }
411    // Also read across tabs, anywhere in it and before the `=`, as a URL parser drops them
412    // (`pass<TAB><TAB>word=`, `password<TAB>=`: B203, B216); either reading naming a secret
413    // hides the value. Not across line breaks: in text they end a line (`invalid password` on
414    // one, `status=denied` on the next); a configuration's URL has them dropped first.
415    let mut across = end;
416    while across > 0 && (name_char(chars[across - 1]) || chars[across - 1] == '\t') {
417        across -= 1;
418    }
419    if across == end {
420        return;
421    }
422    let names = |from: usize| {
423        let name: String = chars[from..end].iter().collect();
424        names_secret(&compact(&percent_decoded(&name)))
425    };
426    let secret = (start < end && names(start)) || (across < start && names(across));
427    if !secret {
428        return;
429    }
430    // A URL's scheme (`token://…`) isn't a value: its user info is masked on its own.
431    if chars[at] == ':' && chars.get(at + 1) == Some(&'/') {
432        return;
433    }
434    let mut from = at + 1;
435    while from < chars.len() && chars[from] == ' ' {
436        from += 1;
437    }
438    // An OS error after a file's name (`…/caching_sha2_password.so: No such file or
439    // directory`) is no value: no secret reads so (B161). Anything else stays hidden, a file
440    // named after a secret too (`/run/secrets/api_key.txt: …`).
441    if chars[at] == ':' && starts_os_error(&chars[from..]) {
442        return;
443    }
444    let quote = chars.get(from).copied().filter(|c| matches!(c, '"' | '\''));
445    if quote.is_some() {
446        from += 1;
447    }
448    let mut to = from;
449    while to < chars.len() {
450        let c = chars[to];
451        let ends = match quote {
452            Some(_) if c == '\\' => {
453                to += 2;
454                continue;
455            }
456            Some(q) => c == q,
457            None => ends_token(c) || matches!(c, '&' | ';' | '#'),
458        };
459        if ends {
460            break;
461        }
462        to += 1;
463    }
464    let to = to.min(chars.len());
465    hidden[from..to].iter_mut().for_each(|flag| *flag = true);
466}
467
468/// Whether `text` starts with one of the C library's file errors, as `strerror` writes them.
469fn starts_os_error(text: &[char]) -> bool {
470    const ERRORS: [&str; 6] = [
471        "No such file or directory",
472        "Permission denied",
473        "Is a directory",
474        "Not a directory",
475        "cannot open shared object file",
476        "File exists",
477    ];
478    ERRORS.iter().any(|error| {
479        let error: Vec<char> = error.chars().collect();
480        text.starts_with(&error)
481    })
482}
483
484/// `text` with its `%XX` escapes decoded (a bad one kept as it is), its tabs and line
485/// breaks dropped.
486pub(crate) fn percent_decoded(text: &str) -> String {
487    // Tabs and line breaks dropped first, as a URL parser drops them (sqlx's does: B203's
488    // review, `pass<TAB>word=` is its `password`).
489    let text: String = text
490        .chars()
491        .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
492        .collect();
493    let bytes = text.as_bytes();
494    let mut out = Vec::with_capacity(bytes.len());
495    let mut i = 0;
496    while i < bytes.len() {
497        if bytes[i] == b'%'
498            && let Some(hex) = text.get(i + 1..i + 3)
499            && let Ok(byte) = u8::from_str_radix(hex, 16)
500        {
501            out.push(byte);
502            i += 3;
503        } else {
504            out.push(bytes[i]);
505            i += 1;
506        }
507    }
508    String::from_utf8_lossy(&out).into_owned()
509}