surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
//! The redaction pass every log line and the diagnostic report go through
//! (SPEC 4.5): the data folder and the profile folder become placeholders,
//! and anything that may be a credential is masked.

use std::path::Path;
use std::sync::LazyLock;

use crate::env::{Env, Os};
use crate::secrets::classify::{find_tokens, is_high_entropy, is_sensitive_key};
use crate::secrets::scanner::SecretMemory;

/// What a masked value becomes.
pub const MASK: &str = "***";
/// Placeholder of the data folder.
pub const HOME_PLACEHOLDER: &str = "<SURJECTION_HOME>";
/// Shortest environment value masked wherever it appears.
const MIN_ENV_VALUE_LEN: usize = 8;
/// Shortest word the entropy rule masks.
const MIN_RANDOM_WORD_LEN: usize = 20;

/// Keyed hashes of every secret value this process resolved, for the
/// redaction pass; never the values themselves.
static MEMORY: LazyLock<Option<SecretMemory>> = LazyLock::new(|| SecretMemory::new().ok());

fn memory() -> Option<&'static SecretMemory> {
    MEMORY.as_ref()
}

/// Remembers a resolved secret value so no log line or report shows it.
/// Called by [`SecretMemory::record`].
pub fn remember(value: &str) {
    if let Some(memory) = memory() {
        memory.record_here(value);
    }
}

/// Redacts text for the log and the diagnostic report.
#[derive(Debug, Clone)]
pub struct Redactor {
    /// Folder spellings and their placeholder, the data folder first (it
    /// usually lies inside the profile).
    roots: Vec<(String, &'static str)>,
    /// Windows paths compare without case.
    fold_case: bool,
    /// Values of environment variables with a sensitive name, longest
    /// first.
    values: Vec<String>,
}

impl Redactor {
    pub fn new(env: &Env, surjection_home: &Path) -> Self {
        let mut roots = Vec::new();
        for (root, placeholder) in [(surjection_home, HOME_PLACEHOLDER), (env.home(), "~")] {
            let native = root.to_string_lossy().into_owned();
            let native = native.trim_end_matches(['/', '\\']).to_owned();
            if native.is_empty() {
                continue;
            }
            let forward = native.replace('\\', "/");
            let doubled = native.replace('\\', "\\\\");
            for form in [doubled, native, forward] {
                if !roots.iter().any(|(known, _)| *known == form) {
                    roots.push((form, placeholder));
                }
            }
        }
        let mut values: Vec<String> = env
            .vars()
            .filter(|(name, _)| is_sensitive_key(name))
            .filter_map(|(_, value)| value.to_str())
            .map(str::trim)
            .filter(|value| value.len() >= MIN_ENV_VALUE_LEN)
            .map(str::to_owned)
            .collect();
        values.sort_by_key(|value| std::cmp::Reverse(value.len()));
        values.dedup();
        Self {
            roots,
            fold_case: env.os() == Os::Windows,
            values,
        }
    }

    /// `text` with secrets masked and absolute folders replaced.
    pub fn redact(&self, text: &str) -> String {
        let mut out = text.to_owned();
        for value in &self.values {
            out = out.replace(value.as_str(), MASK);
        }
        out = mask_remembered(&out);
        out = redact_urls(&out);
        for (form, placeholder) in &self.roots {
            out = replace_root(&out, form, placeholder, self.fold_case);
        }
        out = mask_tokens(&out);
        mask_random_words(&out)
    }
}

/// Masks every value [`remember`] saw.
fn mask_remembered(text: &str) -> String {
    let Some(memory) = memory() else {
        return text.to_owned();
    };
    if memory.is_empty() {
        return text.to_owned();
    }
    let mut out = text.to_owned();
    while let Some(range) = memory.find(out.as_bytes()) {
        if !out.is_char_boundary(range.start) || !out.is_char_boundary(range.end) {
            break;
        }
        out.replace_range(range, MASK);
    }
    out
}

/// In every `scheme://` URL: the userinfo becomes `***@` and the query
/// `?***`.
fn redact_urls(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(sep) = rest.find("://") {
        let (head, tail) = rest.split_at(sep + 3);
        out.push_str(head);
        let end = tail
            .find(|c: char| c.is_whitespace() || "\"'<>`".contains(c))
            .unwrap_or(tail.len());
        let (url, after) = tail.split_at(end);
        let authority_end = url.find(['/', '?', '#']).unwrap_or(url.len());
        let (authority, path) = url.split_at(authority_end);
        match authority.rfind('@') {
            Some(at) => {
                out.push_str(MASK);
                out.push_str(&authority[at..]);
            }
            None => out.push_str(authority),
        }
        match path.find('?') {
            Some(query) => {
                out.push_str(&path[..query]);
                out.push('?');
                out.push_str(MASK);
                if let Some(fragment) = path[query..].find('#') {
                    out.push_str(&path[query + fragment..]);
                }
            }
            None => out.push_str(path),
        }
        rest = after;
    }
    out.push_str(rest);
    out
}

/// Replaces `form` (a folder) with `placeholder` where it is a whole path
/// prefix: the next character is a separator or ends the path.
fn replace_root(text: &str, form: &str, placeholder: &str, fold_case: bool) -> String {
    let bytes = text.as_bytes();
    let needle = form.as_bytes();
    let mut out = String::with_capacity(text.len());
    let mut copied = 0;
    let mut i = 0;
    while i + needle.len() <= bytes.len() {
        let candidate = &bytes[i..i + needle.len()];
        let matches = if fold_case {
            candidate.eq_ignore_ascii_case(needle)
        } else {
            candidate == needle
        };
        let next = bytes.get(i + needle.len()).copied();
        let whole = !next.is_some_and(|b| b.is_ascii_alphanumeric() || b"_-.".contains(&b));
        if matches && whole && text.is_char_boundary(i) {
            out.push_str(&text[copied..i]);
            out.push_str(placeholder);
            i += needle.len();
            copied = i;
        } else {
            i += 1;
        }
    }
    out.push_str(&text[copied..]);
    out
}

/// Masks known token formats (`ghp_...`, `sk-...`, JWTs).
fn mask_tokens(text: &str) -> String {
    let mut out = text.to_owned();
    for hit in find_tokens(text).into_iter().rev() {
        out.replace_range(hit.range, MASK);
    }
    out
}

fn is_word_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b"_-+".contains(&b)
}

/// Masks long random-looking words with letters and digits; ULIDs stay.
fn mask_random_words(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut out = String::with_capacity(text.len());
    let mut copied = 0;
    let mut i = 0;
    while i < bytes.len() {
        if !is_word_byte(bytes[i]) {
            i += 1;
            continue;
        }
        let start = i;
        while i < bytes.len() && is_word_byte(bytes[i]) {
            i += 1;
        }
        let word = &text[start..i];
        if looks_random(word) {
            out.push_str(&text[copied..start]);
            out.push_str(MASK);
            copied = i;
        }
    }
    out.push_str(&text[copied..]);
    out
}

fn looks_random(word: &str) -> bool {
    word.len() >= MIN_RANDOM_WORD_LEN
        && word.bytes().any(|b| b.is_ascii_digit())
        && word.bytes().any(|b| b.is_ascii_alphabetic())
        && !is_ulid(word)
        && is_high_entropy(word)
}

/// 26 characters of Crockford base32, upper case (apply ids, store ids).
fn is_ulid(word: &str) -> bool {
    word.len() == 26
        && word
            .bytes()
            .all(|b| b.is_ascii_digit() || (b.is_ascii_uppercase() && !b"ILOU".contains(&b)))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn url_userinfo_and_query_are_masked() {
        assert_eq!(
            redact_urls("got https://me:pw@example.com/a/b?token=x&q=y#top end"),
            "got https://***@example.com/a/b?***#top end"
        );
        assert_eq!(
            redact_urls("https://example.com/a"),
            "https://example.com/a"
        );
    }

    #[test]
    fn roots_match_whole_folders_only() {
        assert_eq!(
            replace_root("C:\\Users\\me\\x", "C:\\Users\\me", "~", true),
            "~\\x"
        );
        assert_eq!(
            replace_root("C:\\Users\\me2\\x", "C:\\Users\\me", "~", true),
            "C:\\Users\\me2\\x"
        );
        assert_eq!(
            replace_root("c:/users/ME/x", "C:/Users/me", "~", true),
            "~/x"
        );
        assert_eq!(
            replace_root("/home/ME/x", "/home/me", "~", false),
            "/home/ME/x"
        );
    }

    #[test]
    fn random_words_are_masked_but_ulids_and_codes_stay() {
        assert_eq!(mask_random_words("k=Zx81Qa9vLr02mWq7TbYc"), "k=***");
        assert_eq!(
            mask_random_words("id=01JDKQ7Z8M3N4P5Q6R7S8T9V0W code=scanner_download_failed"),
            "id=01JDKQ7Z8M3N4P5Q6R7S8T9V0W code=scanner_download_failed"
        );
    }
}