use crate::git::RepoResolver;
use crate::hosts::{self, HostLists};
use crate::model::{Agent, Host, Location, Progress, Repo, Report, Secret, Verdict};
use crate::paths::Paths;
use crate::rules::{self, RuleSet};
use crate::sources::{self, Transcript};
use crate::state::State;
use crate::time::{self, Day};
use anyhow::Result;
use std::collections::{BTreeSet, HashMap};
const MAX_HOST_LOCATIONS: usize = 50;
pub struct Env {
pub paths: Paths,
pub rules: RuleSet,
pub hosts: HostLists,
pub state: State,
}
impl Env {
pub fn load() -> Result<Self> {
let paths = Paths::from_env()?;
Ok(Self {
rules: RuleSet::load(&paths.rules_dir()),
hosts: HostLists::load(&paths.hosts_file())?,
state: State::load(&paths.state_file())?,
paths,
})
}
pub fn save_state(&self) -> Result<()> {
self.state.save(&self.paths.state_file())
}
pub fn save_hosts(&self) -> Result<()> {
self.hosts.save(&self.paths.hosts_file())
}
}
#[derive(Clone, Debug, Default)]
pub struct Options {
pub agent: Option<Agent>,
pub since: Option<i64>,
pub repo: Option<String>,
}
pub fn scan(env: &Env, opts: &Options) -> Report {
let today = time::today();
let transcripts = sources::discover(&env.paths.home, opts.agent);
let mut agents: Vec<Agent> = transcripts.iter().map(|t| t.agent).collect();
agents.dedup();
let mut collector = Collector {
env,
cutoff: opts.since.map(|n| today - n),
repo_filter: opts.repo.as_deref().map(str::to_lowercase),
repos: RepoResolver::default(),
secrets: Vec::new(),
secret_index: HashMap::new(),
hosts: HashMap::new(),
};
for transcript in &transcripts {
collector.read(transcript);
}
let (secrets, hosts) = collector.finish(today);
Report { scanned_files: transcripts.len(), agents, today, secrets, hosts }
}
struct Collector<'a> {
env: &'a Env,
cutoff: Option<Day>,
repo_filter: Option<String>,
repos: RepoResolver,
secrets: Vec<Secret>,
secret_index: HashMap<String, usize>,
hosts: HashMap<String, (usize, Vec<Location>)>,
}
struct Cursor {
repo: Option<Repo>,
branch: Option<String>,
day: Day,
}
impl Collector<'_> {
fn read(&mut self, transcript: &Transcript) {
let Ok(bytes) = std::fs::read(&transcript.path) else { return };
let content = String::from_utf8_lossy(&bytes);
let modified = std::fs::metadata(&transcript.path).and_then(|m| m.modified()).map(time::day_of).unwrap_or_else(|_| time::today());
let mut cursor = Cursor { repo: None, branch: None, day: modified };
for (index, line) in content.lines().enumerate() {
self.advance(&mut cursor, line);
if self.cutoff.is_some_and(|c| cursor.day < c) || !self.repo_matches(&cursor) {
continue;
}
let location = || Location {
agent: transcript.agent,
file: transcript.path.clone(),
line: index + 1,
repo: cursor.repo.clone(),
branch: cursor.branch.clone(),
day: cursor.day,
};
for hit in self.env.rules.find(line) {
let rule = self.env.rules.rule(hit.rule);
let id = rules::fingerprint(&rule.id, hit.value);
match self.secret_index.get(&id) {
Some(&i) => {
let s = &mut self.secrets[i];
s.occurrences += 1;
s.files.insert(transcript.path.clone());
}
None => {
self.secret_index.insert(id.clone(), self.secrets.len());
self.secrets.push(Secret {
id,
rule: rule.id.clone(),
severity: rule.severity,
preview: rules::preview(hit.value),
value: Some(hit.value.to_string()),
location: location(),
files: BTreeSet::from([transcript.path.clone()]),
occurrences: 1,
new: false,
progress: Progress::default(),
});
}
}
}
for host in hosts::extract(line) {
let entry = self.hosts.entry(host).or_default();
entry.0 += 1;
if entry.1.len() < MAX_HOST_LOCATIONS * 2 {
entry.1.push(location());
}
}
}
}
fn advance(&mut self, cursor: &mut Cursor, line: &str) {
if let Some(at) = line.find("\"timestamp\"") {
let value = line[at + 11..].trim_start_matches([':', ' ', '"']);
if let Some(day) = time::parse_iso(value) {
cursor.day = day;
}
}
if !line.contains("\"cwd\"") {
return;
}
let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else { return };
let field = |key: &str| value.get(key).and_then(|v| v.as_str()).filter(|s| !s.is_empty());
if let Some(cwd) = field("cwd") {
cursor.repo = Some(self.repos.resolve(cwd));
}
if let Some(branch) = field("gitBranch") {
cursor.branch = Some(branch.to_string());
}
}
fn repo_matches(&self, cursor: &Cursor) -> bool {
let Some(filter) = &self.repo_filter else { return true };
cursor
.repo
.as_ref()
.is_some_and(|r| r.name.to_lowercase().contains(filter) || r.remote.as_ref().is_some_and(|x| x.to_lowercase().contains(filter)))
}
fn finish(mut self, today: Day) -> (Vec<Secret>, Vec<Host>) {
let state = &self.env.state;
for s in &mut self.secrets {
s.new = !state.known.contains(&s.id);
s.progress = Progress { rotated: state.rotated.contains(&s.id), masked: false, ignored: state.ignored.contains(&s.id) };
}
for (id, record) in &state.masked {
let in_scope = self.cutoff.is_none_or(|c| record.location.day >= c)
&& self.repo_filter.as_ref().is_none_or(|f| record.location.repo_name().to_lowercase().contains(f));
if self.secret_index.contains_key(id) || !in_scope {
continue;
}
self.secrets.push(Secret {
id: id.clone(),
rule: record.rule.clone(),
severity: record.severity,
preview: record.preview.clone(),
value: None,
location: record.location.clone(),
files: record.edits.iter().map(|e| e.file.clone()).collect(),
occurrences: 0,
new: false,
progress: Progress { rotated: state.rotated.contains(id), masked: true, ignored: state.ignored.contains(id) },
});
}
self.secrets.sort_by(|a, b| {
(a.progress.ignored, a.severity, a.location.repo_name(), &a.rule).cmp(&(
b.progress.ignored,
b.severity,
b.location.repo_name(),
&b.rule,
))
});
let mut hosts: Vec<Host> = self
.hosts
.into_iter()
.map(|(host, (occurrences, mut locations))| {
locations.sort_by_key(|l| std::cmp::Reverse(l.day));
locations.truncate(MAX_HOST_LOCATIONS);
let (verdict, reason) = self.env.hosts.verdict(&host);
Host {
new: verdict == Verdict::Flagged && !state.known_hosts.contains(&host),
last_seen: locations.first().map_or(today, |l| l.day),
host,
verdict,
reason,
occurrences,
locations,
}
})
.collect();
hosts.sort_by(|a, b| (a.verdict, b.occurrences, &a.host).cmp(&(b.verdict, a.occurrences, &b.host)));
(self.secrets, hosts)
}
}