Skip to main content

agentmux_srv_core/backend/vault/
scrub.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Takes a Vault value out of a command's output before anything reads it
5//! (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md ยง7.2).
6//!
7//! **A guard, not a boundary.** A command the agent writes can transform the
8//! value and print it, or send it anywhere. What limits that is the person
9//! seeing the command before an entry is first used. The scrubber catches the
10//! ordinary ways a tool echoes a key it was given: the value itself, and its
11//! base64, URL-encoded and hex forms. For a value of several lines (a private
12//! key), each line is scrubbed too, since output is read line by line.
13
14use base64::Engine as _;
15
16/// Shorter values are refused as command secrets: scrubbing "123" would
17/// mangle every output that has it.
18pub const MIN_LEN: usize = 4;
19
20/// The shortest line of a multi-line value that is scrubbed on its own.
21pub const MIN_LINE: usize = 6;
22
23pub struct Scrubber {
24    /// (what to find, what to put there), longest first so a form that contains
25    /// another is replaced whole.
26    needles: Vec<(String, String)>,
27    /// Values of exactly three digits (a card's security code): found only on their own, where no letter or digit
28    /// touches them, and never inside a mark already put in place. Replaced after the longer needles.
29    standalone: Vec<(String, String)>,
30}
31
32/// Whether the scrubber can clean `value` out of an output: as text (`MIN_LEN` characters or more), or, for a card's
33/// three-digit security code, where it stands alone. Anything shorter would be stored and still show in the output.
34pub fn cleanable(value: &str) -> bool {
35    value.chars().count() >= MIN_LEN || is_code(value)
36}
37
38/// A card's three-digit security code: too short to scrub as text, since `123` is in `4123` and in a timestamp.
39fn is_code(value: &str) -> bool {
40    value.len() == 3 && value.bytes().all(|b| b.is_ascii_digit())
41}
42
43/// `needle` in `text` where it stands alone, as `mark`.
44fn standalone_in(text: &str, needle: &str, mark: &str) -> String {
45    let bytes = text.as_bytes();
46    let touches = |b: Option<u8>| b.is_some_and(|b| b.is_ascii_alphanumeric());
47    let (mut out, mut last) = (String::with_capacity(text.len()), 0);
48    for (at, _) in text.match_indices(needle) {
49        if touches(at.checked_sub(1).map(|i| bytes[i])) || touches(bytes.get(at + needle.len()).copied()) {
50            continue;
51        }
52        out.push_str(&text[last..at]);
53        out.push_str(mark);
54        last = at + needle.len();
55    }
56    out.push_str(&text[last..]);
57    out
58}
59
60/// [`standalone_in`] over `text`, leaving every `[vault:...]` mark as it is: an entry's id can hold the digits.
61fn replace_standalone(text: &str, needle: &str, mark: &str) -> String {
62    let (mut out, mut rest) = (String::with_capacity(text.len()), text);
63    while !rest.is_empty() {
64        let (plain, kept) = match rest.find("[vault:") {
65            Some(at) => (&rest[..at], &rest[at..at + rest[at..].find(']').map_or(rest.len() - at, |e| e + 1)]),
66            None => (rest, ""),
67        };
68        out.push_str(&standalone_in(plain, needle, mark));
69        out.push_str(kept);
70        rest = &rest[plain.len() + kept.len()..];
71    }
72    out
73}
74
75fn percent_encode(s: &str) -> String {
76    let mut out = String::with_capacity(s.len());
77    for b in s.bytes() {
78        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
79            out.push(b as char);
80        } else {
81            out.push_str(&format!("%{b:02X}"));
82        }
83    }
84    out
85}
86
87/// A value and its other ordinary spellings (base64, URL-encoded, hex, as JSON holds it).
88pub(crate) fn forms(value: &str) -> Vec<String> {
89    let engines = [
90        base64::engine::general_purpose::STANDARD,
91        base64::engine::general_purpose::STANDARD_NO_PAD,
92        base64::engine::general_purpose::URL_SAFE,
93        base64::engine::general_purpose::URL_SAFE_NO_PAD,
94    ];
95    let mut out = vec![value.to_string(), percent_encode(value), percent_encode(value).to_lowercase()];
96    out.extend(engines.iter().map(|e| e.encode(value)));
97    let hex: String = value.bytes().map(|b| format!("{b:02x}")).collect();
98    out.push(hex.to_uppercase());
99    out.push(hex);
100    out.extend(json_forms(value));
101    out
102}
103
104/// A value as a JSON string holds it, without the quotes: escaped as serde_json
105/// writes it, with `/` escaped too, and with everything outside ASCII as `\uXXXX`.
106/// A tool that prints JSON prints a value with a quote, a backslash or a newline
107/// in one of these forms, never as is.
108fn json_forms(value: &str) -> Vec<String> {
109    let quoted = serde_json::to_string(value).unwrap_or_default();
110    let Some(plain) = quoted.strip_prefix('"').and_then(|q| q.strip_suffix('"')) else {
111        return Vec::new();
112    };
113    let ascii: String = plain
114        .chars()
115        .flat_map(|c| -> Vec<char> {
116            if c.is_ascii() {
117                vec![c]
118            } else {
119                c.encode_utf16(&mut [0; 2]).iter().flat_map(|u| format!("\\u{u:04x}").chars().collect::<Vec<_>>()).collect()
120            }
121        })
122        .collect();
123    vec![plain.to_string(), plain.replace('/', "\\/"), ascii]
124}
125
126impl Scrubber {
127    /// `secrets` are (entry id, value).
128    pub fn new(secrets: &[(String, String)]) -> Self {
129        let mut needles: Vec<(String, String)> = Vec::new();
130        let mut standalone: Vec<(String, String)> = Vec::new();
131        for (id, value) in secrets {
132            let mark = format!("[vault:{id}]");
133            if is_code(value) {
134                if !standalone.iter().any(|(n, _)| n == value) {
135                    standalone.push((value.clone(), mark));
136                }
137                continue;
138            }
139            let mut parts = vec![value.clone()];
140            if value.contains('\n') {
141                // Output arrives line by line, so a multi-line value never appears whole.
142                parts.extend(value.lines().map(str::trim).filter(|l| l.len() >= MIN_LINE).map(str::to_string));
143            }
144            for part in parts {
145                for form in forms(&part) {
146                    if form.len() >= MIN_LEN && !needles.iter().any(|(n, _)| *n == form) {
147                        needles.push((form, mark.clone()));
148                    }
149                }
150            }
151        }
152        needles.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
153        Self { needles, standalone }
154    }
155
156    /// One scrubber with both sets of values, longest first. Applying two in turn
157    /// isn't the same: the first can break up the second's longer value (a new key
158    /// that contains a key the command was given) and leave the rest of it.
159    pub fn merged(&self, other: &Scrubber) -> Scrubber {
160        let mut needles = self.needles.clone();
161        for n in &other.needles {
162            if !needles.iter().any(|(f, _)| *f == n.0) {
163                needles.push(n.clone());
164            }
165        }
166        needles.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
167        let mut standalone = self.standalone.clone();
168        for n in &other.standalone {
169            if !standalone.iter().any(|(f, _)| *f == n.0) {
170                standalone.push(n.clone());
171            }
172        }
173        Scrubber { needles, standalone }
174    }
175
176    pub fn scrub<'a>(&self, text: &'a str) -> std::borrow::Cow<'a, str> {
177        let mut out = std::borrow::Cow::Borrowed(text);
178        for (needle, mark) in &self.needles {
179            if out.contains(needle.as_str()) {
180                out = std::borrow::Cow::Owned(out.replace(needle.as_str(), mark));
181            }
182        }
183        for (needle, mark) in &self.standalone {
184            if out.contains(needle.as_str()) {
185                let replaced = replace_standalone(&out, needle, mark);
186                if replaced != *out {
187                    out = std::borrow::Cow::Owned(replaced);
188                }
189            }
190        }
191        out
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    fn scrubber(value: &str) -> Scrubber {
200        Scrubber::new(&[("api-key-stripe".to_string(), value.to_string())])
201    }
202
203    #[test]
204    fn the_value_and_its_ordinary_encodings_are_replaced_by_the_entrys_name() {
205        let s = scrubber("sk_live_a/b+c=1234");
206        let mark = "[vault:api-key-stripe]";
207        assert_eq!(s.scrub("key is sk_live_a/b+c=1234 ok"), format!("key is {mark} ok"));
208        let b64 = base64::engine::general_purpose::STANDARD.encode("sk_live_a/b+c=1234");
209        assert_eq!(s.scrub(&format!("Authorization: Basic {b64}")), format!("Authorization: Basic {mark}"));
210        let url = percent_encode("sk_live_a/b+c=1234");
211        assert_eq!(s.scrub(&format!("?key={url}&x=1")), format!("?key={mark}&x=1"));
212        let hex: String = "sk_live_a/b+c=1234".bytes().map(|b| format!("{b:02x}")).collect();
213        assert_eq!(s.scrub(&hex.to_uppercase()), mark);
214        assert_eq!(s.scrub(&hex), mark);
215        let nopad = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode("sk_live_a/b+c=1234");
216        assert_eq!(s.scrub(&nopad), mark);
217    }
218
219    #[test]
220    fn output_without_the_value_is_untouched() {
221        let s = scrubber("hunter2-secret");
222        assert_eq!(s.scrub("all fine here"), "all fine here");
223        assert!(matches!(s.scrub("all fine here"), std::borrow::Cow::Borrowed(_)));
224    }
225
226    #[test]
227    fn each_line_of_a_multi_line_value_is_scrubbed() {
228        let key = "-----BEGIN KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\nabcdEFGHijklMNOP\n-----END KEY-----";
229        let s = scrubber(key);
230        assert_eq!(s.scrub("MIIEvQIBADANBgkqhkiG9w0BAQEFAASC"), "[vault:api-key-stripe]");
231        assert_eq!(s.scrub("  abcdEFGHijklMNOP  "), "  [vault:api-key-stripe]  ");
232        assert_eq!(s.scrub("-----BEGIN KEY-----"), "[vault:api-key-stripe]");
233    }
234
235    #[test]
236    fn a_longer_form_is_replaced_whole_before_a_shorter_one_inside_it() {
237        let s = Scrubber::new(&[("a".to_string(), "abcd1234".to_string()), ("b".to_string(), "abcd1234-and-more".to_string())]);
238        assert_eq!(s.scrub("x abcd1234-and-more y"), "x [vault:b] y");
239        assert_eq!(s.scrub("x abcd1234 y"), "x [vault:a] y");
240    }
241
242
243    #[test]
244    fn a_three_digit_code_is_scrubbed_where_it_stands_alone_and_left_in_longer_digits() {
245        let s = Scrubber::new(&[("card-visa".to_string(), "123".to_string())]);
246        let mark = "[vault:card-visa]";
247        assert_eq!(s.scrub("cvv: 123"), format!("cvv: {mark}"));
248        assert_eq!(s.scrub("\"cvv\":\"123\""), format!("\"cvv\":\"{mark}\""));
249        assert_eq!(s.scrub("123 and 123."), format!("{mark} and {mark}."));
250        assert_eq!(s.scrub("order 4123 of 1234, id a123 b123c"), "order 4123 of 1234, id a123 b123c", "digits or letters touching it are another value");
251        assert!(matches!(s.scrub("no code here"), std::borrow::Cow::Borrowed(_)));
252    }
253
254    #[test]
255    fn a_mark_already_in_place_is_not_scrubbed_again_when_its_id_holds_the_digits() {
256        // The long value goes first and leaves its mark; the code `123` is then looked for around the marks, not in them.
257        let s = Scrubber::new(&[("card-123".to_string(), "4242424242424242".to_string()), ("card-123".to_string(), "123".to_string())]);
258        assert_eq!(s.scrub("pan 4242424242424242 cvv 123"), "pan [vault:card-123] cvv [vault:card-123]");
259    }
260
261    #[test]
262    fn a_longer_secret_that_holds_the_code_is_replaced_whole_first() {
263        let s = Scrubber::new(&[("api-key-a".to_string(), "sk_123_abcdef".to_string()), ("card-v".to_string(), "123".to_string())]);
264        assert_eq!(s.scrub("key sk_123_abcdef and 123"), "key [vault:api-key-a] and [vault:card-v]");
265    }
266
267    #[test]
268    fn merged_scrubbers_keep_the_codes_of_both() {
269        let a = Scrubber::new(&[("card-a".to_string(), "123".to_string())]);
270        let b = Scrubber::new(&[("card-b".to_string(), "456".to_string())]);
271        assert_eq!(a.merged(&b).scrub("123 456"), "[vault:card-a] [vault:card-b]");
272    }
273}