Skip to main content

schedr_agent/
mask.rs

1//! Masking secret values in a task's log and output (decision 167): each value the attempt
2//! fetched, written `****`.
3//!
4//! A value is masked as it is, as JSON escapes it (`"` and `\` in a value, a JSON log line;
5//! also with every non-ASCII character as `\uXXXX`, as Python's `json.dumps` writes it), as
6//! Python's `repr` quotes it (an exception's message), and line by line when it spans several
7//! lines; a form shorter than `min_mask_length` isn't (masking `1` would mangle the log). In a
8//! stored output a number equal to a value is masked too. Streams are masked as they are
9//! copied, across the chunks they are read in: only bytes that could start a value are held
10//! back, until the next chunk or the end.
11//!
12//! Masking guards against a value shown by accident: a task holding a value can always
13//! write it in a form no mask knows (split between stdout and stderr, encoded, reversed).
14
15use std::fmt::Write as _;
16use std::sync::{Mutex, PoisonError};
17
18use schedr_model::Encoding;
19use serde_json::Value;
20
21#[cfg(test)]
22mod tests;
23
24/// The mask a process's output goes through: none, or an attempt's values (compared by
25/// identity, so a [`crate::process::ProcessSpec`] stays comparable).
26#[derive(Debug, Clone, Default)]
27pub struct Mask(pub Option<std::sync::Arc<MaskSet>>);
28
29impl PartialEq for Mask {
30    fn eq(&self, other: &Self) -> bool {
31        match (&self.0, &other.0) {
32            (Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b),
33            (None, None) => true,
34            _ => false,
35        }
36    }
37}
38
39impl Eq for Mask {}
40
41/// Labels and values, never shown by `Debug`.
42#[derive(Default)]
43struct Values(Vec<(String, String)>);
44
45impl std::fmt::Debug for Values {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(f, "{} values", self.0.len())
48    }
49}
50
51/// What a masked value is written as.
52pub const MASK: &str = "****";
53
54/// The values masked for one attempt, and how often each was masked.
55#[derive(Debug)]
56pub struct MaskSet {
57    min_length: usize,
58    inner: Mutex<Inner>,
59}
60
61impl MaskSet {
62    /// Masks in `other` too whatever is masked here, now and from now on: output shared by
63    /// several attempts can't be told apart, so it masks them all.
64    pub fn also_in(&self, other: std::sync::Arc<Self>) {
65        let mut inner = self.inner.lock().unwrap_or_else(PoisonError::into_inner);
66        for (label, value) in &inner.values.0 {
67            other.add(label, value);
68        }
69        inner.also.push(other);
70    }
71}
72
73#[derive(Debug, Default)]
74struct Inner {
75    /// Each form and the secret it comes from (an index into `labels`), longest first.
76    forms: Vec<(Vec<u8>, usize)>,
77    /// For each first byte, the forms starting with it (indexes into `forms`, longest
78    /// first): a byte no form starts with is passed on at once.
79    by_first: Vec<Vec<usize>>,
80    /// The secrets, as written in Python (never their values).
81    labels: Vec<String>,
82    /// How many times each secret was masked.
83    counts: Vec<u64>,
84    /// The values added, for [`MaskSet::also_in`].
85    values: Values,
86    /// The sets that mask these too.
87    also: Vec<std::sync::Arc<MaskSet>>,
88}
89
90impl MaskSet {
91    /// No values; forms shorter than `min_length` characters are never masked.
92    #[must_use]
93    pub fn new(min_length: usize) -> Self {
94        Self {
95            min_length,
96            inner: Mutex::default(),
97        }
98    }
99
100    /// Masks `value` of the secret `label` from now on. Returns `false` when it is too short
101    /// to be masked (nothing is added).
102    pub fn add(&self, label: &str, value: &str) -> bool {
103        let min = self.min_length.max(1);
104        if value.chars().count() < min {
105            return false;
106        }
107        let mut forms = vec![
108            value.to_owned(),
109            json_escaped(value, false),
110            json_escaped(value, true),
111            python_repr_escaped(value),
112            // As a URL's value is written (decision 188): a driver's error may quote the URL.
113            Encoding::Url.apply(value),
114        ];
115        // Single-quoted for a shell, `'` written `'\''` (`task-ctx connection --env`).
116        let quoted: Vec<String> = forms
117            .iter()
118            .filter(|form| form.contains('\''))
119            .map(|form| form.replace('\'', "'\\''"))
120            .collect();
121        forms.extend(quoted);
122        if value.contains('\n') {
123            forms.extend(
124                value
125                    .split('\n')
126                    .map(|line| line.trim_end_matches('\r'))
127                    .filter(|line| line.chars().count() >= min)
128                    .map(str::to_owned),
129            );
130        }
131        let mut inner = self.inner.lock().unwrap_or_else(PoisonError::into_inner);
132        let index = if let Some(index) = inner.labels.iter().position(|l| l == label) {
133            index
134        } else {
135            inner.labels.push(label.to_owned());
136            inner.counts.push(0);
137            inner.labels.len() - 1
138        };
139        for form in forms {
140            let form = form.into_bytes();
141            if !form.is_empty() && !inner.forms.iter().any(|(f, _)| *f == form) {
142                inner.forms.push((form, index));
143            }
144        }
145        inner.index();
146        inner.values.0.push((label.to_owned(), value.to_owned()));
147        let also = inner.also.clone();
148        drop(inner);
149        for other in also {
150            other.add(label, value);
151        }
152        true
153    }
154
155    /// Whether nothing is masked.
156    #[must_use]
157    pub fn is_empty(&self) -> bool {
158        self.inner
159            .lock()
160            .unwrap_or_else(PoisonError::into_inner)
161            .forms
162            .is_empty()
163    }
164
165    /// `bytes` with every value masked.
166    #[must_use]
167    pub fn mask(&self, bytes: &[u8]) -> Vec<u8> {
168        let mut inner = self.inner.lock().unwrap_or_else(PoisonError::into_inner);
169        inner.scan(bytes, false).0
170    }
171
172    /// `text` with every value masked.
173    #[must_use]
174    pub fn mask_text(&self, text: &str) -> String {
175        let masked = self.mask(text.as_bytes());
176        // Only whole values (valid UTF-8 themselves) are replaced, by ASCII: still UTF-8.
177        String::from_utf8(masked)
178            .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
179    }
180
181    /// A JSON value with every string, object key and number masked. A masked number becomes
182    /// the text it is masked in; two keys masked alike stay apart (`**** (2)`, and so on).
183    #[must_use]
184    pub fn mask_json(&self, value: &Value) -> Value {
185        if self.is_empty() {
186            return value.clone();
187        }
188        match value {
189            Value::String(text) => Value::String(self.mask_text(text)),
190            // A value turned into a number (`int(password)`): written out, it is the value.
191            Value::Number(number) => {
192                let text = number.to_string();
193                let masked = self.mask_text(&text);
194                if masked == text {
195                    value.clone()
196                } else {
197                    Value::String(masked)
198                }
199            }
200            Value::Array(items) => Value::Array(items.iter().map(|v| self.mask_json(v)).collect()),
201            Value::Object(entries) => {
202                let mut masked = serde_json::Map::new();
203                for (key, field) in entries {
204                    let shown = self.mask_text(key);
205                    let mut unique = shown.clone();
206                    let mut n = 1;
207                    // Nor taking the name of a key that wasn't masked.
208                    while masked.contains_key(&unique)
209                        || (unique != *key && entries.contains_key(&unique))
210                    {
211                        n += 1;
212                        unique = format!("{shown} ({n})");
213                    }
214                    masked.insert(unique, self.mask_json(field));
215                }
216                Value::Object(masked)
217            }
218            Value::Null | Value::Bool(_) => value.clone(),
219        }
220    }
221
222    /// Each secret masked at least once, with how many times.
223    #[must_use]
224    pub fn counts(&self) -> Vec<(String, u64)> {
225        let inner = self.inner.lock().unwrap_or_else(PoisonError::into_inner);
226        inner
227            .labels
228            .iter()
229            .zip(&inner.counts)
230            .filter(|(_, count)| **count > 0)
231            .map(|(label, count)| (label.clone(), *count))
232            .collect()
233    }
234
235    /// A masking stream: what it is fed comes out masked, held back only where a value may
236    /// continue in the next chunk.
237    #[must_use]
238    pub fn stream(&self) -> MaskStream<'_> {
239        MaskStream {
240            set: self,
241            pending: Vec::new(),
242        }
243    }
244}
245
246impl Inner {
247    /// Sorts the forms longest first and indexes them by their first byte.
248    fn index(&mut self) {
249        self.forms
250            .sort_by_key(|(form, _)| std::cmp::Reverse(form.len()));
251        let mut by_first = vec![Vec::new(); 256];
252        for (index, (form, _)) in self.forms.iter().enumerate() {
253            by_first[usize::from(form[0])].push(index);
254        }
255        self.by_first = by_first;
256    }
257
258    /// `bytes` masked from the start, and how many of them it took. With `partial`, it stops
259    /// at the first place where a value may begin and continue past the end (the rest is
260    /// held for the next chunk); a value that may grow into a longer one waits too.
261    fn scan(&mut self, bytes: &[u8], partial: bool) -> (Vec<u8>, usize) {
262        if self.forms.is_empty() {
263            return (bytes.to_vec(), bytes.len());
264        }
265        let mut out = Vec::with_capacity(bytes.len());
266        let mut at = 0;
267        'scan: while at < bytes.len() {
268            let candidates = &self.by_first[usize::from(bytes[at])];
269            if candidates.is_empty() {
270                out.push(bytes[at]);
271                at += 1;
272                continue;
273            }
274            let rest = &bytes[at..];
275            if partial
276                && candidates.iter().any(|&i| {
277                    let form = &self.forms[i].0;
278                    form.len() > rest.len() && form.starts_with(rest)
279                })
280            {
281                break;
282            }
283            for &i in candidates {
284                let (form, secret) = &self.forms[i];
285                if rest.starts_with(form) {
286                    out.extend_from_slice(MASK.as_bytes());
287                    self.counts[*secret] += 1;
288                    at += form.len();
289                    continue 'scan;
290                }
291            }
292            out.push(bytes[at]);
293            at += 1;
294        }
295        (out, at)
296    }
297}
298
299/// A stream being masked (one per pipe: stdout and stderr each have their own).
300#[derive(Debug)]
301pub struct MaskStream<'a> {
302    set: &'a MaskSet,
303    pending: Vec<u8>,
304}
305
306impl MaskStream<'_> {
307    /// The next chunk, masked; the bytes that may begin a value are kept for the next one.
308    pub fn push(&mut self, chunk: &[u8]) -> Vec<u8> {
309        self.pending.extend_from_slice(chunk);
310        let mut inner = self
311            .set
312            .inner
313            .lock()
314            .unwrap_or_else(PoisonError::into_inner);
315        let (masked, taken) = inner.scan(&self.pending, true);
316        self.pending.drain(..taken);
317        masked
318    }
319
320    /// What is left, masked: the stream ended.
321    pub fn finish(&mut self) -> Vec<u8> {
322        let rest = std::mem::take(&mut self.pending);
323        self.set.mask(&rest)
324    }
325}
326
327/// `value` inside a JSON string, without its quotes; with `ascii`, every non-ASCII character
328/// as `\uXXXX` (a surrogate pair beyond the BMP), as Python's `json.dumps` writes it.
329fn json_escaped(value: &str, ascii: bool) -> String {
330    let quoted = serde_json::to_string(value).unwrap_or_default();
331    let inner = quoted
332        .strip_prefix('"')
333        .and_then(|q| q.strip_suffix('"'))
334        .unwrap_or(&quoted);
335    if !ascii {
336        return inner.to_owned();
337    }
338    let mut out = String::with_capacity(inner.len());
339    for c in inner.chars() {
340        if c.is_ascii() {
341            out.push(c);
342        } else {
343            let mut units = [0; 2];
344            for unit in c.encode_utf16(&mut units) {
345                let _ = write!(out, "\\u{unit:04x}");
346            }
347        }
348    }
349    out
350}
351
352/// `value` inside Python's `repr` of it, without its quotes (an exception's message is often
353/// the `repr` of its argument: `KeyError('...')`).
354fn python_repr_escaped(value: &str) -> String {
355    let quote = if value.contains('\'') && !value.contains('"') {
356        '"'
357    } else {
358        '\''
359    };
360    let mut out = String::with_capacity(value.len());
361    for c in value.chars() {
362        match c {
363            '\\' => out.push_str("\\\\"),
364            '\n' => out.push_str("\\n"),
365            '\r' => out.push_str("\\r"),
366            '\t' => out.push_str("\\t"),
367            c if c == quote => {
368                out.push('\\');
369                out.push(c);
370            }
371            c if python_printable(c) => out.push(c),
372            c => {
373                let code = u32::from(c);
374                let _ = match code {
375                    ..=0xff => write!(out, "\\x{code:02x}"),
376                    0x100..=0xffff => write!(out, "\\u{code:04x}"),
377                    _ => write!(out, "\\U{code:08x}"),
378                };
379            }
380        }
381    }
382    out
383}
384
385/// Python's `str.isprintable` for one character, which decides what its `repr` escapes:
386/// every category but the controls, formats, surrogates, private use, unassigned, and the
387/// separators other than the ASCII space.
388fn python_printable(c: char) -> bool {
389    use unicode_general_category::{GeneralCategory as G, get_general_category};
390    c == ' '
391        || !matches!(
392            get_general_category(c),
393            G::Control
394                | G::Format
395                | G::Surrogate
396                | G::PrivateUse
397                | G::Unassigned
398                | G::LineSeparator
399                | G::ParagraphSeparator
400                | G::SpaceSeparator
401        )
402}