artifactize-provider 0.27.1

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
//! Line-preserving scrubbing across streaming chunks.

/// Placeholder substituted inline by [`StreamRedactor`] while preserving line structure.
pub const REDACTED: &str = "[REDACTED]";

/// Line-preserving cross-chunk secret redactor for text, tools, and diagnostics. Holds any trailing substring that could still begin
/// or extend into a longer known secret across chunk boundaries so neither split secrets nor
/// prefix-overlapping secrets leak unredacted. Unknown credentials read directly from disk by an
/// agent process cannot be detected here.
#[derive(Clone)]
pub struct StreamRedactor {
    secrets: std::sync::Arc<[String]>,
    pending: String,
    replacement: std::sync::Arc<str>,
}

impl StreamRedactor {
    pub fn new(secrets: impl IntoIterator<Item = String>) -> Self {
        let mut unique: Vec<String> = secrets
            .into_iter()
            .filter(|secret| !secret.is_empty())
            .collect();
        unique.sort_by(|left, right| right.len().cmp(&left.len()).then_with(|| left.cmp(right)));
        unique.dedup();
        let replacement = replacement(&unique).into();
        Self {
            secrets: unique.into(),
            replacement,
            pending: String::new(),
        }
    }

    pub(crate) fn withheld() -> Self {
        Self {
            replacement: "".into(),
            ..Self::new([])
        }
    }

    pub(super) fn marker(&self) -> &str {
        &self.replacement
    }

    /// Push a chunk and emit the safe prefix whose characters can no longer begin or extend into
    /// any known secret.
    pub fn push(&mut self, chunk: &str) -> String {
        if self.replacement.is_empty() {
            self.pending.clear();
            return String::new();
        }
        if self.secrets.is_empty() {
            return chunk.to_owned();
        }
        self.pending.push_str(chunk);
        self.redact_streaming(false)
    }

    /// In-flight credentials can rotate before the next chunk is released.
    pub(crate) fn update(&mut self, pattern: &Self) {
        self.secrets = pattern.secrets.clone();
        self.replacement = pattern.replacement.clone();
    }

    /// Emit what a display boundary inside the same stream (a tool call between two runs of
    /// prose, say) may show now: everything except any tail that could still begin or extend into
    /// a known secret. That tail stays pending so the stream's next chunk completes or clears it.
    pub fn release(&mut self) -> String {
        if self.replacement.is_empty() {
            self.pending.clear();
            return String::new();
        }
        if self.secrets.is_empty() {
            return std::mem::take(&mut self.pending);
        }
        self.redact_streaming(false)
    }

    /// Whether any trailing characters are currently buffered awaiting subsequent chunks.
    pub fn has_pending(&self) -> bool {
        !self.pending.is_empty()
    }

    /// Flush the trailing sliding window at turn end.
    pub fn flush(&mut self) -> String {
        if self.replacement.is_empty() {
            self.pending.clear();
            return String::new();
        }
        if self.secrets.is_empty() {
            return std::mem::take(&mut self.pending);
        }
        self.redact_streaming(true)
    }

    /// Redact a complete string in one shot while preserving newlines.
    pub fn redact_all(&self, text: &str) -> String {
        if self.replacement.is_empty() {
            return String::new();
        }
        if self.secrets.is_empty() || text.is_empty() {
            return text.to_owned();
        }
        let mut copy = Self {
            secrets: self.secrets.clone(),
            replacement: self.replacement.clone(),
            pending: text.to_owned(),
        };
        copy.redact_streaming(true)
    }

    /// Left-to-right longest-match redaction. While streaming (`!final_flush`), stops before any
    /// suffix that is a proper prefix of some known secret so a shorter prefix secret is never
    /// replaced before we know whether the next chunk completes a longer secret.
    fn redact_streaming(&mut self, final_flush: bool) -> String {
        if self.replacement.is_empty() {
            self.pending.clear();
            return String::new();
        }
        let mut out = String::new();
        let mut pos = 0;
        let len = self.pending.len();
        while pos < len {
            let rest = &self.pending[pos..];
            if !final_flush && self.could_extend_to_longer_secret(rest) {
                break;
            }
            if let Some(secret) = self.secrets.iter().find(|s| rest.starts_with(s.as_str())) {
                out.push_str(&self.replacement);
                pos += secret.len();
            } else {
                let ch = rest.chars().next().expect("pos < len");
                out.push(ch);
                pos += ch.len_utf8();
            }
        }
        self.pending.drain(..pos);
        out
    }

    fn could_extend_to_longer_secret(&self, rest: &str) -> bool {
        self.secrets
            .iter()
            .any(|secret| secret.len() > rest.len() && secret.starts_with(rest))
    }
}

// A replacement must neither contain a managed value nor complete one with its neighbors.
// Private-use characters provide a visible separator outside the ASCII key alphabet.
fn replacement(secrets: &[String]) -> String {
    let contains_secret = secrets.iter().any(|secret| REDACTED.contains(secret));
    if !contains_secret && !secrets.iter().any(|secret| secret.contains(['[', ']'])) {
        return REDACTED.to_owned();
    }
    // Unicode private-use blocks are valid text without assigned display meaning.
    const BMP_PRIVATE_USE: std::ops::RangeInclusive<char> = '\u{e000}'..='\u{f8ff}';
    const SUPPLEMENTARY_PRIVATE_USE: std::ops::RangeInclusive<char> = '\u{f0000}'..='\u{ffffd}';
    let separator = BMP_PRIVATE_USE
        .chain(SUPPLEMENTARY_PRIVATE_USE)
        .find(|character| !secrets.iter().any(|secret| secret.contains(*character)));
    match (separator, contains_secret) {
        (Some(separator), false) => format!("{separator}{REDACTED}{separator}"),
        (Some(separator), true) => separator.to_string(),
        // Withhold text if the inventory leaves no safe separator.
        (None, _) => String::new(),
    }
}

#[cfg(test)]
mod tests;