egrix 0.1.0

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)?;
        }
        std::fs::write(path, serde_json::to_string_pretty(self)?).with_context(|| format!("cannot write {}", path.display()))?;
        private(path);
        Ok(())
    }

    /// Flip membership of `id` in a set; returns the new state.
    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;
}