rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What a probe keeps out of its answer: every value it starts a server
//! with, so a server that echoes one, in its standard error, an error, or
//! its name, version or tools, does not show it to the client.

use std::sync::{Arc, Mutex, PoisonError};

/// The values a probe started a server with, which it keeps out of what it
/// returns. Clones share them. Not `Debug`: it holds secret values.
#[derive(Clone, Default)]
pub(super) struct Served(Arc<Mutex<Vec<Hidden>>>);

/// Where a value a server is given comes from, which says how it is hidden.
#[derive(Clone, Copy)]
pub(super) enum Origin {
    /// A stored or typed-in secret: hidden wherever it occurs.
    Secret,
    /// The server's config: its `env` or `headers`, or a variable its
    /// `env_from_env` or `headers_from_env` reads. Hidden wherever it
    /// occurs, unless shorter than [`SHORT_VALUE_BYTES`].
    Config,
}

/// One value kept out of the answer, and where.
struct Hidden {
    text: String,
    reach: Reach,
}

/// Where a value is hidden in what a server writes.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Reach {
    /// Every place it occurs.
    Anywhere,
    /// Only where it stands alone, not inside a longer token: a short
    /// config value such as `DEBUG=1`, which hidden everywhere would hide
    /// every `1` the server wrote.
    Alone,
}

/// The shortest config value hidden everywhere, and the shortest word of a
/// value hidden on its own. Credentials are longer: an AWS access key id is
/// 20 bytes, a GitHub token 40, a Stripe secret key over 30, so a key never
/// falls under it, while flags, ports, levels and auth schemes (`1`,
/// `true`, `8080`, `debug`, `Bearer`) do.
const SHORT_VALUE_BYTES: usize = 8;

impl Served {
    /// Keeps `value`, one the server is given, out of the answer as its
    /// `origin` says. A value of several words, such as an `Authorization`
    /// header's `Bearer <token>`, also has each word of at least
    /// [`SHORT_VALUE_BYTES`] hidden wherever it occurs, since a server may
    /// echo the token alone.
    pub(super) fn hide(&self, value: &str, origin: Origin) {
        if value.is_empty() {
            return;
        }
        let reach = match origin {
            Origin::Config if value.len() < SHORT_VALUE_BYTES => Reach::Alone,
            Origin::Secret | Origin::Config => Reach::Anywhere,
        };
        let words = value.split_whitespace().collect::<Vec<_>>();
        let long_words = words
            .iter()
            .filter(|word| words.len() > 1 && word.len() >= SHORT_VALUE_BYTES)
            .map(|word| Hidden {
                text: (*word).to_owned(),
                reach: Reach::Anywhere,
            });
        let mut kept = self.lock();
        kept.push(Hidden {
            text: value.to_owned(),
            reach,
        });
        kept.extend(long_words);
    }

    /// `tail`, the end of a server's standard error, as text a person may
    /// see, redacted as [`Self::redact`] does. When it was `cut` from a
    /// longer output, a start that is the end of a value hidden anywhere,
    /// whose beginning the cut dropped, is redacted too.
    pub(super) fn tail_text(&self, tail: &[u8], cut: bool) -> Option<String> {
        let tail = self.covered(tail, cut);
        let text = String::from_utf8_lossy(&tail);
        let text = text.trim();
        (!text.is_empty()).then(|| text.to_owned())
    }

    /// `text` with each value kept out replaced by `[redacted]`. Every
    /// place a value occurs is found first, overlapping ones included, so
    /// two values that share bytes are both hidden whole.
    pub(super) fn redact(&self, text: &str) -> String {
        String::from_utf8_lossy(&self.covered(text.as_bytes(), /*cut*/ false)).into_owned()
    }

    /// `bytes` with each run that is part of a value kept out replaced by
    /// one `[redacted]`: every occurrence of a value, or, for a short config
    /// value, every one that stands alone, and, when `cut`, the longest
    /// start that is the end of a value hidden anywhere.
    fn covered(&self, bytes: &[u8], cut: bool) -> Vec<u8> {
        let values = self.lock();
        let mut hidden = vec![false; bytes.len()];
        for kept in values.iter() {
            let value = kept.text.as_bytes();
            for start in 0..bytes.len() {
                let end = start + value.len();
                let alone = || {
                    !joins(bytes, start.checked_sub(1), start.checked_sub(2))
                        && !joins(bytes, Some(end), Some(end + 1))
                };
                if bytes[start..].starts_with(value) && (kept.reach == Reach::Anywhere || alone()) {
                    hidden[start..end].fill(true);
                }
            }
            if cut && kept.reach == Reach::Anywhere {
                let fragment = (1..value.len())
                    .map(|from| &value[from..])
                    .find(|end| bytes.starts_with(end));
                if let Some(end) = fragment {
                    hidden[..end.len()].fill(true);
                }
            }
        }
        let mut out = Vec::with_capacity(bytes.len());
        for (index, &byte) in bytes.iter().enumerate() {
            match (hidden[index], index > 0 && hidden[index - 1]) {
                (false, _) => out.push(byte),
                (true, false) => out.extend_from_slice(b"[redacted]"),
                (true, true) => {}
            }
        }
        out
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Hidden>> {
        self.0.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// Whether the byte at `at`, beside a short value, makes it part of a
/// longer token: a letter, a digit or `_`, or a `.` or `-` with a letter or
/// digit at `beyond`, as in `1.0.0`, `127.0.0.1` or `v-1`. A `.` that ends
/// a sentence does not.
fn joins(bytes: &[u8], at: Option<usize>, beyond: Option<usize>) -> bool {
    let byte = |index: Option<usize>| index.and_then(|index| bytes.get(index)).copied();
    let word = |byte: u8| byte.is_ascii_alphanumeric() || byte == b'_';
    match byte(at) {
        Some(b'.' | b'-') => byte(beyond).is_some_and(word),
        Some(other) => word(other),
        None => false,
    }
}

#[cfg(test)]
#[path = "probe_redaction_tests.rs"]
mod tests;