Skip to main content

artifactize_provider/
secret.rs

1//! The one rule for server text that is about to be shown, saved or logged while a request
2//! carried a credential (a bearer token, an API key): a store, provider or proxy may echo the
3//! credential back, whole or split, inside an error. Control characters go first (so a split
4//! cannot be rejoined by dropping them afterwards), then text holding any piece of a
5//! credential is withheld whole, and only then is the rest clipped.
6
7/// Consecutive characters of a credential that count as a piece of it. Eight characters of a
8/// random token are already too many to guess from, while shorter runs (a `sk-` prefix, a common
9/// word) occur in ordinary error text and would withhold harmless messages.
10const PIECE: usize = 8;
11
12/// Below this length, a substring match would make ordinary tool keys and arguments
13/// such as `payload` or `data` collide with one-character credentials.
14const MIN_TOOL_SUBSTRING_CHARS: usize = 4;
15
16/// What is shown instead of server text that held part of a credential.
17pub const WITHHELD: &str = "[withheld: it contained part of the credential sent]";
18
19/// `text` from a server, safe to show: no control characters, no piece of `secrets`, at most
20/// `max_chars` characters.
21pub fn server_text(text: &str, secrets: &[&str], max_chars: usize) -> String {
22    let text: String = text.chars().filter(|c| !c.is_control()).collect();
23    if !secrets.is_empty()
24        && escapes::matches(&text, |spelling| {
25            let visible: String = spelling.chars().filter(|c| !c.is_control()).collect();
26            secrets.iter().any(|secret| holds_piece(&visible, secret))
27        })
28    {
29        return StreamRedactor::new(secrets.iter().map(|value| (*value).to_owned()))
30            .redact_all(WITHHELD);
31    }
32    text.chars().take(max_chars).collect()
33}
34
35/// `text` contains `PIECE` consecutive characters of `secret` (all of a shorter one).
36fn holds_piece(text: &str, secret: &str) -> bool {
37    let secret: Vec<char> = secret.chars().filter(|c| !c.is_control()).collect();
38    if secret.is_empty() {
39        return false;
40    }
41    let size = PIECE.min(secret.len());
42    secret
43        .windows(size)
44        .any(|piece| text.contains(&piece.iter().collect::<String>()))
45}
46
47#[cfg(test)]
48mod tests;
49
50mod escapes;
51pub(crate) use escapes::MARKERS as ESCAPE_MARKERS;
52pub(crate) mod history;
53mod stream;
54pub use stream::{REDACTED, StreamRedactor};
55
56/// Managed credential values. Short values are checked at the tool-argument
57/// boundary, but are not used to scrub ordinary text or payloads.
58#[derive(Clone, Default, PartialEq, Eq)]
59pub struct Inventory {
60    values: Vec<String>,
61    short_values: Vec<String>,
62    unavailable: bool,
63}
64
65impl Inventory {
66    pub(crate) fn withheld() -> Self {
67        Self {
68            unavailable: true,
69            ..Self::default()
70        }
71    }
72
73    /// Read the credentials of this profile without authenticating, refreshing, or initiating HTTP.
74    pub fn read(
75        providers: Option<&crate::auth::Location>,
76        codex: Option<&crate::auth::Location>,
77    ) -> Self {
78        Self::read_values(providers, codex).unwrap_or_else(|_| Self::withheld())
79    }
80
81    /// Read credentials for a boundary that must report an unavailable inventory.
82    pub fn try_read(
83        providers: Option<&crate::auth::Location>,
84        codex: Option<&crate::auth::Location>,
85    ) -> Result<Self, String> {
86        // A refused location is harmless only when it holds no credential file.
87        if let Some(location) = providers {
88            location.refusal(crate::auth::providers::FILE)?;
89        }
90        if let Some(location) = codex {
91            location.refusal(crate::auth::codex::CREDENTIALS)?;
92        }
93        Self::read_values(providers, codex)
94    }
95
96    fn read_values(
97        providers: Option<&crate::auth::Location>,
98        codex: Option<&crate::auth::Location>,
99    ) -> Result<Self, String> {
100        let providers = crate::auth::providers::secret_values(providers)?;
101        let codex = crate::auth::codex::secret_values(codex)?;
102        Ok(Self::new(providers.chain(codex)))
103    }
104
105    pub fn new(values: impl IntoIterator<Item = String>) -> Self {
106        let mut secrets = Self::default();
107        for value in values {
108            secrets.include(value);
109        }
110        secrets
111    }
112
113    pub fn include(&mut self, value: String) {
114        if value.is_empty() {
115            return;
116        }
117        if value.chars().nth(PIECE - 1).is_none() {
118            if !self.short_values.contains(&value) {
119                self.short_values.push(value);
120            }
121            return;
122        }
123        if self.values.contains(&value) {
124            return;
125        }
126        // The same credential may reach an error via Rust Debug or a structured JSON
127        // string. Match both spellings without the surrounding quotation marks.
128        let debug = format!("{value:?}");
129        let json = serde_json::to_string(&value).expect("string is serializable");
130        for encoded in [&debug[1..debug.len() - 1], &json[1..json.len() - 1]] {
131            if encoded != value && !self.values.iter().any(|known| known == encoded) {
132                self.values.push(encoded.to_owned());
133            }
134        }
135        self.values.push(value);
136    }
137
138    /// Whether there is nothing to scrub from ordinary text.
139    pub fn is_empty(&self) -> bool {
140        !self.unavailable && self.values.is_empty()
141    }
142
143    pub fn merge(&mut self, other: Self) {
144        self.unavailable |= other.unavailable;
145        for (known, observed) in [
146            (&mut self.values, other.values),
147            (&mut self.short_values, other.short_values),
148        ] {
149            for value in observed {
150                if !known.contains(&value) {
151                    known.push(value);
152                }
153            }
154        }
155    }
156
157    /// Unlike text scrubbing, structured tool arguments must not carry short credentials
158    /// either. Check actual keys and values, not incidental JSON syntax or tool metadata.
159    pub(crate) fn contains_short_tool_credential(&self, arguments: &serde_json::Value) -> bool {
160        !self.short_values.is_empty() && short_tool_credential(arguments, &self.short_values)
161    }
162
163    /// Include additional caller-owned secrets without taking ownership of their source.
164    pub fn stream_with(&self, additional: impl IntoIterator<Item = String>) -> StreamRedactor {
165        if self.unavailable {
166            return StreamRedactor::withheld();
167        }
168        StreamRedactor::new(self.values.iter().cloned().chain(additional))
169    }
170
171    pub fn stream(&self) -> StreamRedactor {
172        self.stream_with(std::iter::empty())
173    }
174
175    pub fn contains(&self, text: &str) -> bool {
176        self.unavailable && !text.is_empty()
177            || !self.values.is_empty()
178                && escapes::matches(text, |text| {
179                    self.values.iter().any(|secret| text.contains(secret))
180                })
181    }
182
183    /// Remove managed values and their escaped spellings in the text's own syntax
184    /// (for example, JSON or URL escapes), not alternate encodings such as Base64.
185    pub fn scrub(&self, text: &str) -> String {
186        if !self.contains(text) {
187            return text.to_owned();
188        }
189        if !text.contains(ESCAPE_MARKERS) {
190            return self.stream().redact_all(text);
191        }
192        let mut clean = text.to_owned();
193        self.scrub_escaped(text, &mut [&mut clean]);
194        clean
195    }
196
197    /// The suffix of unescaped text that could overlap a currently known secret.
198    /// The caller must still retain the earlier text for future inventory updates.
199    pub(crate) fn overlap_tail<'a>(&self, text: &'a str) -> &'a str {
200        let max = self.values.iter().map(String::len).max().unwrap_or(0);
201        let start = text.len().saturating_sub(max.saturating_sub(1));
202        &text[text.ceil_char_boundary(start)..]
203    }
204
205    /// Scrub text items as one display stream, retaining their order and item count.
206    pub(crate) fn scrub_joined(&self, parts: &mut [&mut String]) {
207        if parts.is_empty() || self.is_empty() {
208            return;
209        }
210        let joined: String = parts.iter().map(|part| part.as_str()).collect();
211        if !self.contains(&joined) {
212            return;
213        }
214        if joined.contains(ESCAPE_MARKERS) {
215            self.scrub_escaped(&joined, parts);
216            return;
217        }
218        let mut stream = self.stream();
219        for part in parts.iter_mut() {
220            **part = stream.push(part);
221        }
222        parts
223            .last_mut()
224            .expect("checked nonempty")
225            .push_str(&stream.flush());
226    }
227
228    fn scrub_escaped(&self, joined: &str, parts: &mut [&mut String]) {
229        let ranges = (!self.unavailable)
230            .then(|| escapes::spans(joined, &self.values))
231            .flatten();
232        let Some(ranges) = ranges else {
233            parts.iter_mut().for_each(|part| part.clear());
234            return;
235        };
236        let pattern = self.stream();
237        let marker = pattern.marker();
238        let mut offset = 0;
239        let mut ranges = ranges.into_iter().peekable();
240        for part in parts.iter_mut() {
241            let end = offset + part.len();
242            let mut cursor = offset;
243            let mut clean = String::new();
244            while let Some(range) = ranges.peek().filter(|range| range.start < end) {
245                if range.start >= cursor {
246                    clean.push_str(&joined[cursor..range.start]);
247                    clean.push_str(marker);
248                }
249                cursor = end.min(range.end);
250                if range.end > end {
251                    break;
252                }
253                ranges.next();
254            }
255            clean.push_str(&joined[cursor..end]);
256            **part = clean;
257            offset = end;
258        }
259        let clean: String = parts.iter().map(|part| part.as_str()).collect();
260        if self.contains(&clean) {
261            // Removing a range may change the interpretation of surrounding escapes.
262            parts.iter_mut().for_each(|part| part.clear());
263        }
264    }
265
266    pub(crate) fn contains_piece(&self, text: &str) -> bool {
267        self.unavailable && !text.is_empty()
268            || !self.values.is_empty()
269                && escapes::matches(text, |spelling| {
270                    let text: String = spelling.chars().filter(|c| !c.is_control()).collect();
271                    self.values.iter().any(|secret| holds_piece(&text, secret))
272                })
273    }
274
275    pub fn diagnostic(&self, text: &str, max_chars: usize) -> String {
276        if self.unavailable {
277            return String::new();
278        }
279        server_text(
280            text,
281            &self.values.iter().map(String::as_str).collect::<Vec<_>>(),
282            max_chars,
283        )
284    }
285
286    /// Scrub string values and object keys before an external JSON payload crosses a boundary.
287    pub fn scrub_json(&self, value: &mut serde_json::Value) -> bool {
288        use serde_json::Value;
289        match value {
290            Value::String(text) if self.contains(text) => {
291                *text = self.scrub(text);
292                true
293            }
294            Value::Number(_) | Value::Bool(_) if self.contains(&value.to_string()) => {
295                *value = Value::Null;
296                true
297            }
298            Value::Array(items) => {
299                let mut changed = false;
300                for item in items {
301                    changed |= self.scrub_json(item);
302                }
303                changed
304            }
305            Value::Object(fields) => {
306                let mut changed = false;
307                let mut suspect = Vec::new();
308                for (key, value) in fields.iter_mut() {
309                    changed = self.scrub_json(value) || changed;
310                    if self.contains(key) {
311                        suspect.push(key.clone());
312                    }
313                }
314                for key in suspect {
315                    let value = fields
316                        .remove(&key)
317                        .expect("observed field is still present");
318                    fields.entry(self.scrub(&key)).or_insert(value);
319                    changed = true;
320                }
321                changed
322            }
323            _ => false,
324        }
325    }
326
327    /// Check typed payloads (including decoded structured strings) without logging them or
328    /// asking a caller to enumerate provider-specific fields.
329    pub(crate) fn scrub_typed<T: serde::Serialize + serde::de::DeserializeOwned>(
330        &self,
331        item: &mut T,
332    ) -> Result<bool, serde_json::Error> {
333        if self.is_empty() {
334            return Ok(false);
335        }
336        let mut value = serde_json::to_value(&*item)?;
337        if self.scrub_json(&mut value) {
338            *item = serde_json::from_value(value)?;
339            Ok(true)
340        } else {
341            Ok(false)
342        }
343    }
344}
345
346fn short_tool_credential(value: &serde_json::Value, credentials: &[String]) -> bool {
347    use serde_json::Value;
348
349    let contains = |text: &str| {
350        escapes::matches(text, |spelling| {
351            credentials.iter().any(|value| {
352                if value.chars().nth(MIN_TOOL_SUBSTRING_CHARS - 1).is_some() {
353                    return spelling.contains(value);
354                }
355                // A credential of one to three characters can also be an ordinary
356                // fragment of a word or identifier. Require a distinct token, not
357                // `a` in `payload` or `23` in a longer number.
358                let token_char = |c: char| c.is_alphanumeric() || c == '_';
359                spelling.char_indices().any(|(start, _)| {
360                    spelling[start..].starts_with(value)
361                        && !spelling[..start].ends_with(token_char)
362                        && !spelling[start + value.len()..].starts_with(token_char)
363                })
364            })
365        })
366    };
367    match value {
368        Value::String(text) => contains(text),
369        Value::Array(items) => items
370            .iter()
371            .any(|item| short_tool_credential(item, credentials)),
372        Value::Object(fields) => fields
373            .iter()
374            .any(|(key, value)| contains(key) || short_tool_credential(value, credentials)),
375        Value::Number(_) | Value::Bool(_) | Value::Null => credentials.contains(&value.to_string()),
376    }
377}
378
379/// Flatten decoded JSON argument values in their delivered order, not their wire syntax.
380pub(crate) fn append_scalar_values(value: &serde_json::Value, joined: &mut String) {
381    use serde_json::Value;
382    match value {
383        Value::String(text) => joined.push_str(text),
384        Value::Array(items) => items
385            .iter()
386            .for_each(|item| append_scalar_values(item, joined)),
387        Value::Object(fields) => fields
388            .values()
389            .for_each(|value| append_scalar_values(value, joined)),
390        Value::Number(_) | Value::Bool(_) => joined.push_str(&value.to_string()),
391        Value::Null => {}
392    }
393}