egrix 0.1.0

Find leaked credentials and suspicious network destinations in AI agent transcripts. Local, offline, redacted by default.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Dashboard state and the actions a key can trigger. No drawing here, and no
//! logic the commands do not also have: every action calls the same core.

use crate::cli::Group;
use crate::context::{self, ExcerptLine};
use crate::model::{Host, Report, Secret, Severity, Verdict};
use crate::report::{plural, repo_label};
use crate::scan::{self, Env, Options};
use crate::state::State;
use crate::{commands, fix, time};
use anyhow::Result;
use std::collections::HashSet;

pub const PERIODS: [(Option<i64>, &str); 3] = [(None, "all time"), (Some(30), "30 days"), (Some(7), "7 days")];
const EXCERPT_RADIUS: usize = 4;
const MAX_PAGES: usize = 5;

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Tab {
    Summary,
    Secrets,
    Egress,
}

impl Tab {
    pub const ALL: [Tab; 3] = [Tab::Summary, Tab::Secrets, Tab::Egress];
    pub fn title(self) -> &'static str {
        match self {
            Tab::Summary => "Summary",
            Tab::Secrets => "Secrets",
            Tab::Egress => "Egress",
        }
    }
}

/// One repository on the summary screen.
pub struct RepoRow {
    pub name: String,
    pub label: String,
    pub open: usize,
    pub high: usize,
    pub flagged: usize,
    pub unknown: usize,
}

/// A transcript excerpt on screen: one page per sighting.
pub struct View {
    pub title: String,
    pub needle: String,
    pub pages: Vec<Page>,
    pub page: usize,
    pub total: usize,
}

pub struct Page {
    pub header: String,
    pub lines: Vec<ExcerptLine>,
}

/// Something that needs a yes before it happens.
pub enum Pending {
    Mask(Vec<String>),
    Unmask(Vec<String>),
    Reveal(String),
}

pub enum Modal {
    Confirm { lines: Vec<String>, label: &'static str, action: Pending },
    Info { title: &'static str, lines: Vec<String> },
}

pub struct App {
    pub env: Env,
    pub report: Report,
    pub tab: Tab,
    selected: [usize; 3],
    pub group: Group,
    pub filter: String,
    /// The filter line has the keyboard.
    pub typing: bool,
    pub period: usize,
    pub show_remote: bool,
    pub revealed: HashSet<String>,
    pub view: Option<View>,
    pub modal: Option<Modal>,
    pub quit: bool,
}

impl App {
    pub fn new(env: Env) -> Self {
        let report = scan::scan(&env, &Options::default());
        Self {
            env,
            report,
            tab: Tab::Summary,
            selected: [0; 3],
            group: Group::Repo,
            filter: String::new(),
            typing: false,
            period: 0,
            show_remote: false,
            revealed: HashSet::new(),
            view: None,
            modal: None,
            quit: false,
        }
    }

    // ---- what is on screen -------------------------------------------------

    fn in_period(&self, day: time::Day) -> bool {
        PERIODS[self.period].0.is_none_or(|n| day >= self.report.today - n)
    }

    fn matches(&self, fields: &[&str]) -> bool {
        let needle = self.filter.to_lowercase();
        needle.is_empty() || fields.iter().any(|f| f.to_lowercase().contains(&needle))
    }

    /// Indexes into `report.secrets`, in display order: grouped, worst first,
    /// false positives last.
    pub fn secrets(&self) -> Vec<usize> {
        let mut rows: Vec<usize> = (0..self.report.secrets.len())
            .filter(|&i| {
                let s = &self.report.secrets[i];
                let remote = repo_label(s.location.repo.as_ref(), true);
                self.in_period(s.location.day)
                    && self.matches(&[&s.rule, s.location.repo_name(), &remote, s.location.agent.name(), &s.preview, &s.id])
            })
            .collect();
        rows.sort_by_key(|&i| {
            let s = &self.report.secrets[i];
            (s.progress.ignored, self.group.key(s), s.severity, s.rule.clone())
        });
        rows
    }

    /// Indexes into `report.hosts`; the report already sorts worst first.
    pub fn hosts(&self) -> Vec<usize> {
        (0..self.report.hosts.len())
            .filter(|&i| {
                let h = &self.report.hosts[i];
                self.in_period(h.last_seen) && self.matches(&[&h.host, &h.reason, h.repo_name()])
            })
            .collect()
    }

    pub fn repos(&self) -> Vec<RepoRow> {
        let secrets: Vec<&Secret> = self.report.secrets.iter().filter(|s| self.in_period(s.location.day)).collect();
        let hosts: Vec<&Host> = self.report.hosts.iter().filter(|h| self.in_period(h.last_seen)).collect();
        let mut names: Vec<&str> = Vec::new();
        for n in secrets
            .iter()
            .map(|s| s.location.repo_name())
            .chain(hosts.iter().filter(|h| h.verdict != Verdict::Allowed).map(|h| h.repo_name()))
        {
            if !names.contains(&n) {
                names.push(n);
            }
        }
        names
            .into_iter()
            .map(|name| {
                let open: Vec<&&Secret> = secrets.iter().filter(|s| s.location.repo_name() == name && s.is_open()).collect();
                let repo = secrets
                    .iter()
                    .map(|s| &s.location)
                    .chain(hosts.iter().flat_map(|h| h.locations.first()))
                    .find(|l| l.repo_name() == name)
                    .and_then(|l| l.repo.as_ref());
                let count = |v: Verdict| hosts.iter().filter(|h| h.repo_name() == name && h.verdict == v).count();
                RepoRow {
                    name: name.to_string(),
                    label: repo_label(repo, self.show_remote),
                    open: open.len(),
                    high: open.iter().filter(|s| s.severity == Severity::High).count(),
                    flagged: count(Verdict::Flagged),
                    unknown: count(Verdict::Unknown),
                }
            })
            .collect()
    }

    pub fn row_count(&self) -> usize {
        match self.tab {
            Tab::Summary => self.repos().len(),
            Tab::Secrets => self.secrets().len(),
            Tab::Egress => self.hosts().len(),
        }
    }

    pub fn cursor(&self) -> usize {
        self.selected[self.tab as usize].min(self.row_count().saturating_sub(1))
    }

    pub fn selected_secret(&self) -> Option<&Secret> {
        self.secrets().get(self.cursor()).map(|&i| &self.report.secrets[i])
    }

    pub fn selected_host(&self) -> Option<&Host> {
        self.hosts().get(self.cursor()).map(|&i| &self.report.hosts[i])
    }

    /// The value to show for a secret: raw only after an explicit reveal.
    pub fn display_value<'a>(&self, s: &'a Secret) -> &'a str {
        match &s.value {
            Some(v) if self.revealed.contains(&s.id) => v,
            _ => &s.preview,
        }
    }

    // ---- navigation --------------------------------------------------------

    pub fn go(&mut self, tab: Tab) {
        self.tab = tab;
        self.view = None;
    }

    pub fn next_tab(&mut self) {
        self.go(Tab::ALL[(self.tab as usize + 1) % Tab::ALL.len()]);
    }

    pub fn move_by(&mut self, delta: isize) {
        let last = self.row_count().saturating_sub(1) as isize;
        self.selected[self.tab as usize] = (self.cursor() as isize + delta).clamp(0, last) as usize;
    }

    fn reset_cursor(&mut self) {
        self.selected = [0; 3];
    }

    pub fn cycle_period(&mut self) {
        self.period = (self.period + 1) % PERIODS.len();
        self.reset_cursor();
    }

    pub fn cycle_group(&mut self) {
        self.group = self.group.next();
        self.reset_cursor();
    }

    pub fn set_filter(&mut self, filter: String) {
        self.filter = filter;
        self.reset_cursor();
    }

    /// Enter: drill into whatever is selected.
    pub fn open(&mut self) {
        match self.tab {
            Tab::Summary => {
                if let Some(row) = self.repos().get(self.cursor()) {
                    self.filter = row.name.clone();
                    self.group = Group::Repo;
                    self.reset_cursor();
                    self.tab = Tab::Secrets;
                }
            }
            Tab::Secrets => self.view = self.selected_secret().map(|s| self.secret_view(s)),
            Tab::Egress => self.view = self.selected_host().map(|h| self.host_view(h)),
        }
    }

    fn page(&self, loc: &crate::model::Location, needle: &str) -> Page {
        Page {
            header: format!(
                "{}:{}  {}  {}  {}",
                self.env.paths.tilde(&loc.file),
                loc.line,
                loc.agent,
                loc.repo_name(),
                time::format(loc.day)
            ),
            lines: context::excerpt(&loc.file, loc.line, needle, &self.env.rules, EXCERPT_RADIUS).unwrap_or_default(),
        }
    }

    fn secret_view(&self, s: &Secret) -> View {
        let needle = if s.progress.masked { fix::marker(&s.id) } else { s.preview.clone() };
        View { title: s.rule.clone(), pages: vec![self.page(&s.location, &needle)], needle, page: 0, total: 1 }
    }

    fn host_view(&self, h: &Host) -> View {
        let pages = h.locations.iter().take(MAX_PAGES).map(|l| self.page(l, &h.host)).collect();
        View { title: h.host.clone(), needle: h.host.clone(), pages, page: 0, total: h.occurrences }
    }

    // ---- actions -----------------------------------------------------------

    fn save(&mut self) -> Result<()> {
        self.env.save_state()
    }

    fn toggle(&mut self, pick: fn(&mut State) -> &mut std::collections::BTreeSet<String>) -> Result<()> {
        let Some(id) = self.selected_secret().map(|s| s.id.clone()) else { return Ok(()) };
        let on = State::toggle(pick(&mut self.env.state), &id);
        self.env.state.known.insert(id.clone());
        let state = &self.env.state;
        if let Some(s) = self.report.secrets.iter_mut().find(|s| s.id == id) {
            s.progress.rotated = state.rotated.contains(&id);
            s.progress.ignored = state.ignored.contains(&id);
            s.new = false;
        }
        let _ = on;
        self.save()
    }

    pub fn toggle_rotated(&mut self) -> Result<()> {
        if self.selected_secret().is_some_and(|s| s.progress.ignored) {
            return Ok(());
        }
        self.toggle(|s| &mut s.rotated)
    }

    pub fn toggle_ignored(&mut self) -> Result<()> {
        self.toggle(|s| &mut s.ignored)
    }

    pub fn ask_mask_selected(&mut self) {
        let Some(s) = self.selected_secret().filter(|s| s.value.is_some() && !s.progress.ignored) else { return };
        let mut lines = vec![
            format!("Mask {} in {}?", s.rule, plural(s.files.len(), "file")),
            String::new(),
            format!("A copy of each file is kept in {}. u undoes it.", self.env.paths.tilde(&self.env.paths.backup_dir())),
        ];
        if !s.progress.rotated {
            lines.push("This does not revoke the credential: rotate it at the provider.".into());
        }
        self.modal = Some(Modal::Confirm { lines, label: "Mask", action: Pending::Mask(vec![s.id.clone()]) });
    }

    pub fn ask_mask_all(&mut self) {
        let targets: Vec<&Secret> =
            self.secrets().into_iter().map(|i| &self.report.secrets[i]).filter(|s| s.value.is_some() && !s.progress.ignored).collect();
        if targets.is_empty() {
            self.info("Mask all", vec!["Nothing left to mask in this list.".into()]);
            return;
        }
        let files: HashSet<_> = targets.iter().flat_map(|s| s.files.iter()).collect();
        let scope = if self.filter.is_empty() {
            "No filter is active: this is the whole list.".to_string()
        } else {
            format!("Only what matches the filter \"{}\".", self.filter)
        };
        let lines = vec![
            format!("Mask {} in {}?", plural(targets.len(), "secret"), plural(files.len(), "file")),
            scope,
            String::new(),
            format!("A copy of each file is kept in {}. U undoes it.", self.env.paths.tilde(&self.env.paths.backup_dir())),
            "This revokes nothing: rotate every credential at the provider.".into(),
        ];
        let ids = targets.iter().map(|s| s.id.clone()).collect();
        self.modal = Some(Modal::Confirm { lines, label: "Mask all", action: Pending::Mask(ids) });
    }

    pub fn unmask_selected(&mut self) -> Result<()> {
        match self.selected_secret().filter(|s| s.progress.masked).map(|s| s.id.clone()) {
            Some(id) => self.apply(Pending::Unmask(vec![id])),
            None => Ok(()),
        }
    }

    pub fn ask_unmask_all(&mut self) {
        let ids: Vec<String> =
            self.secrets().into_iter().map(|i| &self.report.secrets[i]).filter(|s| s.progress.masked).map(|s| s.id.clone()).collect();
        if ids.is_empty() {
            self.info("Undo all", vec!["Nothing in this list is masked.".into()]);
            return;
        }
        let lines = vec![
            format!("Restore {}?", plural(ids.len(), "masked secret")),
            "The values go back into the transcripts in plain text.".into(),
        ];
        self.modal = Some(Modal::Confirm { lines, label: "Undo all", action: Pending::Unmask(ids) });
    }

    pub fn toggle_reveal(&mut self) {
        let Some(s) = self.selected_secret().filter(|s| s.value.is_some()) else { return };
        let id = s.id.clone();
        if !self.revealed.remove(&id) {
            let lines = vec!["Show the full value on screen?".into(), "Anyone watching or recording this terminal will see it.".into()];
            self.modal = Some(Modal::Confirm { lines, label: "Reveal", action: Pending::Reveal(id) });
        }
    }

    pub fn set_host(&mut self, allow: bool) -> Result<()> {
        let Some(host) = self.selected_host().map(|h| h.host.clone()) else { return Ok(()) };
        self.env.hosts.set(&host, allow);
        self.env.save_hosts()?;
        for h in &mut self.report.hosts {
            (h.verdict, h.reason) = self.env.hosts.verdict(&h.host);
            h.new = h.verdict == Verdict::Flagged && !self.env.state.known_hosts.contains(&h.host);
        }
        self.report.hosts.sort_by(|a, b| (a.verdict, b.occurrences, &a.host).cmp(&(b.verdict, a.occurrences, &b.host)));
        Ok(())
    }

    pub fn accept_baseline(&mut self) -> Result<()> {
        let added = commands::accept(&mut self.env.state, &self.report);
        self.save()?;
        self.rescan();
        self.info("Baseline", vec![format!("{} accepted.", plural(added, "finding")), "`egrix scan` now exits 1 only on new ones.".into()]);
        Ok(())
    }

    /// Run a confirmed action.
    pub fn apply(&mut self, action: Pending) -> Result<()> {
        match action {
            Pending::Reveal(id) => {
                self.revealed.insert(id);
            }
            Pending::Mask(ids) => {
                for id in ids {
                    let Some(secret) = self.report.secrets.iter().find(|s| s.id == id).cloned() else { continue };
                    fix::mask(&self.env.paths, &mut self.env.state, &secret)?;
                    self.env.state.known.insert(id.clone());
                    self.revealed.remove(&id);
                }
                self.save()?;
                self.rescan();
            }
            Pending::Unmask(ids) => {
                for id in ids {
                    fix::unmask(&self.env.rules, &mut self.env.state, &id)?;
                }
                self.save()?;
                self.rescan();
            }
        }
        Ok(())
    }

    fn rescan(&mut self) {
        self.report = scan::scan(&self.env, &Options::default());
    }

    pub fn info(&mut self, title: &'static str, lines: Vec<String>) {
        self.modal = Some(Modal::Info { title, lines });
    }

    pub fn help(&mut self) {
        let rows = [
            ("1 2 3, tab", "switch screen"),
            ("↑ ↓, j k", "move"),
            ("enter", "Summary: open the repository's secrets. Elsewhere: show the transcript"),
            ("/", "filter; esc clears it"),
            ("s", "period: all time, 30 days, 7 days"),
            ("b", "accept everything listed as the baseline"),
            ("u", "Summary: name or remote. Secrets: undo the mask on this one"),
            ("t", "Secrets: mark the credential as rotated"),
            ("m, M", "Secrets: mask this one, or everything in the list"),
            ("U", "Secrets: undo every mask in the list"),
            ("i", "Secrets: mark or unmark a false positive"),
            ("r", "Secrets: reveal the value"),
            ("g", "Secrets: change the grouping"),
            ("a, d", "Egress: allow or deny the host"),
            ("q", "quit"),
        ];
        self.info("Keys", rows.iter().map(|(k, v)| format!("{k:<11} {v}")).collect());
    }
}