Skip to main content

lean_ctx/core/redaction/
structured.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Structural masking of JSON that a released document carries: the whole
3//! value of a member with a credential's name, at any depth, whatever its
4//! shape.
5//!
6//! The text rules of `super::redaction_rules` read a secret by the name in
7//! front of it (`"token":"…"`), so they only see a STRING right after the
8//! name. A secret one level further down (`{"token":["S"]}`,
9//! `{"auth":{"value":"S"}}`) or kept as a number or a boolean passed every
10//! text rule unmasked. Here a member whose name reads as a credential
11//! ([`is_secret_key`]) has its whole value replaced by [`SECRET_MEMBER_MARKER`]:
12//! arrays, objects, numbers and booleans alike, the names inside included.
13//! Only `null`, `""` and a value that is already a mask stay as they are
14//! (allowlist; every other shape is masked).
15//!
16//! A string value at any depth that is itself a JSON object or array (a fact
17//! whose value is a serialized document) is masked the same way, and the
18//! masked JSON stands in the string. The value detectors (provider tokens,
19//! key/value rules) still run on every string leaf where the caller releases
20//! the document; this pass only adds what they cannot see.
21
22use serde_json::Value;
23
24/// What stands in place of the whole value of a credential member. It starts
25/// with `[REDACTED` like every marker of the text rules, so callers that
26/// locate masked spans by that prefix see it as a mask.
27pub const SECRET_MEMBER_MARKER: &str = "[REDACTED:Secret member]";
28
29/// Nesting deeper than this is not inspected: the document is refused.
30const MAX_DEPTH: usize = 64;
31
32/// Embedded JSON candidates in free text that fail to parse before the scan
33/// gives up and refuses the text (bounds the work on hostile input).
34const MAX_FAILED_CANDIDATES: usize = 4096;
35
36/// Why a text could not be inspected; the caller withholds it.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Uninspectable {
39    /// Nested deeper than the inspection depth.
40    TooDeep,
41    /// Too many JSON-like fragments that do not parse.
42    TooManyFragments,
43}
44
45/// A masked text and the masked string values that are worth looking for
46/// elsewhere in the delivered text (benign literals such as `none` are masked
47/// but not listed: finding them elsewhere proves nothing).
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct Masked {
50    pub text: String,
51    pub originals: Vec<String>,
52}
53
54impl Masked {
55    /// Whether a masked value of four or more characters still appears in the
56    /// masked text, as written or as JSON escapes it (a copy under another
57    /// name, or inside another value). Such a text must be withheld.
58    pub fn still_carries_an_original(&self) -> bool {
59        self.originals
60            .iter()
61            .filter(|original| original.chars().count() >= 4)
62            .any(|original| {
63                let escaped = serde_json::to_string(original).unwrap_or_default();
64                let escaped = escaped
65                    .strip_prefix('"')
66                    .and_then(|inner| inner.strip_suffix('"'))
67                    .unwrap_or(&escaped);
68                self.text.contains(original.as_str()) || self.text.contains(escaped)
69            })
70    }
71}
72
73/// Credential words that make a member name secret when they END it.
74const SECRET_LAST_WORDS: &[&str] = &[
75    "password",
76    "passwd",
77    "pwd",
78    "passphrase",
79    "passcode",
80    "secret",
81    "secrets",
82    "token",
83    "credential",
84    "credentials",
85    "auth",
86    "authorization",
87    "bearer",
88    "cookie",
89    "apikey",
90    "privatekey",
91    "secretkey",
92    "accesskey",
93];
94
95/// Qualifiers that make a final `key` a credential (`api_key`,
96/// `private_key`). A bare `key` (a knowledge fact's slug) and a
97/// `public_key` stay readable.
98const SECRET_KEY_QUALIFIERS: &[&str] = &[
99    "api",
100    "access",
101    "secret",
102    "private",
103    "signing",
104    "encryption",
105    "master",
106    "client",
107    "session",
108];
109
110/// The words of a member name: split at every non-alphanumeric character and
111/// at camelCase boundaries (`accessToken`, `APIKey`, `x-api-key`), lowercased.
112fn name_words(name: &str) -> Vec<String> {
113    let chars: Vec<char> = name.chars().collect();
114    let mut words = Vec::new();
115    let mut current = String::new();
116    for (index, &ch) in chars.iter().enumerate() {
117        if !ch.is_alphanumeric() {
118            if !current.is_empty() {
119                words.push(std::mem::take(&mut current));
120            }
121            continue;
122        }
123        if ch.is_uppercase() && !current.is_empty() {
124            let previous = chars[index - 1];
125            let next_is_lower = chars.get(index + 1).is_some_and(|c| c.is_lowercase());
126            if previous.is_lowercase()
127                || previous.is_ascii_digit()
128                || (previous.is_uppercase() && next_is_lower)
129            {
130                words.push(std::mem::take(&mut current));
131            }
132        }
133        current.extend(ch.to_lowercase());
134    }
135    if !current.is_empty() {
136        words.push(current);
137    }
138    words
139}
140
141/// Whether a JSON member name reads as a credential: its last word is one
142/// (`token`, `password`, `auth`, `client_secret`, `accessToken`), or it ends
143/// in `key` with a credential qualifier (`api_key`, `private_key`). Counts
144/// and metadata (`tokens`, `max_tokens`, `token_type`, `secret_count`), a bare
145/// `key` and `public_key` are not.
146pub fn is_secret_key(name: &str) -> bool {
147    let words = name_words(name);
148    let Some(last) = words.last() else {
149        return false;
150    };
151    if SECRET_LAST_WORDS.contains(&last.as_str()) {
152        return true;
153    }
154    last == "key"
155        && words.len() >= 2
156        && SECRET_KEY_QUALIFIERS.contains(&words[words.len() - 2].as_str())
157}
158
159/// A value under a credential name that is left as it is: nothing in it can
160/// be a secret.
161fn is_empty_or_mask(value: &Value) -> bool {
162    match value {
163        Value::Null => true,
164        Value::String(text) => {
165            text.is_empty()
166                || (text.starts_with("[REDACTED") && text.ends_with(']') && !text.contains('\n'))
167        }
168        _ => false,
169    }
170}
171
172/// Collect the string leaves of a masked subtree that are worth looking for
173/// elsewhere.
174fn collect_originals(value: &Value, originals: &mut Vec<String>) {
175    match value {
176        Value::String(text) => {
177            if !super::is_benign_quoted_value(text) {
178                originals.push(text.clone());
179            }
180        }
181        Value::Array(items) => items
182            .iter()
183            .for_each(|item| collect_originals(item, originals)),
184        Value::Object(map) => map
185            .values()
186            .for_each(|item| collect_originals(item, originals)),
187        Value::Null | Value::Bool(_) | Value::Number(_) => {}
188    }
189}
190
191/// Mask, in place, the whole value of every member of `value` whose name is a
192/// credential ([`is_secret_key`]), at any depth, and every JSON document kept
193/// as a string value. Returns whether anything changed; the masked string
194/// values worth looking for elsewhere are appended to `originals`.
195pub fn mask_secret_members(
196    value: &mut Value,
197    originals: &mut Vec<String>,
198) -> Result<bool, Uninspectable> {
199    mask_value(value, 0, originals)
200}
201
202fn mask_value(
203    value: &mut Value,
204    depth: usize,
205    originals: &mut Vec<String>,
206) -> Result<bool, Uninspectable> {
207    if depth > MAX_DEPTH {
208        return Err(Uninspectable::TooDeep);
209    }
210    match value {
211        Value::Object(map) => {
212            let mut changed = false;
213            for (name, item) in map.iter_mut() {
214                if is_secret_key(name) {
215                    if !is_empty_or_mask(item) {
216                        collect_originals(item, originals);
217                        *item = Value::String(SECRET_MEMBER_MARKER.to_owned());
218                        changed = true;
219                    }
220                } else {
221                    changed |= mask_value(item, depth + 1, originals)?;
222                }
223            }
224            Ok(changed)
225        }
226        Value::Array(items) => {
227            let mut changed = false;
228            for item in items {
229                changed |= mask_value(item, depth + 1, originals)?;
230            }
231            Ok(changed)
232        }
233        Value::String(text) => {
234            if let Some(mut inner) = embedded_document(text) {
235                if !mask_value(&mut inner, depth + 1, originals)? {
236                    return Ok(false);
237                }
238                *text = inner.to_string();
239                return Ok(true);
240            }
241            // JSON after other text in the value (`creds: {"token":["S"]}`)
242            // is masked where it stands, as it is in free text.
243            match mask_embedded_json(text, depth + 1, originals)? {
244                Some(masked) => {
245                    *text = masked;
246                    Ok(true)
247                }
248                None => Ok(false),
249            }
250        }
251        Value::Null | Value::Bool(_) | Value::Number(_) => Ok(false),
252    }
253}
254
255/// The JSON object or array a string value holds as its whole text.
256fn embedded_document(text: &str) -> Option<Value> {
257    let trimmed = text.trim();
258    if !(trimmed.starts_with('{') || trimmed.starts_with('[')) {
259        return None;
260    }
261    serde_json::from_str::<Value>(trimmed)
262        .ok()
263        .filter(|value| value.is_object() || value.is_array())
264}
265
266/// [`mask_secret_members`] for a text: a text that is one JSON document is
267/// masked as a value and written back in its own layout (pretty when it
268/// spans lines); any other text has every embedded JSON object or array
269/// masked where it stands. `Ok(None)`: nothing to mask, the text keeps its
270/// bytes.
271pub fn mask_structured_text(text: &str) -> Result<Option<Masked>, Uninspectable> {
272    let mut originals = Vec::new();
273    if let Ok(mut value) = serde_json::from_str::<Value>(text) {
274        if !mask_secret_members(&mut value, &mut originals)? {
275            return Ok(None);
276        }
277        let serialized = if text.contains('\n') {
278            serde_json::to_string_pretty(&value)
279        } else {
280            serde_json::to_string(&value)
281        };
282        let mut masked = serialized.map_err(|_| Uninspectable::TooDeep)?;
283        if text.ends_with('\n') && !masked.ends_with('\n') {
284            masked.push('\n');
285        }
286        return Ok(Some(Masked {
287            text: masked,
288            originals,
289        }));
290    }
291    mask_embedded_json(text, 0, &mut originals)
292        .map(|masked| masked.map(|text| Masked { text, originals }))
293}
294
295/// Whether the byte at `at` may start an embedded JSON object or array worth
296/// parsing: `{` followed by a member name, or `[` followed by a container or
297/// a string.
298fn starts_candidate(bytes: &[u8], at: usize) -> bool {
299    let next = bytes[at + 1..]
300        .iter()
301        .copied()
302        .find(|b| !b.is_ascii_whitespace());
303    matches!(
304        (bytes[at], next),
305        (b'{', Some(b'"')) | (b'[', Some(b'{' | b'[' | b'"'))
306    )
307}
308
309/// Mask every JSON object or array embedded in `text` where it stands, at
310/// nesting `depth` (a text inside a string value counts the levels above it).
311fn mask_embedded_json(
312    text: &str,
313    depth: usize,
314    originals: &mut Vec<String>,
315) -> Result<Option<String>, Uninspectable> {
316    let bytes = text.as_bytes();
317    let mut out = String::new();
318    let mut copied = 0;
319    let mut at = 0;
320    let mut failed = 0usize;
321    let mut changed = false;
322    while at < bytes.len() {
323        if !matches!(bytes[at], b'{' | b'[') || !starts_candidate(bytes, at) {
324            at += 1;
325            continue;
326        }
327        let mut stream = serde_json::Deserializer::from_str(&text[at..]).into_iter::<Value>();
328        match stream.next() {
329            Some(Ok(mut value)) => {
330                let end = at + stream.byte_offset();
331                if mask_value(&mut value, depth, originals)? {
332                    out.push_str(&text[copied..at]);
333                    out.push_str(&value.to_string());
334                    copied = end;
335                    changed = true;
336                }
337                at = end;
338            }
339            Some(Err(error))
340                if error.classify() == serde_json::error::Category::Syntax
341                    && error.to_string().contains("recursion limit") =>
342            {
343                return Err(Uninspectable::TooDeep);
344            }
345            _ => {
346                failed += 1;
347                if failed > MAX_FAILED_CANDIDATES {
348                    return Err(Uninspectable::TooManyFragments);
349                }
350                at += 1;
351            }
352        }
353    }
354    if !changed {
355        return Ok(None);
356    }
357    out.push_str(&text[copied..]);
358    Ok(Some(out))
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364    use serde_json::json;
365
366    /// A credential-shaped value built at run time, so no fixture in the
367    /// repository looks like a real token to a secret scanner.
368    fn secret() -> String {
369        ["q7", "Zr", "Lm", "x2", "Vb", "8n", "Tk", "w4"].concat()
370    }
371
372    fn masked(value: Value) -> (Value, Vec<String>) {
373        let mut value = value;
374        let mut originals = Vec::new();
375        mask_secret_members(&mut value, &mut originals).expect("inspectable");
376        (value, originals)
377    }
378
379    #[test]
380    fn secret_names_are_recognized_and_metadata_names_are_not() {
381        for name in [
382            "token",
383            "password",
384            "auth",
385            "Authorization",
386            "client_secret",
387            "accessToken",
388            "refresh-token",
389            "APIKey",
390            "api_key",
391            "x-api-key",
392            "private_key",
393            "AWS_SECRET_ACCESS_KEY",
394            "db_password",
395            "secrets",
396            "credentials",
397        ] {
398            assert!(is_secret_key(name), "{name} must be secret");
399        }
400        for name in [
401            "key",
402            "public_key",
403            "signer_public_key",
404            "tokens",
405            "max_tokens",
406            "input_tokens",
407            "token_type",
408            "token_count",
409            "secret_count",
410            "author",
411            "oauth_provider",
412            "category",
413            "value",
414            "keys",
415        ] {
416            assert!(!is_secret_key(name), "{name} must stay readable");
417        }
418    }
419
420    #[test]
421    fn every_shape_under_a_secret_name_is_masked() {
422        let s = secret();
423        let (value, originals) = masked(json!({
424            "token": [s],
425            "auth": {"value": s},
426            "passcode": 1234,
427            "api_key": true,
428            "password": null,
429            "secret": "",
430        }));
431        assert_eq!(value["token"], SECRET_MEMBER_MARKER);
432        assert_eq!(value["auth"], SECRET_MEMBER_MARKER);
433        assert_eq!(value["passcode"], SECRET_MEMBER_MARKER);
434        assert_eq!(value["api_key"], SECRET_MEMBER_MARKER);
435        assert_eq!(value["password"], Value::Null);
436        assert_eq!(value["secret"], "");
437        assert!(originals.iter().all(|o| o == &s) && originals.len() == 2);
438        assert!(!value.to_string().contains(&s));
439    }
440
441    #[test]
442    fn deep_nesting_arrays_of_objects_and_embedded_documents_are_masked() {
443        let s = secret();
444        let embedded = json!({"nested": {"credentials": {"user": "u", "value": s}}}).to_string();
445        let (value, _) = masked(json!({
446            "a": {"b": {"c": {"d": [{"e": {"client_secret": {"x": [s]}}}]}}},
447            "rows": [{"name": "one", "token": s}, {"name": "two", "token": [s, s]}],
448            "value": embedded,
449        }));
450        let text = value.to_string();
451        assert!(!text.contains(&s), "{text}");
452        assert_eq!(value["rows"][0]["name"], "one");
453        assert_eq!(value["rows"][1]["name"], "two");
454        assert!(value["value"].as_str().unwrap().contains("Secret member"));
455    }
456
457    #[test]
458    fn readable_documents_keep_their_bytes() {
459        let clean = r#"{"facts":[{"category":"auth","key":"token-type","value":"bearer, rotated daily","tokens":42,"public_key":"abc"}]}"#;
460        assert_eq!(mask_structured_text(clean), Ok(None));
461        let pretty =
462            serde_json::to_string_pretty(&serde_json::from_str::<Value>(clean).unwrap()).unwrap();
463        assert_eq!(mask_structured_text(&pretty), Ok(None));
464        assert_eq!(mask_structured_text("plain text {not json}"), Ok(None));
465    }
466
467    #[test]
468    fn json_embedded_in_free_text_is_masked_where_it_stands() {
469        let s = secret();
470        let text = format!(
471            "[auth] creds: {} (kept) and {{\"name\":\"ok\"}}",
472            json!({"auth": {"value": s}})
473        );
474        let out = mask_structured_text(&text).unwrap().expect("masked");
475        assert!(!out.text.contains(&s));
476        assert!(
477            out.text
478                .starts_with("[auth] creds: {\"auth\":\"[REDACTED:Secret member]\"}")
479        );
480        assert!(out.text.ends_with("(kept) and {\"name\":\"ok\"}"));
481        assert_eq!(out.originals, vec![s]);
482    }
483
484    /// !427 review B3: JSON after other text in a string value
485    /// (`"creds: {\"token\":[\"S\"]}"`) was released: only a value that is
486    /// a JSON document as a whole was inspected.
487    #[test]
488    fn json_after_other_text_in_a_string_value_is_masked() {
489        let s = secret();
490        let inner = format!("creds: {}", json!({"token": [s]}));
491        let (value, originals) = masked(json!([{"key": "c", "value": inner}]));
492        let text = value[0]["value"].as_str().expect("string");
493        assert!(!text.contains(&s), "{text}");
494        assert_eq!(text, "creds: {\"token\":\"[REDACTED:Secret member]\"}");
495        assert_eq!(value[0]["key"], "c");
496        assert_eq!(originals, vec![s.clone()]);
497        let document = json!([{"key": "c", "value": inner}]).to_string();
498        let out = mask_structured_text(&document).unwrap().expect("masked");
499        assert!(!out.text.contains(&s), "{}", out.text);
500        // The same text on its own (free text) is masked as well.
501        let out = mask_structured_text(&inner).unwrap().expect("masked");
502        assert!(!out.text.contains(&s), "{}", out.text);
503        // A readable value with braces keeps its bytes.
504        let clean = json!([{"value": "see {\"name\":\"ok\"} and [\"a\"]"}]).to_string();
505        assert_eq!(mask_structured_text(&clean), Ok(None));
506    }
507
508    #[test]
509    fn too_deep_documents_are_refused() {
510        let deep = format!("{}{}", "[".repeat(80), "]".repeat(80));
511        let mut value: Value = serde_json::from_str(&deep).unwrap();
512        assert_eq!(
513            mask_secret_members(&mut value, &mut Vec::new()),
514            Err(Uninspectable::TooDeep)
515        );
516    }
517}