artifactize-provider 0.27.1

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
//! The one rule for server text that is about to be shown, saved or logged while a request
//! carried a credential (a bearer token, an API key): a store, provider or proxy may echo the
//! credential back, whole or split, inside an error. Control characters go first (so a split
//! cannot be rejoined by dropping them afterwards), then text holding any piece of a
//! credential is withheld whole, and only then is the rest clipped.

/// Consecutive characters of a credential that count as a piece of it. Eight characters of a
/// random token are already too many to guess from, while shorter runs (a `sk-` prefix, a common
/// word) occur in ordinary error text and would withhold harmless messages.
const PIECE: usize = 8;

/// Below this length, a substring match would make ordinary tool keys and arguments
/// such as `payload` or `data` collide with one-character credentials.
const MIN_TOOL_SUBSTRING_CHARS: usize = 4;

/// What is shown instead of server text that held part of a credential.
pub const WITHHELD: &str = "[withheld: it contained part of the credential sent]";

/// `text` from a server, safe to show: no control characters, no piece of `secrets`, at most
/// `max_chars` characters.
pub fn server_text(text: &str, secrets: &[&str], max_chars: usize) -> String {
    let text: String = text.chars().filter(|c| !c.is_control()).collect();
    if !secrets.is_empty()
        && escapes::matches(&text, |spelling| {
            let visible: String = spelling.chars().filter(|c| !c.is_control()).collect();
            secrets.iter().any(|secret| holds_piece(&visible, secret))
        })
    {
        return StreamRedactor::new(secrets.iter().map(|value| (*value).to_owned()))
            .redact_all(WITHHELD);
    }
    text.chars().take(max_chars).collect()
}

/// `text` contains `PIECE` consecutive characters of `secret` (all of a shorter one).
fn holds_piece(text: &str, secret: &str) -> bool {
    let secret: Vec<char> = secret.chars().filter(|c| !c.is_control()).collect();
    if secret.is_empty() {
        return false;
    }
    let size = PIECE.min(secret.len());
    secret
        .windows(size)
        .any(|piece| text.contains(&piece.iter().collect::<String>()))
}

#[cfg(test)]
mod tests;

mod escapes;
pub(crate) use escapes::MARKERS as ESCAPE_MARKERS;
pub(crate) mod history;
mod stream;
pub use stream::{REDACTED, StreamRedactor};

/// Managed credential values. Short values are checked at the tool-argument
/// boundary, but are not used to scrub ordinary text or payloads.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Inventory {
    values: Vec<String>,
    short_values: Vec<String>,
    unavailable: bool,
}

impl Inventory {
    pub(crate) fn withheld() -> Self {
        Self {
            unavailable: true,
            ..Self::default()
        }
    }

    /// Read the credentials of this profile without authenticating, refreshing, or initiating HTTP.
    pub fn read(
        providers: Option<&crate::auth::Location>,
        codex: Option<&crate::auth::Location>,
    ) -> Self {
        Self::read_values(providers, codex).unwrap_or_else(|_| Self::withheld())
    }

    /// Read credentials for a boundary that must report an unavailable inventory.
    pub fn try_read(
        providers: Option<&crate::auth::Location>,
        codex: Option<&crate::auth::Location>,
    ) -> Result<Self, String> {
        // A refused location is harmless only when it holds no credential file.
        if let Some(location) = providers {
            location.refusal(crate::auth::providers::FILE)?;
        }
        if let Some(location) = codex {
            location.refusal(crate::auth::codex::CREDENTIALS)?;
        }
        Self::read_values(providers, codex)
    }

    fn read_values(
        providers: Option<&crate::auth::Location>,
        codex: Option<&crate::auth::Location>,
    ) -> Result<Self, String> {
        let providers = crate::auth::providers::secret_values(providers)?;
        let codex = crate::auth::codex::secret_values(codex)?;
        Ok(Self::new(providers.chain(codex)))
    }

    pub fn new(values: impl IntoIterator<Item = String>) -> Self {
        let mut secrets = Self::default();
        for value in values {
            secrets.include(value);
        }
        secrets
    }

    pub fn include(&mut self, value: String) {
        if value.is_empty() {
            return;
        }
        if value.chars().nth(PIECE - 1).is_none() {
            if !self.short_values.contains(&value) {
                self.short_values.push(value);
            }
            return;
        }
        if self.values.contains(&value) {
            return;
        }
        // The same credential may reach an error via Rust Debug or a structured JSON
        // string. Match both spellings without the surrounding quotation marks.
        let debug = format!("{value:?}");
        let json = serde_json::to_string(&value).expect("string is serializable");
        for encoded in [&debug[1..debug.len() - 1], &json[1..json.len() - 1]] {
            if encoded != value && !self.values.iter().any(|known| known == encoded) {
                self.values.push(encoded.to_owned());
            }
        }
        self.values.push(value);
    }

    /// Whether there is nothing to scrub from ordinary text.
    pub fn is_empty(&self) -> bool {
        !self.unavailable && self.values.is_empty()
    }

    pub fn merge(&mut self, other: Self) {
        self.unavailable |= other.unavailable;
        for (known, observed) in [
            (&mut self.values, other.values),
            (&mut self.short_values, other.short_values),
        ] {
            for value in observed {
                if !known.contains(&value) {
                    known.push(value);
                }
            }
        }
    }

    /// Unlike text scrubbing, structured tool arguments must not carry short credentials
    /// either. Check actual keys and values, not incidental JSON syntax or tool metadata.
    pub(crate) fn contains_short_tool_credential(&self, arguments: &serde_json::Value) -> bool {
        !self.short_values.is_empty() && short_tool_credential(arguments, &self.short_values)
    }

    /// Include additional caller-owned secrets without taking ownership of their source.
    pub fn stream_with(&self, additional: impl IntoIterator<Item = String>) -> StreamRedactor {
        if self.unavailable {
            return StreamRedactor::withheld();
        }
        StreamRedactor::new(self.values.iter().cloned().chain(additional))
    }

    pub fn stream(&self) -> StreamRedactor {
        self.stream_with(std::iter::empty())
    }

    pub fn contains(&self, text: &str) -> bool {
        self.unavailable && !text.is_empty()
            || !self.values.is_empty()
                && escapes::matches(text, |text| {
                    self.values.iter().any(|secret| text.contains(secret))
                })
    }

    /// Remove managed values and their escaped spellings in the text's own syntax
    /// (for example, JSON or URL escapes), not alternate encodings such as Base64.
    pub fn scrub(&self, text: &str) -> String {
        if !self.contains(text) {
            return text.to_owned();
        }
        if !text.contains(ESCAPE_MARKERS) {
            return self.stream().redact_all(text);
        }
        let mut clean = text.to_owned();
        self.scrub_escaped(text, &mut [&mut clean]);
        clean
    }

    /// The suffix of unescaped text that could overlap a currently known secret.
    /// The caller must still retain the earlier text for future inventory updates.
    pub(crate) fn overlap_tail<'a>(&self, text: &'a str) -> &'a str {
        let max = self.values.iter().map(String::len).max().unwrap_or(0);
        let start = text.len().saturating_sub(max.saturating_sub(1));
        &text[text.ceil_char_boundary(start)..]
    }

    /// Scrub text items as one display stream, retaining their order and item count.
    pub(crate) fn scrub_joined(&self, parts: &mut [&mut String]) {
        if parts.is_empty() || self.is_empty() {
            return;
        }
        let joined: String = parts.iter().map(|part| part.as_str()).collect();
        if !self.contains(&joined) {
            return;
        }
        if joined.contains(ESCAPE_MARKERS) {
            self.scrub_escaped(&joined, parts);
            return;
        }
        let mut stream = self.stream();
        for part in parts.iter_mut() {
            **part = stream.push(part);
        }
        parts
            .last_mut()
            .expect("checked nonempty")
            .push_str(&stream.flush());
    }

    fn scrub_escaped(&self, joined: &str, parts: &mut [&mut String]) {
        let ranges = (!self.unavailable)
            .then(|| escapes::spans(joined, &self.values))
            .flatten();
        let Some(ranges) = ranges else {
            parts.iter_mut().for_each(|part| part.clear());
            return;
        };
        let pattern = self.stream();
        let marker = pattern.marker();
        let mut offset = 0;
        let mut ranges = ranges.into_iter().peekable();
        for part in parts.iter_mut() {
            let end = offset + part.len();
            let mut cursor = offset;
            let mut clean = String::new();
            while let Some(range) = ranges.peek().filter(|range| range.start < end) {
                if range.start >= cursor {
                    clean.push_str(&joined[cursor..range.start]);
                    clean.push_str(marker);
                }
                cursor = end.min(range.end);
                if range.end > end {
                    break;
                }
                ranges.next();
            }
            clean.push_str(&joined[cursor..end]);
            **part = clean;
            offset = end;
        }
        let clean: String = parts.iter().map(|part| part.as_str()).collect();
        if self.contains(&clean) {
            // Removing a range may change the interpretation of surrounding escapes.
            parts.iter_mut().for_each(|part| part.clear());
        }
    }

    pub(crate) fn contains_piece(&self, text: &str) -> bool {
        self.unavailable && !text.is_empty()
            || !self.values.is_empty()
                && escapes::matches(text, |spelling| {
                    let text: String = spelling.chars().filter(|c| !c.is_control()).collect();
                    self.values.iter().any(|secret| holds_piece(&text, secret))
                })
    }

    pub fn diagnostic(&self, text: &str, max_chars: usize) -> String {
        if self.unavailable {
            return String::new();
        }
        server_text(
            text,
            &self.values.iter().map(String::as_str).collect::<Vec<_>>(),
            max_chars,
        )
    }

    /// Scrub string values and object keys before an external JSON payload crosses a boundary.
    pub fn scrub_json(&self, value: &mut serde_json::Value) -> bool {
        use serde_json::Value;
        match value {
            Value::String(text) if self.contains(text) => {
                *text = self.scrub(text);
                true
            }
            Value::Number(_) | Value::Bool(_) if self.contains(&value.to_string()) => {
                *value = Value::Null;
                true
            }
            Value::Array(items) => {
                let mut changed = false;
                for item in items {
                    changed |= self.scrub_json(item);
                }
                changed
            }
            Value::Object(fields) => {
                let mut changed = false;
                let mut suspect = Vec::new();
                for (key, value) in fields.iter_mut() {
                    changed = self.scrub_json(value) || changed;
                    if self.contains(key) {
                        suspect.push(key.clone());
                    }
                }
                for key in suspect {
                    let value = fields
                        .remove(&key)
                        .expect("observed field is still present");
                    fields.entry(self.scrub(&key)).or_insert(value);
                    changed = true;
                }
                changed
            }
            _ => false,
        }
    }

    /// Check typed payloads (including decoded structured strings) without logging them or
    /// asking a caller to enumerate provider-specific fields.
    pub(crate) fn scrub_typed<T: serde::Serialize + serde::de::DeserializeOwned>(
        &self,
        item: &mut T,
    ) -> Result<bool, serde_json::Error> {
        if self.is_empty() {
            return Ok(false);
        }
        let mut value = serde_json::to_value(&*item)?;
        if self.scrub_json(&mut value) {
            *item = serde_json::from_value(value)?;
            Ok(true)
        } else {
            Ok(false)
        }
    }
}

fn short_tool_credential(value: &serde_json::Value, credentials: &[String]) -> bool {
    use serde_json::Value;

    let contains = |text: &str| {
        escapes::matches(text, |spelling| {
            credentials.iter().any(|value| {
                if value.chars().nth(MIN_TOOL_SUBSTRING_CHARS - 1).is_some() {
                    return spelling.contains(value);
                }
                // A credential of one to three characters can also be an ordinary
                // fragment of a word or identifier. Require a distinct token, not
                // `a` in `payload` or `23` in a longer number.
                let token_char = |c: char| c.is_alphanumeric() || c == '_';
                spelling.char_indices().any(|(start, _)| {
                    spelling[start..].starts_with(value)
                        && !spelling[..start].ends_with(token_char)
                        && !spelling[start + value.len()..].starts_with(token_char)
                })
            })
        })
    };
    match value {
        Value::String(text) => contains(text),
        Value::Array(items) => items
            .iter()
            .any(|item| short_tool_credential(item, credentials)),
        Value::Object(fields) => fields
            .iter()
            .any(|(key, value)| contains(key) || short_tool_credential(value, credentials)),
        Value::Number(_) | Value::Bool(_) | Value::Null => credentials.contains(&value.to_string()),
    }
}

/// Flatten decoded JSON argument values in their delivered order, not their wire syntax.
pub(crate) fn append_scalar_values(value: &serde_json::Value, joined: &mut String) {
    use serde_json::Value;
    match value {
        Value::String(text) => joined.push_str(text),
        Value::Array(items) => items
            .iter()
            .for_each(|item| append_scalar_values(item, joined)),
        Value::Object(fields) => fields
            .values()
            .for_each(|value| append_scalar_values(value, joined)),
        Value::Number(_) | Value::Bool(_) => joined.push_str(&value.to_string()),
        Value::Null => {}
    }
}