egrix 0.2.1

Find leaked credentials and suspicious network destinations in AI agent transcripts. Local, offline, redacted by default.
//! Output for people: a summary first, details after, a next step at the end.

use super::{plural, repo_label, Style};
use crate::cli::Group;
use crate::context::ExcerptLine;
use crate::model::{Host, Report, Secret, Severity, Verdict};
use crate::paths::Paths;
use crate::time;
use std::fmt::Write;

/// Which half of the report a command is about.
#[derive(Clone, Copy, PartialEq)]
pub enum Scope {
    All,
    Secrets,
    Hosts,
}

pub fn headline(r: &Report, scope: Scope, st: Style) -> String {
    let open: Vec<&Secret> = r.open_secrets().collect();
    let repos = open.iter().map(|s| s.location.repo_name()).collect::<std::collections::BTreeSet<_>>().len();
    let new = open.iter().filter(|s| s.new).count();
    let flagged = r.flagged_hosts().count();
    let unknown = r.hosts.iter().filter(|h| h.verdict == Verdict::Unknown).count();
    let secrets = format!("{} open in {}", plural(open.len(), "secret"), plural(repos, "repo"));
    let mut parts = Vec::new();
    if scope != Scope::Hosts {
        parts.push(format!(
            "{}{}",
            if open.is_empty() { st.good(&secrets) } else { st.bad(&secrets) },
            if new > 0 { format!(" ({new} new)") } else { String::new() }
        ));
    }
    if scope != Scope::Secrets {
        parts.push(if flagged == 0 { st.good("0 flagged hosts") } else { st.bad(&plural(flagged, "flagged host")) });
        parts.push(plural(unknown, "unknown host"));
    }
    let mut out = String::new();
    let _ = writeln!(out, "{}", parts.join(" ยท "));
    let agents: Vec<&str> = r.agents.iter().map(|a| a.name()).collect();
    let _ = writeln!(
        out,
        "{}",
        st.dim(&format!(
            "scanned {} from {}",
            plural(r.scanned_files, "file"),
            if agents.is_empty() { "no agents".into() } else { agents.join(", ") }
        ))
    );
    out
}

pub fn summary(r: &Report, st: Style) -> String {
    let mut out = headline(r, Scope::All, st);
    let open: Vec<&Secret> = r.open_secrets().collect();
    if !open.is_empty() {
        out.push('\n');
        out.push_str(&secret_rows(&open, Group::Repo, r, st, false));
    }
    let flagged: Vec<&Host> = r.flagged_hosts().collect();
    if !flagged.is_empty() {
        let _ = writeln!(out, "\n{}", st.bold("Flagged hosts"));
        out.push_str(&host_rows(&flagged, r, st));
    }
    out.push_str(&next_step(r, st));
    out
}

pub fn secrets(r: &Report, group: Group, reveal: bool, st: Style) -> String {
    let mut out = headline(r, Scope::Secrets, st);
    let all: Vec<&Secret> = r.secrets.iter().collect();
    if !all.is_empty() {
        out.push('\n');
        out.push_str(&secret_rows(&all, group, r, st, reveal));
        let _ = writeln!(out, "\n{}", st.dim("t = credential rotated, m = masked in history. Details: egrix secrets --show <id>"));
    }
    out.push_str(&next_step(r, st));
    out
}

pub fn egress(r: &Report, all: bool, st: Style) -> String {
    let mut out = headline(r, Scope::Hosts, st);
    for verdict in [Verdict::Flagged, Verdict::Unknown, Verdict::Allowed] {
        let rows: Vec<&Host> = r.hosts.iter().filter(|h| h.verdict == verdict).collect();
        if rows.is_empty() || (verdict == Verdict::Allowed && !all) {
            continue;
        }
        let _ = writeln!(out, "\n{} ({})", st.bold(verdict.name()), rows.len());
        out.push_str(&host_rows(&rows, r, st));
    }
    let allowed = r.hosts.iter().filter(|h| h.verdict == Verdict::Allowed).count();
    if allowed > 0 && !all {
        let _ = writeln!(out, "\n{}", st.dim(&format!("{} hidden. Show them with --all.", plural(allowed, "allowed host"))));
    }
    if r.hosts.iter().any(|h| h.verdict != Verdict::Allowed) {
        let _ = writeln!(out, "\nNext: `egrix egress --show <host>` to see what happened, then `egrix hosts allow|deny <host>`.");
    }
    out
}

fn secret_rows(secrets: &[&Secret], group: Group, r: &Report, st: Style, reveal: bool) -> String {
    let mut out = String::new();
    let mut keys: Vec<String> = Vec::new();
    for s in secrets {
        let k = if s.progress.ignored { "ignored (false positives)".to_string() } else { group.key(s) };
        if !keys.contains(&k) {
            keys.push(k);
        }
    }
    let rule_w = secrets.iter().map(|s| s.rule.len()).max().unwrap_or(0);
    for key in keys {
        let members: Vec<&&Secret> =
            secrets.iter().filter(|s| if s.progress.ignored { key.starts_with("ignored") } else { group.key(s) == key }).collect();
        let remote = (group == Group::Repo).then(|| members[0].location.repo.as_ref().and_then(|x| x.remote.clone())).flatten();
        let _ = writeln!(out, "{}{}", st.bold(&key), remote.map(|x| st.dim(&format!("  {x}"))).unwrap_or_default());
        for s in members {
            let sev = format!("{} {:<6}", s.severity.glyph(), s.severity.name());
            let sev = match s.severity {
                Severity::High => st.bad(&sev),
                Severity::Medium => st.warn(&sev),
                Severity::Low => st.dim(&sev),
            };
            let value = match (&s.value, reveal) {
                (Some(v), true) => v.clone(),
                _ => s.preview.clone(),
            };
            let marks = format!("{}{}", if s.progress.rotated { "t" } else { "-" }, if s.progress.masked { "m" } else { "-" });
            let _ = writeln!(
                out,
                "  {sev} {} {:<rule_w$}  {}  {}",
                st.dim(&s.id[..8]),
                s.rule,
                if s.is_open() { marks } else { st.good(&marks) },
                st.dim(&format!(
                    "{value}  {} {}  {}{}",
                    s.location.agent,
                    if group == Group::Repo { s.location.branch.clone().unwrap_or_default() } else { s.location.repo_name().to_string() },
                    time::ago(s.location.day, r.today),
                    if s.new { "  new" } else { "" }
                )),
            );
        }
    }
    out
}

fn host_rows(hosts: &[&Host], r: &Report, st: Style) -> String {
    let width = hosts.iter().map(|h| h.host.len()).max().unwrap_or(0);
    let mut out = String::new();
    for h in hosts {
        let mark = match h.verdict {
            Verdict::Flagged => st.bad(h.verdict.glyph()),
            Verdict::Unknown => st.warn(h.verdict.glyph()),
            Verdict::Allowed => st.good(h.verdict.glyph()),
        };
        let agent = h.locations.first().map_or(String::new(), |l| l.agent.to_string());
        let _ = writeln!(
            out,
            "  {mark} {:<width$}  {}",
            h.host,
            st.dim(&format!("{}  {}x  {agent}  {}  {}", h.reason, h.occurrences, h.repo_name(), time::ago(h.last_seen, r.today)))
        );
    }
    out
}

fn next_step(r: &Report, st: Style) -> String {
    let open: Vec<&Secret> = r.open_secrets().collect();
    if open.is_empty() {
        return if r.scanned_files == 0 { format!("\n{}\n", st.dim("No agent history found on this machine.")) } else { String::new() };
    }
    let unrotated = open.iter().filter(|s| !s.progress.rotated).count();
    let unmasked = open.iter().filter(|s| !s.progress.masked).count();
    let mut steps = Vec::new();
    if unrotated > 0 {
        steps.push(format!("rotate {} at the provider (then `egrix mark <id> --rotated`)", plural(unrotated, "credential")));
    }
    if unmasked > 0 {
        steps.push("run `egrix fix` to mask the history".to_string());
    }
    format!("\nNext: {}.\n", steps.join(", then "))
}

pub fn secret_detail(s: &Secret, r: &Report, paths: &Paths, excerpt: &[ExcerptLine], st: Style) -> String {
    let mut out = String::new();
    let loc = &s.location;
    let _ = writeln!(out, "{}  {} {}", st.bold(&s.rule), s.severity.glyph(), s.severity.name());
    for (k, v) in [
        ("id", s.id.clone()),
        ("value", s.preview.clone()),
        ("agent", loc.agent.to_string()),
        (
            "repository",
            format!("{}{}", repo_label(loc.repo.as_ref(), true), loc.branch.as_ref().map(|b| format!(" @ {b}")).unwrap_or_default()),
        ),
        ("file", format!("{}:{}", paths.tilde(&loc.file), loc.line)),
        ("exposed", format!("{} ({}), in {}", time::ago(loc.day, r.today), time::format(loc.day), plural(s.files.len(), "file"))),
        ("rotated", yes_no(s.progress.rotated)),
        ("masked", yes_no(s.progress.masked)),
    ] {
        let _ = writeln!(out, "  {:<11}{v}", st.dim(k));
    }
    out.push_str(&excerpt_block(excerpt, st));
    out
}

pub fn host_detail(h: &Host, r: &Report, paths: &Paths, excerpts: &[Vec<ExcerptLine>], st: Style) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "{}  {} {} ({})", st.bold(&h.host), h.verdict.glyph(), h.verdict.name(), h.reason);
    let _ =
        writeln!(out, "  {}", st.dim(&format!("{}, last seen {}", plural(h.occurrences, "occurrence"), time::ago(h.last_seen, r.today))));
    for (loc, lines) in h.locations.iter().zip(excerpts) {
        let _ = writeln!(
            out,
            "\n{}",
            st.dim(&format!("{}:{}  {}  {}  {}", paths.tilde(&loc.file), loc.line, loc.agent, loc.repo_name(), time::format(loc.day)))
        );
        out.push_str(&excerpt_block(lines, st));
    }
    if h.occurrences > excerpts.len() {
        let _ = writeln!(out, "\n{}", st.dim(&format!("Showing {} of {}.", excerpts.len(), plural(h.occurrences, "occurrence"))));
    }
    out
}

fn excerpt_block(lines: &[ExcerptLine], st: Style) -> String {
    let mut out = String::new();
    for l in lines {
        let row = format!("{:>6}  {:<10} {}", l.number, l.role, l.text);
        let _ = writeln!(out, "{}", if l.hit { row } else { st.dim(&row) });
    }
    out
}

fn yes_no(b: bool) -> String {
    if b { "yes" } else { "no" }.to_string()
}