egrix 0.1.0

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,
    Gemini,
    Copilot,
    Antigravity,
}

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

    pub fn name(self) -> &'static str {
        match self {
            Agent::Claude => "claude",
            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>,
}

#[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)
    }
    /// 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)
    }
}