Cotton code
248 lines · 9.1 KB · RustRaw
//! Every case of `packages/core/__tests__/engine/redact.test.ts` — every//! pattern the spec names, and the benign look-alikes that must survive, since//! a git sha, a uuid and a phone number are everyday session content.use super::*;// ── each pattern ─────────────────────────────────────────────────────────────#[test]fn redacts_a_cotton_mcp_token() {    assert_eq!(        redact_secrets("use ctn_abcdefghijklmnopqrstuvwxyz123456 here"),        "use [redacted:cotton-token] here"    );}#[test]fn redacts_a_token_whose_base64url_body_carries_underscore_and_hyphen() {    // What `randomBytes(32).toString("base64url")` actually emits. The rule's    // class was `[A-Za-z0-9]` until 2026-08-31, which ended the run at the    // first `_` or `-` — half of all real tokens went through untouched and a    // quarter were left with their tail in the text.    assert_eq!(        redact_secrets("use ctn_ab-cd_efghijklmnopqrstuvwxyz123456 here"),        "use [redacted:cotton-token] here"    );    assert_eq!(        redact_secrets("ctn_-_-_-_-_-_-_-_-_-_-abcdefghij"),        "[redacted:cotton-token]"    );}#[test]fn redacts_a_feedback_ingest_token() {    // The one credential an assistant is handed in plaintext — and an assistant    // calls `log_session`, which scrubs through here.    assert_eq!(        redact_secrets("ingestToken: cfi_ab-cd_efghijklmnopqrstuvwxyz123456"),        "ingestToken: [redacted:cotton-ingest-token]"    );}#[test]fn redacts_a_code_credential_wherever_a_git_remote_prints_one() {    // The two shapes a `ctg_` actually travels in: the mint's own answer, and a    // remote URL a session prints. Both are text a session log carries.    assert_eq!(        redact_secrets("secret: ctg_ab-cd_efghijklmnopqrstuvwxyz123456"),        "secret: [redacted:cotton-code-credential]"    );    assert_eq!(        redact_secrets(            "https://device-a:ctg_ab-cd_efghijklmnopqrstuvwxyz123456@x.relay.cottondb.com/git/"        ),        "https://device-a:[redacted:cotton-code-credential]@x.relay.cottondb.com/git/"    );}#[test]fn redacts_an_sk_api_key() {    assert_eq!(        redact_secrets("OPENAI=sk-proj-abcdefghijklmnop1234"),        "OPENAI=[redacted:api-key]"    );}#[test]fn redacts_github_tokens_of_every_prefix() {    assert_eq!(        redact_secrets("ghp_abcdefghijklmnopqrstuvwxyz0123456789"),        "[redacted:github-token]"    );    assert_eq!(        redact_secrets("gho_abcdefghijklmnopqrstuvwxyz0123456789"),        "[redacted:github-token]"    );    assert_eq!(        redact_secrets("github_pat_11ABCDEFG0abcdefghijklmnopqrstuvwxyz"),        "[redacted:github-token]"    );}#[test]fn redacts_an_aws_access_key_id() {    assert_eq!(        redact_secrets("key AKIAIOSFODNN7EXAMPLE used"),        "key [redacted:aws-key] used"    );}#[test]fn redacts_a_jwt() {    let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";    assert_eq!(        redact_secrets(&format!("token {jwt}.")),        "token [redacted:jwt]."    );}#[test]fn redacts_slack_tokens() {    assert_eq!(        redact_secrets("xoxb-1234567890-abcdefghij"),        "[redacted:slack-token]"    );    assert_eq!(        redact_secrets("xoxp-1234567890-abcdefghij"),        "[redacted:slack-token]"    );    assert_eq!(        redact_secrets("xoxa-1234567890-abcdefghij"),        "[redacted:slack-token]"    );}#[test]fn redacts_a_whole_private_key_block() {    let block = [        "-----BEGIN RSA PRIVATE KEY-----",        "MIIEowIBAAKCAQEA0Z3VS5JJcds3xfn",        "-----END RSA PRIVATE KEY-----",    ]    .join("\n");    assert_eq!(        redact_secrets(&format!("cat key\n{block}\ndone")),        "cat key\n[redacted:private-key]\ndone"    );}#[test]fn redacts_an_unterminated_private_key_block_to_the_end_of_the_text() {    let cut = "-----BEGIN PRIVATE KEY-----\nMIIEowIBAAKCAQEA0Z3VS5JJcds3xfn";    assert_eq!(        redact_secrets(&format!("truncated: {cut}")),        "truncated: [redacted:private-key]"    );}#[test]fn redacts_a_bearer_value_and_keeps_the_word_bearer() {    assert_eq!(        redact_secrets("Authorization: Bearer abc.def-ghi_jkl"),        "Authorization: Bearer [redacted:bearer]"    );}#[test]fn redacts_several_secrets_in_one_text() {    assert_eq!(        redact_secrets("ghp_abcdefghijklmnopqrstuvwxyz0123456789 and AKIAIOSFODNN7EXAMPLE"),        "[redacted:github-token] and [redacted:aws-key]"    );}// ── benign survivors ─────────────────────────────────────────────────────────#[test]fn leaves_the_everyday_look_alikes_untouched() {    for (label, text) in [        (            "a git sha",            "fixed in 66442054f1b2c3d4e5f60718293a4b5c6d7e8f90",        ),        (            "a uuid",            "row 11111111-1111-4111-8111-111111111111 was skipped",        ),        ("a phone number", "call +91 00000 11111 tomorrow"),        (            "a PR url",            "shipped https://github.com/example/repo/pull/2062",        ),        ("a kebab slug", "cite [no-prod-release-without-the-ask]"),        ("an env assignment", "set COTTON_DATA_DIR=/srv/cotton"),        ("a short sk word", "ask-the-owner first"),        ("the word bearer alone", "the bearer of bad news"),        (            "an ordinary sentence",            "Rotate the litestream token before the deploy.",        ),    ] {        assert_eq!(redact_secrets(text), text, "{label}");    }}#[test]fn returns_an_empty_string_for_an_empty_string() {    assert_eq!(redact_secrets(""), "");}/// The ORDER of the rules is load-bearing, and this is the case that proves it:/// a bearer JWT must read as the bearer value it was, not as a bare JWT that/// happened to follow the word.#[test]fn a_bearer_jwt_reads_as_a_bearer_not_a_jwt() {    let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.abcdef";    assert_eq!(        redact_secrets(&format!("Authorization: Bearer {jwt}")),        "Authorization: Bearer [redacted:bearer]"    );}/// And a private key block goes first so its body cannot be eaten piecemeal by/// the token rules — a base64 body can easily contain a `sk-` or `ghp_` run.#[test]fn a_private_key_block_is_taken_whole_not_piecemeal() {    let block = "-----BEGIN OPENSSH PRIVATE KEY-----\nghp_abcdefghijklmnopqrstuvwxyz0123\nsk-abcdefghijklmnop\n-----END OPENSSH PRIVATE KEY-----";    assert_eq!(redact_secrets(block), "[redacted:private-key]");}// ── connection config ────────────────────────────────────────────────────────/// RULE: A connection's config answers an assistant with no credential at any depth — by key name, by value shape, inside a URL or as an opaque run — because the transcript keeps what it reads.#[test]fn a_connection_config_loses_every_credential_at_any_depth() {    let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJpbnZlbnRlZCJ9.c2lnbmF0dXJlLWludmVudGVk";    let hex = "9f86d081884c7d659a2feaa0c55ad015";    let config = serde_json::json!({        "host": "mail.example.test",        "server": {"headers": {"x-api-key": "INVENTED-1", "Authorization": "INVENTED-2"},            "oauth": {"refreshToken": "INVENTED-3", "client_secret": "INVENTED-4", "client": {"id": "invented-client"}},            "auth": {"user": "someone", "pass": "INVENTED-5"}},        "level1": {"level2": {"level3": {"note": jwt, "account": hex, "header": "Basic aW52ZW50ZWQ6c2VjcmV0", "pwd": "INVENTED-6"}}},        "url": "https://someone:INVENTED-7@dav.example.test/cal?access_token=INVENTED-8&view=week",        "list": [{"privateKeyPem": "INVENTED-9"}, {"signature": "INVENTED-10"}, 60]    });    let answer = redact_connection_config(&config);    let text = answer.to_string();    for leaked in ["INVENTED-", jwt, hex, "aW52ZW50ZWQ6c2VjcmV0"] {        assert!(!text.contains(leaked), "{leaked} reached the answer: {text}");    }    // What is not a credential survives, so the answer still diagnoses.    assert_eq!(answer["host"], "mail.example.test");    assert_eq!(answer["list"][2], 60);    assert!(answer["url"].as_str().unwrap().contains("dav.example.test/cal"), "{text}");    assert!(answer["url"].as_str().unwrap().contains("view=week"), "{text}");}/// RULE: Connection redaction keeps the everyday look-alikes a connection needs to be diagnosed — hosts, uuids, paths, ports, plain words.#[test]fn a_connection_config_keeps_what_is_not_a_credential() {    let config = serde_json::json!({        "host": "imap.example.test", "port": 993, "calendar": "11111111-1111-4111-8111-111111111111",        "folder": "/Users/someone/Library/Containers/Archive2026Exports", "site": "https://example.test/feed?page=2",        "account": "someone@example.test"    });    assert_eq!(redact_connection_config(&config), config);}