Cotton code
186 lines · 8.5 KB · RustRaw
//! Redaction — what a session summary or prompt loses before it reaches the//! file. The port of `packages/core/src/engine/redact.ts`.//!//! Shared by the server (`log_session` scrubs BEFORE the write) and the app, so//! a token pasted into a prompt on any machine is gone before any replica holds//! it. This is the complement of `looks_like_secret` in the memory briefing: a//! memory entry is REFUSED when it carries a credential, because a memory is//! curated and the agent can rephrase — a session log is a record of what was//! said, so the credential is cut out and the rest kept.//!//! Each rule names its kind in the replacement, `[redacted:<kind>]`, so a//! reader can still tell what was there. Benign look-alikes survive by design://! a git sha, a uuid, a phone number and a kebab slug have no prefix these//! patterns require, and the private-key rule needs the armour lines.use std::sync::LazyLock;use regex::Regex;struct RedactionRule {    pattern: Regex,    /// What to put in the text.    replacement: String,}fn marker(kind: &str) -> String {    format!("[redacted:{kind}]")}fn rule(pattern: &str, kind: &str) -> RedactionRule {    RedactionRule {        pattern: Regex::new(pattern).expect("a valid pattern"),        replacement: marker(kind),    }}/// Order is load-bearing: a private key block goes first so its body cannot be/// eaten piecemeal by the token rules, and `Bearer <value>` goes before the/// token rules so a bearer JWT reads as the bearer value it was, not a bare JWT/// that happened to follow the word.static RULES: LazyLock<Vec<RedactionRule>> = LazyLock::new(|| {    vec![        rule(            r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----",            "private-key",        ),        // A block whose END line was cut off (a truncated summary) still ends        // the usable text — everything after the armour is key material.        rule(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*$", "private-key"),        RedactionRule {            pattern: Regex::new(r"(?-u:\b)Bearer\s+[A-Za-z0-9._~+/=-]{8,}")                .expect("a valid pattern"),            replacement: format!("Bearer {}", marker("bearer")),        },        // BASE64URL, not alphanumeric. Both Cotton credentials are a prefix        // plus `randomBytes(32).toString("base64url")`, whose alphabet includes        // `_` and `-`; the class here was `[A-Za-z0-9]` until 2026-08-31, which        // made this rule miss roughly half of all real tokens outright (the run        // ended at the first `_` or `-`, and 20 clean characters is a coin        // flip) and truncate a quarter more. Measured over 20k minted tokens:        // 47% unredacted, 27% partially redacted.        rule(r"(?-u:\b)ctn_[A-Za-z0-9_-]{20,}", "cotton-token"),        // The retired feedback-ingest token. It matters MORE        // than the OAuth pair (`cta_`/`ctr_`, which are server-held and never        // spoken): `register_feedback_app` handed the plaintext to an assistant,        // and an assistant routinely calls `log_session` — which scrubs through        // here. Absent this rule the credential lands verbatim in the owner's        // own file.        //        // THAT TOOL IS RETIRED and no `cfi_` will ever be minted again. The        // rule is not: one minted while the ingest route was live can sit in a        // note, a session log or a memory entry already written, and a pattern        // that stops matching is a secret that starts getting echoed. Deleting        // this is a decision about text that already exists, not about a        // feature.        rule(r"(?-u:\b)cfi_[A-Za-z0-9_-]{20,}", "cotton-ingest-token"),        // The CODE credential a git client and a script spend        // (`cotton-server/src/code/credentials.rs`). It matters for `cfi_`'s        // reason rather than the OAuth pair's: a `ctg_` is HANDED TO A PERSON        // once, at mint, and the two places it then travels are a terminal a        // session is watching and a `git remote` a session can print. Both of        // those reach `log_session`, which scrubs through here.        rule(r"(?-u:\b)ctg_[A-Za-z0-9_-]{20,}", "cotton-code-credential"),        rule(r"(?-u:\b)sk-[A-Za-z0-9_-]{16,}", "api-key"),        rule(r"(?-u:\b)gh[pousr]_[A-Za-z0-9]{16,}", "github-token"),        rule(r"(?-u:\b)github_pat_[A-Za-z0-9_]{20,}", "github-token"),        rule(r"(?-u:\b)AKIA[0-9A-Z]{16}(?-u:\b)", "aws-key"),        rule(            r"(?-u:\b)eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+",            "jwt",        ),        rule(r"(?-u:\b)xox[bpa]-[A-Za-z0-9-]{10,}", "slack-token"),    ]});/// The text with every credential-shaped run replaced by its marker.pub fn redact_secrets(text: &str) -> String {    let mut out = text.to_string();    for rule in RULES.iter() {        // `replace_all` is the `g` flag. The replacement carries no `$`, so no        // capture-group expansion can fire inside it.        out = rule            .pattern            .replace_all(&out, rule.replacement.as_str())            .into_owned();    }    out}/// The key fragments that mark a connection config value as a credential./// Over-matching drops a harmless setting from an assistant's answer; missing/// one hands a credential to its transcript, so the list leans wide.const CREDENTIAL_KEY_PARTS: &[&str] = &[    "token", "secret", "pass", "pwd", "key", "cookie", "session", "auth", "credential", "bearer",    "signature", "private", "basic",];/// `scheme://user:password@host` — the userinfo of a URL.static URL_USERINFO: LazyLock<Regex> =    LazyLock::new(|| Regex::new(r"(?i)\b([a-z][a-z0-9+.-]*://)[^/\s@?#]+@").expect("a valid pattern"));/// One `name=value` of a URL's query or fragment.static URL_PARAM: LazyLock<Regex> =    LazyLock::new(|| Regex::new(r"([?&#;])([^=&\s#]+)=([^&\s#]*)").expect("a valid pattern"));/// `Basic <base64>` — an HTTP basic credential, which is a password in clear.static BASIC: LazyLock<Regex> =    LazyLock::new(|| Regex::new(r"(?-u:\b)Basic\s+[A-Za-z0-9+/=]{8,}").expect("a valid pattern"));/// A whole value that is one opaque run: an API key or token with no prefix.static OPAQUE: LazyLock<Regex> =    LazyLock::new(|| Regex::new(r"^[A-Za-z0-9_+=-][A-Za-z0-9_+/=-]{23,}$").expect("a valid pattern"));static UUID: LazyLock<Regex> = LazyLock::new(|| {    Regex::new(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$").expect("a valid pattern")});fn is_credential_key(key: &str) -> bool {    let lower = key.to_ascii_lowercase();    CREDENTIAL_KEY_PARTS.iter().any(|part| lower.contains(part))}/// One text value of a connection — config, its address or its last error —/// with every credential shape cut: the shared session rules, a URL's userinfo/// and credential-named query values, a basic header, and a whole value that is/// an opaque run (a key with no prefix, which no shape rule can name).pub fn redact_connection_text(text: &str) -> String {    let trimmed = text.trim();    if OPAQUE.is_match(trimmed)        && !UUID.is_match(trimmed)        && trimmed.chars().any(|c| c.is_ascii_digit())        && trimmed.chars().any(|c| c.is_ascii_alphabetic())    {        return marker("opaque");    }    let out = redact_secrets(text);    let out = BASIC.replace_all(&out, format!("Basic {}", marker("basic")).as_str()).into_owned();    let out = URL_USERINFO.replace_all(&out, format!("${{1}}{}@", marker("userinfo")).as_str()).into_owned();    URL_PARAM        .replace_all(&out, |caps: &regex::Captures<'_>| {            if is_credential_key(&caps[2]) {                format!("{}{}={}", &caps[1], &caps[2], marker("param"))            } else {                caps[0].to_string()            }        })        .into_owned()}/// A connection config may carry credentials at any depth. Drop credential/// keys and redact every remaining text value as [`redact_connection_text`].pub fn redact_connection_config(value: &serde_json::Value) -> serde_json::Value {    use serde_json::Value;    match value {        Value::Object(fields) => Value::Object(            fields                .iter()                .filter(|(key, _)| !is_credential_key(key))                .map(|(key, value)| (key.clone(), redact_connection_config(value)))                .collect(),        ),        Value::Array(values) => Value::Array(values.iter().map(redact_connection_config).collect()),        Value::String(text) => Value::String(redact_connection_text(text)),        other => other.clone(),    }}#[cfg(test)]#[path = "redact_tests.rs"]mod tests;