Skip to main content

feldera_types/
secret_redaction.rs

1//! Redaction of referenced and declared credential values in diagnostics.
2//!
3//! Terms:
4//!
5//! - A reference names a secret in a configuration, such as
6//!   `${secret:kubernetes:pg/uri}`.
7//! - The value of a secret is its plaintext, which the pipeline reads from
8//!   the secret store.
9//! - The resolver replaces each reference in a configuration with its value.
10//! - The registry, [`SecretRedactor`], holds each resolved value with its
11//!   reference.
12//! - A declared credential is the value of a configuration field that the
13//!   schema of a connector marks as a credential. It can have no reference.
14//!
15//! The resolver registers each value it resolves. Error responses, connector
16//! error lists, the panic hook and the pipeline log pass through the
17//! registry, so a value that a message copies by mistake leaves the process
18//! as its reference. This is a safety net: code that builds a diagnostic
19//! must not rely on it.
20//!
21//! What replaces a registered value:
22//!
23//! | The text holds | It becomes |
24//! |---|---|
25//! | the value, as resolved or trimmed | the reference |
26//! | a form derived from the value: percent-encoded, percent-decoded, debug-escaped or JSON-escaped, or the password of a value that is a URL | `[REDACTED <reference>]` |
27//! | a declared credential with no reference, or a form derived from it | `[REDACTED]` |
28//!
29//! The registry is process-wide and never logged or serialized. A value
30//! registered twice keeps its first reference; references take precedence over
31//! supplemental credential markers. Unit tests share it, so a
32//! test registers a value that no other message can contain.
33
34use crate::json_strings::rewrite_json_strings;
35use aho_corasick::{AhoCorasick, MatchKind};
36use serde_json::Value;
37use std::borrow::Cow;
38use std::sync::{PoisonError, RwLock, TryLockError};
39use url::Url;
40
41/// Shortest value the registry redacts, measured once the value is trimmed.
42/// A shorter value, such as `5432` or `admin`, also occurs in ordinary text,
43/// so it is not registered. Neither is a derived form shorter than this.
44pub const MIN_REDACTED_LEN: usize = 8;
45
46#[derive(Clone)]
47enum Replacement {
48    Reference(String),
49    Credential,
50}
51
52impl Replacement {
53    fn text(&self) -> &str {
54        match self {
55            Self::Reference(text) => text,
56            Self::Credential => "[REDACTED]",
57        }
58    }
59}
60
61#[derive(Default)]
62struct Entries {
63    values: Vec<String>,
64    replacements: Vec<Replacement>,
65    /// Finds candidate values, preferring the longest match at each position.
66    automaton: Option<AhoCorasick>,
67}
68
69/// Registry of resolved secret values and the text that replaces each one.
70///
71/// All state is behind one lock: registration takes it for writing, redaction
72/// for reading, so both are safe from any thread.
73#[derive(Default)]
74pub struct SecretRedactor {
75    entries: RwLock<Entries>,
76}
77
78static GLOBAL: SecretRedactor = SecretRedactor::new();
79
80/// The registry of this process.
81pub fn secret_redactor() -> &'static SecretRedactor {
82    &GLOBAL
83}
84
85impl SecretRedactor {
86    pub const fn new() -> Self {
87        Self {
88            entries: RwLock::new(Entries {
89                values: Vec::new(),
90                replacements: Vec::new(),
91                automaton: None,
92            }),
93        }
94    }
95
96    /// Registers `value`, resolved from `reference`, and the forms of it
97    /// that a connector or a formatter can derive: see the module
98    /// documentation.
99    pub fn register(&self, reference: &str, value: &str) {
100        self.register_value(Some(reference), value);
101    }
102
103    /// Adds a schema-declared credential. A reference registered for the same
104    /// value, before or after this call, takes precedence over the marker.
105    /// The global length floor applies here too.
106    pub fn register_credential(&self, value: &str) {
107        self.register_value(None, value);
108    }
109
110    fn register_value(&self, reference: Option<&str>, value: &str) {
111        if value.trim().len() < MIN_REDACTED_LEN {
112            return;
113        }
114        let original = reference.map_or(Replacement::Credential, |r| {
115            Replacement::Reference(r.to_owned())
116        });
117        let derived = reference.map_or(Replacement::Credential, |r| {
118            Replacement::Reference(format!("[REDACTED {r}]"))
119        });
120        let mut forms = vec![
121            (value.to_string(), original.clone()),
122            (value.trim().to_string(), original),
123            (urlencoding::encode(value).into_owned(), derived.clone()),
124            (debug_escaped(value), derived.clone()),
125            (json_escaped(value), derived.clone()),
126        ];
127        if let Ok(decoded) = urlencoding::decode(value) {
128            forms.push((decoded.into_owned(), derived.clone()));
129        }
130        if let Some(password) = Url::parse(value)
131            .ok()
132            .and_then(|url| url.password().map(str::to_owned))
133        {
134            if let Ok(decoded) = urlencoding::decode(&password) {
135                forms.push((debug_escaped(&decoded), derived.clone()));
136                forms.push((decoded.into_owned(), derived.clone()));
137            }
138            forms.push((debug_escaped(&password), derived.clone()));
139            forms.push((password, derived));
140        }
141
142        let mut entries = self.entries.write().unwrap_or_else(PoisonError::into_inner);
143        let mut changed = false;
144        for (value, replacement) in forms {
145            if value.len() < MIN_REDACTED_LEN {
146                continue;
147            }
148            if let Some(index) = entries
149                .values
150                .iter()
151                .position(|existing| existing == &value)
152            {
153                if matches!(entries.replacements[index], Replacement::Credential) {
154                    entries.replacements[index] = replacement;
155                }
156                continue;
157            }
158            entries.values.push(value);
159            entries.replacements.push(replacement);
160            changed = true;
161        }
162        if !changed {
163            return;
164        }
165        // Leftmost-longest: a URL is replaced before the password inside it.
166        entries.automaton = Some(
167            AhoCorasick::builder()
168                .match_kind(MatchKind::LeftmostLongest)
169                .build(&entries.values)
170                .expect("plain string patterns build"),
171        );
172    }
173
174    /// Replaces every registered value in `text`.
175    ///
176    /// A value is replaced where it stands as a whole token: a secret that
177    /// is a common word, such as a user name, does not rewrite the longer
178    /// identifiers that contain it.
179    pub fn redact<'a>(&self, text: &'a str) -> Cow<'a, str> {
180        let entries = self.entries.read().unwrap_or_else(PoisonError::into_inner);
181        Self::redact_entries(&entries, text)
182    }
183
184    /// Redacts a panic payload without waiting for a registry writer. The panic
185    /// may have interrupted that writer on this thread. While a writer holds
186    /// the lock, omit the payload; the hook keeps its location and backtrace.
187    /// A lock poisoned by an earlier panic still holds a usable registry.
188    pub fn redact_for_panic<'a>(&self, text: &'a str) -> Cow<'a, str> {
189        match self.entries.try_read() {
190            Ok(entries) => Self::redact_entries(&entries, text),
191            Err(TryLockError::Poisoned(poisoned)) => {
192                Self::redact_entries(&poisoned.into_inner(), text)
193            }
194            Err(TryLockError::WouldBlock) => Cow::Owned("[REDACTED]".to_string()),
195        }
196    }
197
198    /// Replaces every value of `entries` in `text`, which is one message or
199    /// log line. Returns `text` itself when it holds none.
200    fn redact_entries<'a>(entries: &Entries, text: &'a str) -> Cow<'a, str> {
201        let Some(automaton) = &entries.automaton else {
202            return Cow::Borrowed(text);
203        };
204        let mut out = String::new();
205        let mut last = 0;
206        let mut search_from = 0;
207        while let Some(found) = automaton.find(&text[search_from..]) {
208            let start = search_from + found.start();
209            let mut end = search_from + found.end();
210            let mut pattern = found.pattern().as_usize();
211            if !at_token_boundary(text, start, end) {
212                // A rejected longer pattern must not hide an eligible shorter
213                // credential at the same position or inside it.
214                let shorter = entries
215                    .values
216                    .iter()
217                    .enumerate()
218                    .filter(|(_, value)| {
219                        text[start..].starts_with(value.as_str())
220                            && at_token_boundary(text, start, start + value.len())
221                    })
222                    .max_by_key(|(_, value)| value.len());
223                if let Some((index, value)) = shorter {
224                    pattern = index;
225                    end = start + value.len();
226                } else {
227                    // Patterns are nonempty UTF-8 strings.
228                    search_from = start + text[start..].chars().next().unwrap().len_utf8();
229                    continue;
230                }
231            }
232            out.push_str(&text[last..start]);
233            out.push_str(entries.replacements[pattern].text());
234            last = end;
235            search_from = end;
236        }
237        if last == 0 {
238            Cow::Borrowed(text)
239        } else {
240            out.push_str(&text[last..]);
241            Cow::Owned(out)
242        }
243    }
244
245    /// Whether the registry holds a value.
246    fn is_empty(&self) -> bool {
247        self.entries
248            .read()
249            .unwrap_or_else(PoisonError::into_inner)
250            .automaton
251            .is_none()
252    }
253
254    /// Replaces every registered value in `bytes`, read as UTF-8.
255    pub fn redact_bytes<'a>(&self, bytes: &'a [u8]) -> Cow<'a, [u8]> {
256        let text = String::from_utf8_lossy(bytes);
257        match self.redact(&text) {
258            Cow::Borrowed(_) => Cow::Borrowed(bytes),
259            Cow::Owned(redacted) => Cow::Owned(redacted.into_bytes()),
260        }
261    }
262
263    /// Replaces every registered value in the strings of `value`, keys
264    /// included.
265    pub fn redact_json(&self, value: &mut Value) {
266        if !self.is_empty() {
267            rewrite_json_strings(value, &|text| self.redact(text));
268        }
269    }
270}
271
272/// Whether `c` can be part of an identifier or a word.
273fn is_token_char(c: char) -> bool {
274    c.is_alphanumeric() || c == '_'
275}
276
277/// Whether the match at `text[start..end]` is not part of a longer token.
278/// An edge of the match that is itself no token character, such as a quote
279/// or a bracket, needs no boundary.
280fn at_token_boundary(text: &str, start: usize, end: usize) -> bool {
281    let found = &text[start..end];
282    let before = &text[..start];
283    let before_ok = !found.starts_with(is_token_char)
284        || before.chars().next_back().is_none_or(|c| !is_token_char(c))
285        || ends_with_escape(before);
286    let after_ok = !found.ends_with(is_token_char)
287        || text[end..].chars().next().is_none_or(|c| !is_token_char(c));
288    before_ok && after_ok
289}
290
291/// Whether `text` ends with an escape sequence that a formatter glued to
292/// the next token: `\n` from `{:?}`, or `%3D` from percent-encoding.
293fn ends_with_escape(text: &str) -> bool {
294    let bytes = text.as_bytes();
295    let n = bytes.len();
296    (n >= 2 && bytes[n - 2] == b'\\')
297        || (n >= 3
298            && bytes[n - 3] == b'%'
299            && bytes[n - 2].is_ascii_hexdigit()
300            && bytes[n - 1].is_ascii_hexdigit())
301}
302
303/// `value` as `{:?}` prints it, without the quotes.
304fn debug_escaped(value: &str) -> String {
305    let escaped = format!("{value:?}");
306    escaped[1..escaped.len() - 1].to_string()
307}
308
309/// `value` as serde_json writes it, without the quotes. It differs from the
310/// debug form for control characters: `\u0001` against `\u{1}`.
311fn json_escaped(value: &str) -> String {
312    let escaped = Value::String(value.to_string()).to_string();
313    escaped[1..escaped.len() - 1].to_string()
314}
315
316#[cfg(test)]
317mod tests {
318    use super::{MIN_REDACTED_LEN, SecretRedactor};
319    use serde_json::json;
320
321    const REFERENCE: &str = "${secret:kubernetes:pg/uri}";
322
323    /// `{:?}` and percent-encoding glue an escape to the value: the escape
324    /// is a boundary, not part of the token.
325    #[test]
326    fn an_escape_before_the_value_is_a_boundary() {
327        let redactor = SecretRedactor::new();
328        redactor.register(REFERENCE, "hunter2hunter2");
329        assert_eq!(
330            redactor.redact(r"line\nhunter2hunter2"),
331            format!(r"line\n{REFERENCE}")
332        );
333        assert_eq!(
334            redactor.redact("x%3Dhunter2hunter2"),
335            format!("x%3D{REFERENCE}")
336        );
337        // No escape here: the value is glued to a letter, so it is read as
338        // part of a longer word and stays.
339        assert_eq!(redactor.redact("nhunter2hunter2"), "nhunter2hunter2");
340    }
341
342    #[test]
343    fn panic_redaction_does_not_wait_for_a_registry_writer() {
344        let redactor = SecretRedactor::new();
345        redactor.register(REFERENCE, "panic-lock-secret-2136");
346        let writer = redactor.entries.write().unwrap();
347        assert_eq!(
348            redactor.redact_for_panic("panic-lock-secret-2136"),
349            "[REDACTED]"
350        );
351        drop(writer);
352        assert_eq!(
353            redactor.redact_for_panic("panic-lock-secret-2136"),
354            REFERENCE
355        );
356        assert_eq!(
357            redactor.redact_for_panic("ordinary panic"),
358            "ordinary panic"
359        );
360    }
361
362    /// A panic while a writer held the lock poisons it. Later panics still
363    /// get their payload redacted instead of omitted.
364    #[test]
365    fn a_poisoned_registry_still_redacts_panic_payloads() {
366        let redactor = SecretRedactor::new();
367        redactor.register(REFERENCE, "poison-secret-2136");
368        let poison = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
369            let _writer = redactor.entries.write().unwrap();
370            panic!("registration failed");
371        }));
372        assert!(poison.is_err());
373        assert!(redactor.entries.is_poisoned());
374        assert_eq!(
375            redactor.redact_for_panic("bad poison-secret-2136"),
376            format!("bad {REFERENCE}")
377        );
378        assert_eq!(
379            redactor.redact_for_panic("ordinary panic"),
380            "ordinary panic"
381        );
382    }
383
384    #[test]
385    fn concurrent_registration_preserves_every_reference() {
386        let redactor = SecretRedactor::new();
387        let start = std::sync::Barrier::new(4);
388        std::thread::scope(|scope| {
389            for worker in 0..4 {
390                let redactor = &redactor;
391                let start = &start;
392                scope.spawn(move || {
393                    start.wait();
394                    for index in 0..25 {
395                        let reference = format!("${{secret:kubernetes:worker{worker}/key{index}}}");
396                        let value = format!("concurrent-secret-{worker}-{index}-2136");
397                        redactor.register(&reference, &value);
398                        assert_eq!(redactor.redact(&value), reference);
399                    }
400                });
401            }
402        });
403        for worker in 0..4 {
404            for index in 0..25 {
405                assert_eq!(
406                    redactor.redact(&format!("concurrent-secret-{worker}-{index}-2136")),
407                    format!("${{secret:kubernetes:worker{worker}/key{index}}}")
408                );
409            }
410        }
411    }
412
413    #[test]
414    fn a_rejected_longer_match_does_not_hide_a_reference() {
415        let redactor = SecretRedactor::new();
416        redactor.register(REFERENCE, "nested-secret-2136");
417        redactor.register_credential("prefix/nested-secret-2136");
418        assert_eq!(
419            redactor.redact("xprefix/nested-secret-2136"),
420            format!("xprefix/{REFERENCE}")
421        );
422        redactor.register_credential("nested-secret-2136/suffix");
423        assert_eq!(
424            redactor.redact("nested-secret-2136/suffixx"),
425            format!("{REFERENCE}/suffixx")
426        );
427    }
428
429    #[test]
430    fn credential_key_collisions_preserve_all_details() {
431        let redactor = SecretRedactor::new();
432        redactor.register_credential("first-credential-2136");
433        redactor.register_credential("second-credential-2136");
434        let mut value =
435            json!({"first-credential-2136":1, "second-credential-2136":2, "[REDACTED]":3});
436        redactor.redact_json(&mut value);
437        let mut values: Vec<_> = value
438            .as_object()
439            .unwrap()
440            .values()
441            .map(|v| v.as_i64().unwrap())
442            .collect();
443        values.sort();
444        assert_eq!(values, vec![1, 2, 3]);
445        assert!(!value.to_string().contains("credential-2136"));
446    }
447
448    #[test]
449    fn references_win_over_credentials_in_either_order() {
450        for credential_first in [true, false] {
451            let redactor = SecretRedactor::new();
452            let value = "quote\"and\\secret-2136";
453            if credential_first {
454                redactor.register_credential(value);
455                assert_eq!(redactor.redact(value), "[REDACTED]");
456            }
457            redactor.register(REFERENCE, value);
458            redactor.register_credential(value);
459            redactor.register("${secret:kubernetes:other/key}", value);
460            assert_eq!(redactor.redact(value), REFERENCE);
461            assert_eq!(
462                redactor.redact(&super::json_escaped(value)),
463                format!("[REDACTED {REFERENCE}]")
464            );
465            assert_eq!(
466                redactor.redact(&urlencoding::encode(value)),
467                format!("[REDACTED {REFERENCE}]")
468            );
469        }
470    }
471
472    /// A rejected match scans the registry for a shorter form. Many near
473    /// misses against a large registry still give the right result quickly.
474    #[test]
475    fn many_near_misses_against_a_large_registry() {
476        let redactor = SecretRedactor::new();
477        for index in 0..200 {
478            redactor.register_credential(&format!("near-miss-value-{index:03}-2136"));
479        }
480        let line = (0..100)
481            .map(|index| format!("xnear-miss-value-{:03}-2136x", index % 200))
482            .collect::<Vec<_>>()
483            .join(" ");
484        assert_eq!(redactor.redact(&line), line);
485        assert_eq!(
486            redactor.redact(&format!("{line} near-miss-value-007-2136")),
487            format!("{line} [REDACTED]")
488        );
489    }
490
491    #[test]
492    fn inline_credentials_keep_the_length_floor_and_token_boundaries() {
493        let redactor = SecretRedactor::new();
494        for value in ["on", "1", "  short  "] {
495            redactor.register_credential(value);
496        }
497        assert_eq!(redactor.redact("on 1 short"), "on 1 short");
498        redactor.register_credential("inline-credential-2136");
499        assert_eq!(
500            redactor.redact("password inline-credential-2136 rejected"),
501            "password [REDACTED] rejected"
502        );
503        assert_eq!(
504            redactor.redact("prefixinline-credential-2136suffix"),
505            "prefixinline-credential-2136suffix"
506        );
507    }
508
509    #[test]
510    fn value_becomes_its_reference() {
511        let redactor = SecretRedactor::new();
512        redactor.register(REFERENCE, "hunter2-hunter2");
513        assert_eq!(
514            redactor.redact("password hunter2-hunter2 rejected"),
515            format!("password {REFERENCE} rejected")
516        );
517        assert_eq!(
518            redactor.redact_bytes(b"ok hunter2-hunter2\n").as_ref(),
519            format!("ok {REFERENCE}\n").as_bytes()
520        );
521    }
522
523    #[test]
524    fn url_password_and_encoded_forms_are_redacted() {
525        let redactor = SecretRedactor::new();
526        let uri = "postgres://feldera:p%40ss-word-2136@db.internal:5432/app";
527        redactor.register(REFERENCE, uri);
528        assert_eq!(redactor.redact(uri), REFERENCE);
529        assert_eq!(
530            redactor.redact("password \"p@ss-word-2136\" rejected"),
531            format!("password \"[REDACTED {REFERENCE}]\" rejected")
532        );
533        assert_eq!(
534            redactor.redact("password \"p%40ss-word-2136\" rejected"),
535            format!("password \"[REDACTED {REFERENCE}]\" rejected")
536        );
537        assert_eq!(
538            redactor.redact(&urlencoding::encode(uri)),
539            format!("[REDACTED {REFERENCE}]")
540        );
541    }
542
543    #[test]
544    fn trimmed_and_escaped_forms_are_redacted() {
545        let redactor = SecretRedactor::new();
546        redactor.register(REFERENCE, "quote\"and\\slash\n");
547        assert_eq!(
548            redactor.redact("x quote\"and\\slash y"),
549            format!("x {REFERENCE} y")
550        );
551        assert_eq!(
552            redactor.redact("x quote\\\"and\\\\slash\\n y"),
553            format!("x [REDACTED {REFERENCE}] y")
554        );
555    }
556
557    /// A secret that is a common word stays inside longer identifiers; the
558    /// word on its own is still replaced.
559    #[test]
560    fn a_common_word_leaves_longer_tokens_alone() {
561        let redactor = SecretRedactor::new();
562        redactor.register("${secret:kubernetes:pg/user}", "postgres");
563        assert_eq!(
564            redactor.redact("Unable to connect to postgres instance via postgres_input"),
565            "Unable to connect to ${secret:kubernetes:pg/user} instance via postgres_input"
566        );
567        assert_eq!(
568            redactor.redact("postgresql://h/db postgres1 'postgres'"),
569            "postgresql://h/db postgres1 '${secret:kubernetes:pg/user}'"
570        );
571    }
572
573    /// A control character is written differently by serde_json and by
574    /// `{:?}`; both forms are recognized.
575    #[test]
576    fn json_escaped_control_characters_are_redacted() {
577        let redactor = SecretRedactor::new();
578        redactor.register(REFERENCE, "ctrl\u{1}secret-2136");
579        let json = serde_json::to_string("value ctrl\u{1}secret-2136 end").unwrap();
580        assert_eq!(
581            redactor.redact(&json),
582            format!("\"value [REDACTED {REFERENCE}] end\"")
583        );
584        assert_eq!(
585            redactor.redact("value ctrl\\u{1}secret-2136 end"),
586            format!("value [REDACTED {REFERENCE}] end")
587        );
588    }
589
590    #[test]
591    fn short_values_are_not_registered() {
592        let redactor = SecretRedactor::new();
593        let short = "a".repeat(MIN_REDACTED_LEN - 1);
594        redactor.register(REFERENCE, &short);
595        assert_eq!(redactor.redact(&short), short);
596        // The floor counts the trimmed value.
597        redactor.register(REFERENCE, &format!("{short}\n"));
598        assert_eq!(redactor.redact(&short), short);
599    }
600
601    #[test]
602    fn first_registration_wins_and_several_values_share_a_line() {
603        let redactor = SecretRedactor::new();
604        redactor.register(REFERENCE, "shared-secret-value");
605        redactor.register("${secret:kubernetes:other/key}", "shared-secret-value");
606        redactor.register("${secret:kubernetes:kafka/pw}", "kafka-secret-value");
607        assert_eq!(
608            redactor.redact("a shared-secret-value b kafka-secret-value c"),
609            format!("a {REFERENCE} b ${{secret:kubernetes:kafka/pw}} c")
610        );
611    }
612
613    #[test]
614    fn json_strings_are_redacted() {
615        let redactor = SecretRedactor::new();
616        redactor.register(REFERENCE, "json-secret-value");
617        let mut details = json!({
618            "endpoint": "pg_in",
619            "error": "connect json-secret-value failed",
620            "chain": [{"cause": "json-secret-value"}, 1, null, true],
621        });
622        redactor.redact_json(&mut details);
623        assert_eq!(
624            details,
625            json!({
626                "endpoint": "pg_in",
627                "error": format!("connect {REFERENCE} failed"),
628                "chain": [{"cause": REFERENCE}, 1, null, true],
629            })
630        );
631    }
632
633    #[test]
634    fn escaped_url_passwords_and_json_keys_are_redacted() {
635        let redactor = SecretRedactor::new();
636        redactor.register(REFERENCE, "postgres://u:pass%22word2136@db/app");
637        assert_eq!(
638            redactor.redact(r#"password pass\"word2136"#),
639            format!("password [REDACTED {REFERENCE}]")
640        );
641        redactor.register(REFERENCE, "json-key-secret-2136");
642        let mut details = json!({"json-key-secret-2136": "details"});
643        redactor.redact_json(&mut details);
644        assert_eq!(details, json!({REFERENCE: "details"}));
645    }
646
647    /// A URL match rejected at a token boundary must not hide the password
648    /// inside it: the scan resumes one character further, not after the
649    /// rejected match.
650    #[test]
651    fn a_rejected_longer_match_does_not_hide_the_password_inside() {
652        let redactor = SecretRedactor::new();
653        redactor.register(REFERENCE, "postgres://u:Sup3rSecretPw@db/app");
654        assert_eq!(
655            redactor.redact("connect postgres://u:Sup3rSecretPw@db/app2 failed"),
656            format!("connect postgres://u:[REDACTED {REFERENCE}]@db/app2 failed")
657        );
658    }
659}