egrix 0.2.1

Find leaked credentials and suspicious network destinations in AI agent transcripts. Local, offline, redacted by default.
//! The data every other module speaks: what a scan found and where.

use crate::time::Day;
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
use std::fmt;
use std::path::PathBuf;

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum Agent {
    Claude,
    Codex,
    Gemini,
    Copilot,
    Antigravity,
}

impl Agent {
    pub const ALL: [Agent; 5] = [Agent::Claude, Agent::Codex, Agent::Gemini, Agent::Copilot, Agent::Antigravity];

    pub fn name(self) -> &'static str {
        match self {
            Agent::Claude => "claude",
            Agent::Codex => "codex",
            Agent::Gemini => "gemini",
            Agent::Copilot => "copilot",
            Agent::Antigravity => "antigravity",
        }
    }
}

impl fmt::Display for Agent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// Ordered so that sorting ascending puts the worst first.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    High,
    #[default]
    Medium,
    Low,
}

impl Severity {
    pub fn name(self) -> &'static str {
        match self {
            Severity::High => "high",
            Severity::Medium => "medium",
            Severity::Low => "low",
        }
    }
    pub fn glyph(self) -> &'static str {
        match self {
            Severity::High => "▲",
            Severity::Medium => "■",
            Severity::Low => "·",
        }
    }
}

/// The repository a transcript line was recorded in.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Repo {
    /// Directory name of the repository root: the short label.
    pub name: String,
    /// Absolute path the agent was working in.
    pub path: String,
    /// `host/owner/name` from the git remote, credentials stripped.
    pub remote: Option<String>,
}

impl Repo {
    /// Whether the name or remote contains `filter` (already lowercased).
    pub fn matches(&self, filter: &str) -> bool {
        self.name.to_lowercase().contains(filter) || self.remote.as_ref().is_some_and(|r| r.to_lowercase().contains(filter))
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Location {
    pub agent: Agent,
    pub file: PathBuf,
    pub line: usize,
    pub repo: Option<Repo>,
    pub branch: Option<String>,
    pub day: Day,
}

impl Location {
    pub fn repo_name(&self) -> &str {
        self.repo.as_ref().map_or("(no repository)", |r| r.name.as_str())
    }
}

/// What the user has done about a secret. A finding is resolved only when the
/// credential was rotated *and* the history was masked: masking alone leaves a
/// live credential, rotating alone leaves it readable on disk.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub struct Progress {
    pub rotated: bool,
    pub masked: bool,
    pub ignored: bool,
}

#[derive(Clone, Debug, Serialize)]
pub struct Secret {
    /// Stable id: a truncated SHA-256 of rule and value. Never the value.
    pub id: String,
    pub rule: String,
    pub severity: Severity,
    /// Redacted preview, safe to print.
    pub preview: String,
    /// The raw value. Kept in memory for masking; serialized only on `--reveal`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
    /// First place it was seen.
    pub location: Location,
    /// Every transcript file that contains it.
    pub files: BTreeSet<PathBuf>,
    pub occurrences: usize,
    /// Not in the baseline yet.
    pub new: bool,
    pub progress: Progress,
}

impl Secret {
    pub fn is_open(&self) -> bool {
        !self.progress.ignored && !(self.progress.rotated && self.progress.masked)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Verdict {
    Flagged,
    Unknown,
    Allowed,
}

impl Verdict {
    pub fn name(self) -> &'static str {
        match self {
            Verdict::Flagged => "flagged",
            Verdict::Unknown => "unknown",
            Verdict::Allowed => "allowed",
        }
    }
    pub fn glyph(self) -> &'static str {
        match self {
            Verdict::Flagged => "✗",
            Verdict::Unknown => "?",
            Verdict::Allowed => "✓",
        }
    }
}

#[derive(Clone, Debug, Serialize)]
pub struct Host {
    pub host: String,
    pub verdict: Verdict,
    /// Why it got that verdict: `your deny list`, `paste site`, `no rule`…
    pub reason: String,
    pub occurrences: usize,
    /// Most recent sightings first, capped.
    pub locations: Vec<Location>,
    pub last_seen: Day,
    pub new: bool,
}

impl Host {
    pub fn repo_name(&self) -> &str {
        self.locations.first().map_or("(no repository)", Location::repo_name)
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct Report {
    pub scanned_files: usize,
    pub agents: Vec<Agent>,
    pub today: Day,
    pub secrets: Vec<Secret>,
    pub hosts: Vec<Host>,
}

impl Report {
    pub fn open_secrets(&self) -> impl Iterator<Item = &Secret> {
        self.secrets.iter().filter(|s| s.is_open())
    }
    pub fn flagged_hosts(&self) -> impl Iterator<Item = &Host> {
        self.hosts.iter().filter(|h| h.verdict == Verdict::Flagged)
    }
    /// Secrets seen in the last `days`; `None` means all time.
    pub fn secrets_since(&self, days: Option<i64>) -> impl Iterator<Item = &Secret> {
        let cutoff = days.map(|n| self.today - n);
        self.secrets.iter().filter(move |s| cutoff.is_none_or(|c| s.location.day >= c))
    }
    /// Hosts last seen in the last `days`; `None` means all time.
    pub fn hosts_since(&self, days: Option<i64>) -> impl Iterator<Item = &Host> {
        let cutoff = days.map(|n| self.today - n);
        self.hosts.iter().filter(move |h| cutoff.is_none_or(|c| h.last_seen >= c))
    }
    #[cfg_attr(not(feature = "tui"), allow(dead_code))]
    pub fn open_secrets_since(&self, days: Option<i64>) -> impl Iterator<Item = &Secret> {
        self.secrets_since(days).filter(|s| s.is_open())
    }
    #[cfg_attr(not(feature = "tui"), allow(dead_code))]
    pub fn flagged_hosts_since(&self, days: Option<i64>) -> impl Iterator<Item = &Host> {
        self.hosts_since(days).filter(|h| h.verdict == Verdict::Flagged)
    }
    /// What the exit code reports: open secrets and flagged hosts that are not
    /// in the baseline.
    pub fn has_new_findings(&self) -> bool {
        self.open_secrets().any(|s| s.new) || self.flagged_hosts().any(|h| h.new)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn location(day: Day) -> Location {
        Location { agent: Agent::Claude, file: PathBuf::from("x.jsonl"), line: 1, repo: None, branch: None, day }
    }

    fn secret(id: &str, day: Day, progress: Progress) -> Secret {
        Secret {
            id: id.into(),
            rule: "test-rule".into(),
            severity: Severity::Low,
            preview: "****".into(),
            value: None,
            location: location(day),
            files: BTreeSet::new(),
            occurrences: 1,
            new: false,
            progress,
        }
    }

    fn host(name: &str, day: Day) -> Host {
        Host {
            host: name.into(),
            verdict: Verdict::Flagged,
            reason: "test".into(),
            occurrences: 1,
            locations: vec![location(day)],
            last_seen: day,
            new: false,
        }
    }

    #[test]
    fn period_helpers_window_secrets_and_hosts() {
        let mut report = Report { today: 100, ..Report::default() };
        report.secrets.push(secret("recent", 100, Progress::default()));
        report.secrets.push(secret("old", 60, Progress::default()));
        report.secrets.push(secret("resolved", 100, Progress { rotated: true, masked: true, ignored: false }));
        report.hosts.push(host("recent.test", 100));
        report.hosts.push(host("old.test", 60));

        let ids = |days: Option<i64>| report.secrets_since(days).map(|s| s.id.as_str()).collect::<Vec<_>>();
        assert_eq!(ids(Some(30)), ["recent", "resolved"]);
        assert_eq!(ids(None).len(), 3);
        assert_eq!(report.open_secrets_since(Some(30)).count(), 1, "resolved secrets are closed");
        assert_eq!(report.flagged_hosts_since(Some(30)).count(), 1);
        assert_eq!(report.flagged_hosts_since(None).count(), 2);
    }
}