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
74    /// HTTP: the saved API keys and custom keys, and the tokens of the Codex CLI's own store.
75    pub fn read(providers: Option<&crate::auth::Location>) -> Self {
76        Self::read_values(providers).unwrap_or_else(|_| Self::withheld())
77    }
78
79    /// Read credentials for a boundary that must report an unavailable inventory.
80    pub fn try_read(providers: Option<&crate::auth::Location>) -> Result<Self, String> {
81        // A refused location is harmless only when it holds no credential file.
82        if let Some(location) = providers {
83            location.refusal(crate::auth::providers::FILE)?;
84        }
85        Self::read_values(providers)
86    }
87
88    fn read_values(providers: Option<&crate::auth::Location>) -> Result<Self, String> {
89        let providers = crate::auth::providers::secret_values(providers)?;
90        let codex = crate::auth::codex::secret_values()?;
91        Ok(Self::new(providers.chain(codex)))
92    }
93
94    /// The keys saved at `providers` only, for Chat: its agents keep their own sign-ins, which
95    /// artifactize does not read, while the Codex reviewer's sign-in is in [`Self::read`].
96    pub fn read_keys(providers: Option<&crate::auth::Location>) -> Self {
97        crate::auth::providers::secret_values(providers)
98            .map(Self::new)
99            .unwrap_or_else(|_| Self::withheld())
100    }
101
102    pub fn new(values: impl IntoIterator<Item = String>) -> Self {
103        let mut secrets = Self::default();
104        for value in values {
105            secrets.include(value);
106        }
107        secrets
108    }
109
110    pub fn include(&mut self, value: String) {
111        if value.is_empty() {
112            return;
113        }
114        if value.chars().nth(PIECE - 1).is_none() {
115            if !self.short_values.contains(&value) {
116                self.short_values.push(value);
117            }
118            return;
119        }
120        if self.values.contains(&value) {
121            return;
122        }
123        // The same credential may reach an error via Rust Debug or a structured JSON
124        // string. Match both spellings without the surrounding quotation marks.
125        let debug = format!("{value:?}");
126        let json = serde_json::to_string(&value).expect("string is serializable");
127        for encoded in [&debug[1..debug.len() - 1], &json[1..json.len() - 1]] {
128            if encoded != value && !self.values.iter().any(|known| known == encoded) {
129                self.values.push(encoded.to_owned());
130            }
131        }
132        self.values.push(value);
133    }
134
135    /// Whether there is nothing to scrub from ordinary text.
136    pub fn is_empty(&self) -> bool {
137        !self.unavailable && self.values.is_empty()
138    }
139
140    pub fn merge(&mut self, other: Self) {
141        self.unavailable |= other.unavailable;
142        for (known, observed) in [
143            (&mut self.values, other.values),
144            (&mut self.short_values, other.short_values),
145        ] {
146            for value in observed {
147                if !known.contains(&value) {
148                    known.push(value);
149                }
150            }
151        }
152    }
153
154    /// Unlike text scrubbing, structured tool arguments must not carry short credentials
155    /// either. Check actual keys and values, not incidental JSON syntax or tool metadata.
156    pub(crate) fn contains_short_tool_credential(&self, arguments: &serde_json::Value) -> bool {
157        !self.short_values.is_empty() && short_tool_credential(arguments, &self.short_values)
158    }
159
160    /// Include additional caller-owned secrets without taking ownership of their source.
161    pub fn stream_with(&self, additional: impl IntoIterator<Item = String>) -> StreamRedactor {
162        if self.unavailable {
163            return StreamRedactor::withheld();
164        }
165        StreamRedactor::new(self.values.iter().cloned().chain(additional))
166    }
167
168    pub fn stream(&self) -> StreamRedactor {
169        self.stream_with(std::iter::empty())
170    }
171
172    pub fn contains(&self, text: &str) -> bool {
173        self.unavailable && !text.is_empty()
174            || !self.values.is_empty()
175                && escapes::matches(text, |text| {
176                    self.values.iter().any(|secret| text.contains(secret))
177                })
178    }
179
180    /// Remove managed values and their escaped spellings in the text's own syntax
181    /// (for example, JSON or URL escapes), not alternate encodings such as Base64.
182    pub fn scrub(&self, text: &str) -> String {
183        if !self.contains(text) {
184            return text.to_owned();
185        }
186        if !text.contains(ESCAPE_MARKERS) {
187            return self.stream().redact_all(text);
188        }
189        let mut clean = text.to_owned();
190        self.scrub_escaped(text, &mut [&mut clean]);
191        clean
192    }
193
194    /// The suffix of unescaped text that could overlap a currently known secret.
195    /// The caller must still retain the earlier text for future inventory updates.
196    pub(crate) fn overlap_tail<'a>(&self, text: &'a str) -> &'a str {
197        let max = self.values.iter().map(String::len).max().unwrap_or(0);
198        let start = text.len().saturating_sub(max.saturating_sub(1));
199        &text[text.ceil_char_boundary(start)..]
200    }
201
202    /// Scrub text items as one display stream, retaining their order and item count.
203    pub(crate) fn scrub_joined(&self, parts: &mut [&mut String]) {
204        if parts.is_empty() || self.is_empty() {
205            return;
206        }
207        let joined: String = parts.iter().map(|part| part.as_str()).collect();
208        if !self.contains(&joined) {
209            return;
210        }
211        if joined.contains(ESCAPE_MARKERS) {
212            self.scrub_escaped(&joined, parts);
213            return;
214        }
215        let mut stream = self.stream();
216        for part in parts.iter_mut() {
217            **part = stream.push(part);
218        }
219        parts
220            .last_mut()
221            .expect("checked nonempty")
222            .push_str(&stream.flush());
223    }
224
225    fn scrub_escaped(&self, joined: &str, parts: &mut [&mut String]) {
226        let ranges = (!self.unavailable)
227            .then(|| escapes::spans(joined, &self.values))
228            .flatten();
229        let Some(ranges) = ranges else {
230            parts.iter_mut().for_each(|part| part.clear());
231            return;
232        };
233        let pattern = self.stream();
234        let marker = pattern.marker();
235        let mut offset = 0;
236        let mut ranges = ranges.into_iter().peekable();
237        for part in parts.iter_mut() {
238            let end = offset + part.len();
239            let mut cursor = offset;
240            let mut clean = String::new();
241            while let Some(range) = ranges.peek().filter(|range| range.start < end) {
242                if range.start >= cursor {
243                    clean.push_str(&joined[cursor..range.start]);
244                    clean.push_str(marker);
245                }
246                cursor = end.min(range.end);
247                if range.end > end {
248                    break;
249                }
250                ranges.next();
251            }
252            clean.push_str(&joined[cursor..end]);
253            **part = clean;
254            offset = end;
255        }
256        let clean: String = parts.iter().map(|part| part.as_str()).collect();
257        if self.contains(&clean) {
258            // Removing a range may change the interpretation of surrounding escapes.
259            parts.iter_mut().for_each(|part| part.clear());
260        }
261    }
262
263    pub(crate) fn contains_piece(&self, text: &str) -> bool {
264        self.unavailable && !text.is_empty()
265            || !self.values.is_empty()
266                && escapes::matches(text, |spelling| {
267                    let text: String = spelling.chars().filter(|c| !c.is_control()).collect();
268                    self.values.iter().any(|secret| holds_piece(&text, secret))
269                })
270    }
271
272    pub fn diagnostic(&self, text: &str, max_chars: usize) -> String {
273        if self.unavailable {
274            return String::new();
275        }
276        server_text(
277            text,
278            &self.values.iter().map(String::as_str).collect::<Vec<_>>(),
279            max_chars,
280        )
281    }
282
283    /// Scrub string values and object keys before an external JSON payload crosses a boundary.
284    pub fn scrub_json(&self, value: &mut serde_json::Value) -> bool {
285        use serde_json::Value;
286        match value {
287            Value::String(text) if self.contains(text) => {
288                *text = self.scrub(text);
289                true
290            }
291            Value::Number(_) | Value::Bool(_) if self.contains(&value.to_string()) => {
292                *value = Value::Null;
293                true
294            }
295            Value::Array(items) => {
296                let mut changed = false;
297                for item in items {
298                    changed |= self.scrub_json(item);
299                }
300                changed
301            }
302            Value::Object(fields) => {
303                let mut changed = false;
304                let mut suspect = Vec::new();
305                for (key, value) in fields.iter_mut() {
306                    changed = self.scrub_json(value) || changed;
307                    if self.contains(key) {
308                        suspect.push(key.clone());
309                    }
310                }
311                for key in suspect {
312                    let value = fields
313                        .remove(&key)
314                        .expect("observed field is still present");
315                    fields.entry(self.scrub(&key)).or_insert(value);
316                    changed = true;
317                }
318                changed
319            }
320            _ => false,
321        }
322    }
323
324    /// Check typed payloads (including decoded structured strings) without logging them or
325    /// asking a caller to enumerate provider-specific fields.
326    pub(crate) fn scrub_typed<T: serde::Serialize + serde::de::DeserializeOwned>(
327        &self,
328        item: &mut T,
329    ) -> Result<bool, serde_json::Error> {
330        if self.is_empty() {
331            return Ok(false);
332        }
333        let mut value = serde_json::to_value(&*item)?;
334        if self.scrub_json(&mut value) {
335            *item = serde_json::from_value(value)?;
336            Ok(true)
337        } else {
338            Ok(false)
339        }
340    }
341}
342
343fn short_tool_credential(value: &serde_json::Value, credentials: &[String]) -> bool {
344    use serde_json::Value;
345
346    let contains = |text: &str| {
347        escapes::matches(text, |spelling| {
348            credentials.iter().any(|value| {
349                if value.chars().nth(MIN_TOOL_SUBSTRING_CHARS - 1).is_some() {
350                    return spelling.contains(value);
351                }
352                // A credential of one to three characters can also be an ordinary
353                // fragment of a word or identifier. Require a distinct token, not
354                // `a` in `payload` or `23` in a longer number.
355                let token_char = |c: char| c.is_alphanumeric() || c == '_';
356                spelling.char_indices().any(|(start, _)| {
357                    spelling[start..].starts_with(value)
358                        && !spelling[..start].ends_with(token_char)
359                        && !spelling[start + value.len()..].starts_with(token_char)
360                })
361            })
362        })
363    };
364    match value {
365        Value::String(text) => contains(text),
366        Value::Array(items) => items
367            .iter()
368            .any(|item| short_tool_credential(item, credentials)),
369        Value::Object(fields) => fields
370            .iter()
371            .any(|(key, value)| contains(key) || short_tool_credential(value, credentials)),
372        Value::Number(_) | Value::Bool(_) | Value::Null => credentials.contains(&value.to_string()),
373    }
374}
375
376/// Flatten decoded JSON argument values in their delivered order, not their wire syntax.
377pub(crate) fn append_scalar_values(value: &serde_json::Value, joined: &mut String) {
378    use serde_json::Value;
379    match value {
380        Value::String(text) => joined.push_str(text),
381        Value::Array(items) => items
382            .iter()
383            .for_each(|item| append_scalar_values(item, joined)),
384        Value::Object(fields) => fields
385            .values()
386            .for_each(|value| append_scalar_values(value, joined)),
387        Value::Number(_) | Value::Bool(_) => joined.push_str(&value.to_string()),
388        Value::Null => {}
389    }
390}