egrix 0.2.1

Find leaked credentials and suspicious network destinations in AI agent transcripts. Local, offline, redacted by default.
//! One function per command. Each loads what it needs, calls the core modules
//! and returns the process exit code; none of them contains scanning or
//! matching logic of its own.

use crate::cli::{Filter, Group, HostsAction, Output, RulesAction};
use crate::model::{Report, Secret};
use crate::report::{self, plural, Style};
use crate::scan::{self, Env, Options};
use crate::state::State;
use crate::{context, fix, hosts, time};
use anyhow::{bail, Context, Result};
use std::io::{IsTerminal, Write};
use std::path::Path;
use std::process::ExitCode;

/// Lines of transcript shown on each side of a finding.
const EXCERPT_RADIUS: usize = 3;
/// Sightings printed by `egress --show`.
const MAX_SHOWN: usize = 5;

pub fn options(filter: &Filter) -> Result<Options> {
    let since = match &filter.since {
        Some(span) => Some(time::parse_span(span).with_context(|| format!("`{span}` is not a period. Use 7d, 2w or 3m."))?),
        None => None,
    };
    Ok(Options { agent: filter.agent, since, repo: filter.repo.clone() })
}

fn load(filter: &Filter) -> Result<(Env, Report)> {
    let env = Env::load()?;
    for warning in &env.rules.warnings {
        eprintln!("egrix: warning: {warning}");
    }
    let report = scan::scan(&env, &options(filter)?);
    Ok((env, report))
}

fn verdict(report: &Report) -> ExitCode {
    ExitCode::from(u8::from(report.has_new_findings()))
}

/// Print in the format the flags ask for; `text` renders the default one.
fn emit(report: &Report, output: &Output, text: impl FnOnce(Style) -> String) -> Result<ExitCode> {
    if output.json {
        println!("{}", report::json::render(report, output.reveal)?);
    } else if output.sarif {
        println!("{}", report::sarif::render(report)?);
    } else {
        print!("{}", text(Style::detect()));
    }
    Ok(verdict(report))
}

pub fn scan(filter: &Filter, output: &Output) -> Result<ExitCode> {
    let (_, report) = load(filter)?;
    emit(&report, output, |st| report::text::summary(&report, st))
}

pub fn secrets(filter: &Filter, output: &Output, group: Group, show: Option<&str>) -> Result<ExitCode> {
    let (env, mut report) = load(filter)?;
    report.hosts.clear();
    if let Some(id) = show {
        let secret = find_secret(&report, id)?;
        let excerpt =
            context::excerpt(&secret.location.file, secret.location.line, &secret.preview, &env.rules, EXCERPT_RADIUS).unwrap_or_default();
        print!("{}", report::text::secret_detail(secret, &report, &env.paths, &excerpt, Style::detect()));
        return Ok(ExitCode::SUCCESS);
    }
    emit(&report, output, |st| report::text::secrets(&report, group, output.reveal, st))
}

pub fn egress(filter: &Filter, output: &Output, show: Option<&str>, all: bool) -> Result<ExitCode> {
    let (env, mut report) = load(filter)?;
    report.secrets.clear();
    if let Some(name) = show {
        let name = hosts::normalize(name);
        let host =
            report.hosts.iter().find(|h| h.host == name).with_context(|| format!("{name} does not appear in the scanned history"))?;
        let excerpts: Vec<_> = host
            .locations
            .iter()
            .take(MAX_SHOWN)
            .map(|l| context::excerpt(&l.file, l.line, &host.host, &env.rules, EXCERPT_RADIUS).unwrap_or_default())
            .collect();
        print!("{}", report::text::host_detail(host, &report, &env.paths, &excerpts, Style::detect()));
        return Ok(ExitCode::SUCCESS);
    }
    emit(&report, output, |st| report::text::egress(&report, all, st))
}

pub fn fix(filter: &Filter, id: Option<&str>, undo: bool, yes: bool) -> Result<ExitCode> {
    let (mut env, report) = load(filter)?;
    let wanted = |s: &&Secret| !s.progress.ignored && s.progress.masked == undo;
    let targets: Vec<&Secret> = match id {
        Some(id) => vec![find_secret(&report, id)?].into_iter().filter(wanted).collect(),
        None => report.secrets.iter().filter(wanted).collect(),
    };
    if targets.is_empty() {
        println!("Nothing to {}.", if undo { "restore" } else { "mask" });
        return Ok(ExitCode::SUCCESS);
    }
    let files: std::collections::BTreeSet<_> = targets.iter().flat_map(|s| s.files.iter()).collect();
    println!("{} {} in {}:", if undo { "Restore" } else { "Mask" }, plural(targets.len(), "secret"), plural(files.len(), "file"));
    for s in &targets {
        println!("  {} {}  {}  {}", &s.id[..8], s.rule, s.preview, s.location.repo_name());
    }
    if undo {
        println!("The values go back into the transcripts in plain text.");
    } else {
        println!("A copy of each file is kept in {}.", env.paths.tilde(&env.paths.backup_dir()));
        println!("Masking does not revoke anything: rotate these credentials at the provider.");
    }
    if !yes && !confirm("Proceed?")? {
        println!("Nothing changed.");
        return Ok(ExitCode::SUCCESS);
    }
    let mut done = 0;
    let mut failure = None;
    for s in targets {
        let result = if undo { fix::unmask(&env.rules, &mut env.state, &s.id) } else { fix::mask(&env.paths, &mut env.state, s) };
        match result {
            Ok(files) => done += usize::from(files > 0),
            Err(error) => {
                failure.get_or_insert(error);
            }
        }
        env.state.known.insert(s.id.clone());
    }
    env.save_state()?;
    println!("{} {}.", if undo { "Restored" } else { "Masked" }, plural(done, "secret"));
    if let Some(error) = failure {
        return Err(error).context("some files could not be changed; what did change is saved");
    }
    Ok(ExitCode::SUCCESS)
}

pub fn mark(id: &str, rotated: bool, ignored: bool, clear: bool) -> Result<ExitCode> {
    let (mut env, report) = load(&Filter::default())?;
    let secret = find_secret(&report, id)?;
    let (id, rule) = (secret.id.clone(), secret.rule.clone());
    match (rotated, ignored, clear) {
        (true, _, _) => {
            env.state.rotated.insert(id.clone());
            println!("{rule}: marked as rotated.{}", if secret.progress.masked { "" } else { " Run `egrix fix` to mask the history." });
        }
        (_, true, _) => {
            env.state.ignored.insert(id.clone());
            println!("{rule}: ignored as a false positive.");
        }
        (_, _, true) => {
            env.state.rotated.remove(&id);
            env.state.ignored.remove(&id);
            println!("{rule}: marks cleared.");
        }
        _ => bail!("say what to record: --rotated, --ignored or --clear"),
    }
    env.state.known.insert(id);
    env.save_state()?;
    Ok(ExitCode::SUCCESS)
}

pub fn hosts(action: &HostsAction) -> Result<ExitCode> {
    let mut env = Env::load()?;
    match action {
        HostsAction::List => {
            for (title, list) in [("allow", &env.hosts.allow), ("deny", &env.hosts.deny)] {
                println!("{title} ({})", list.len());
                list.iter().for_each(|h| println!("  {h}"));
            }
            return Ok(ExitCode::SUCCESS);
        }
        HostsAction::Allow { host } => {
            let host = host_target(host)?;
            env.hosts.set(&host, true);
            println!("{host} is allowed, with its subdomains.");
        }
        HostsAction::Deny { host } => {
            let host = host_target(host)?;
            env.hosts.set(&host, false);
            println!("{host} is flagged, with its subdomains.");
        }
        HostsAction::Remove { host } => {
            let host = host_target(host)?;
            if !env.hosts.remove(&host) {
                bail!("{host} is on neither list");
            }
            println!("{host} removed from your lists.");
        }
    }
    env.save_hosts()?;
    Ok(ExitCode::SUCCESS)
}

/// Accept a host, a host:port or a URL and reduce it to the host list form.
fn host_target(input: &str) -> Result<String> {
    let host = hosts::normalize(input);
    if host.is_empty() {
        bail!("`{input}` is not a host");
    }
    Ok(host)
}

pub fn rules(action: &RulesAction) -> Result<ExitCode> {
    let env = Env::load()?;
    env.rules.warnings.iter().for_each(|w| eprintln!("egrix: warning: {w}"));
    match action {
        RulesAction::List => {
            for r in env.rules.rules() {
                println!("{:<7} {:<32} {:<8} {}", r.severity.name(), r.id, if r.bundled { "bundled" } else { "yours" }, r.pattern);
            }
            println!("{} active. Add your own in {}.", plural(env.rules.rules().len(), "rule"), env.paths.tilde(&env.paths.rules_dir()));
        }
        RulesAction::Test { file } => return rules_test(&env, file),
    }
    Ok(ExitCode::SUCCESS)
}

fn rules_test(env: &Env, file: &Path) -> Result<ExitCode> {
    let text = std::fs::read_to_string(file).with_context(|| format!("cannot read {}", file.display()))?;
    let mut found = 0;
    for (i, line) in text.lines().enumerate() {
        for hit in env.rules.find(line) {
            let rule = env.rules.rule(hit.rule);
            println!("{}:{}  {}  {}", file.display(), i + 1, rule.id, crate::rules::preview(hit.value));
            found += 1;
        }
    }
    println!("{}.", plural(found, "match"));
    Ok(ExitCode::SUCCESS)
}

pub fn baseline(filter: &Filter) -> Result<ExitCode> {
    let (mut env, report) = load(filter)?;
    let added = accept(&mut env.state, &report);
    env.save_state()?;
    println!("Baseline updated: {} accepted. Scans now fail only on new ones.", plural(added, "finding"));
    Ok(ExitCode::SUCCESS)
}

/// Record every current finding as known. Returns how many were new.
pub fn accept(state: &mut State, report: &Report) -> usize {
    let secrets = report.secrets.iter().filter(|s| state.known.insert(s.id.clone())).count();
    let hosts = report.flagged_hosts().filter(|h| state.known_hosts.insert(h.host.clone())).count();
    secrets + hosts
}

fn find_secret<'a>(report: &'a Report, id: &str) -> Result<&'a Secret> {
    let mut matches = report.secrets.iter().filter(|s| s.id.starts_with(id));
    match (matches.next(), matches.next()) {
        (Some(s), None) => Ok(s),
        (None, _) => bail!("no secret with id {id}. List them with `egrix secrets`."),
        (Some(_), Some(_)) => bail!("id {id} matches more than one secret; use more characters"),
    }
}

fn confirm(question: &str) -> Result<bool> {
    if !std::io::stdin().is_terminal() {
        bail!("this changes files and there is no terminal to confirm on; pass --yes");
    }
    print!("{question} [y/N] ");
    std::io::stdout().flush()?;
    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer)?;
    Ok(matches!(answer.trim(), "y" | "Y" | "yes"))
}