egrix 0.2.1

Find leaked credentials and suspicious network destinations in AI agent transcripts. Local, offline, redacted by default.
//! What the user has decided about findings, persisted between runs. Holds
//! fingerprints and redacted previews only: never a secret value.

use crate::model::{Location, Severity};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct State {
    /// Secrets already seen: the baseline. Anything else is reported as new.
    #[serde(default)]
    pub known: BTreeSet<String>,
    /// Secrets whose credential the user says was rotated.
    #[serde(default)]
    pub rotated: BTreeSet<String>,
    /// False positives.
    #[serde(default)]
    pub ignored: BTreeSet<String>,
    /// Secrets masked in the transcripts. They no longer show up in a scan, so
    /// what is needed to list and undo them is kept here.
    #[serde(default)]
    pub masked: BTreeMap<String, Masked>,
    /// Flagged hosts already seen.
    #[serde(default)]
    pub known_hosts: BTreeSet<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Masked {
    pub rule: String,
    pub severity: Severity,
    pub preview: String,
    pub location: Location,
    pub edits: Vec<Edit>,
}

/// One transcript file that was rewritten, and the copy made before.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Edit {
    pub file: PathBuf,
    pub backup: PathBuf,
}

impl State {
    pub fn load(path: &Path) -> Result<Self> {
        match std::fs::read_to_string(path) {
            Ok(text) => serde_json::from_str(&text).with_context(|| format!("{} is not valid", path.display())),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(e) => Err(e).with_context(|| format!("cannot read {}", path.display())),
        }
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        if let Some(dir) = path.parent() {
            std::fs::create_dir_all(dir)?;
        }
        // Write beside the target and rename, so a crash never leaves a
        // half-written state with no pointer to the backups.
        let mut tmp = path.to_path_buf();
        tmp.set_extension("json.tmp");
        std::fs::write(&tmp, serde_json::to_string_pretty(self)?).with_context(|| format!("cannot write {}", tmp.display()))?;
        private(&tmp);
        std::fs::rename(&tmp, path).with_context(|| format!("cannot replace {}", path.display()))?;
        private(path);
        Ok(())
    }

    /// Flip membership of `id` in a set; returns the new state.
    #[cfg_attr(not(feature = "tui"), allow(dead_code))]
    pub fn toggle(set: &mut BTreeSet<String>, id: &str) -> bool {
        if set.remove(id) {
            false
        } else {
            set.insert(id.to_string());
            true
        }
    }
}

/// Owner-only permissions, where the platform has them.
pub fn private(path: &Path) {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = if path.is_dir() { 0o700 } else { 0o600 };
        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
    }
    #[cfg(not(unix))]
    let _ = path;
}

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

    #[test]
    fn saves_through_a_temporary_file_and_round_trips() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state.json");
        let mut state = State::default();
        state.known.insert("0123456789abcdef".into());

        state.save(&path).unwrap();
        assert!(State::load(&path).unwrap().known.contains("0123456789abcdef"));
        assert!(!path.with_extension("json.tmp").exists(), "the temporary file is renamed away");

        state.known.insert("fedcba9876543210".into());
        state.save(&path).unwrap();
        assert_eq!(State::load(&path).unwrap().known.len(), 2);
    }
}