use super::app::{App, Modal, Tab, View, PERIODS};
use crate::model::{Host, Secret, Severity, Verdict};
use crate::report::{plural, repo_label};
use crate::time;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};
use ratatui::Frame;
const ACCENT: Color = Color::Cyan;
const BAD: Color = Color::Red;
const WARN: Color = Color::Yellow;
const GOOD: Color = Color::Green;
const DIM: Color = Color::DarkGray;
fn fg(color: Color) -> Style {
Style::default().fg(color)
}
fn dim(text: impl Into<String>) -> Span<'static> {
Span::styled(text.into(), fg(DIM))
}
fn plain(text: impl Into<String>) -> Span<'static> {
Span::raw(text.into())
}
fn colored(text: impl Into<String>, color: Color) -> Span<'static> {
Span::styled(text.into(), fg(color))
}
fn bold(text: impl Into<String>, color: Color) -> Span<'static> {
Span::styled(text.into(), fg(color).add_modifier(Modifier::BOLD))
}
fn heading(text: impl Into<String>) -> Line<'static> {
Line::from(bold(text.into().to_uppercase(), DIM))
}
fn severity_color(s: Severity) -> Color {
match s {
Severity::High => BAD,
Severity::Medium => WARN,
Severity::Low => DIM,
}
}
fn verdict_color(v: Verdict) -> Color {
match v {
Verdict::Flagged => BAD,
Verdict::Unknown => WARN,
Verdict::Allowed => GOOD,
}
}
fn cell(text: &str, width: usize) -> String {
let count = text.chars().count();
if count <= width {
format!("{text}{}", " ".repeat(width - count))
} else {
format!("{}…", text.chars().take(width.saturating_sub(1)).collect::<String>())
}
}
pub fn draw(frame: &mut Frame, app: &App) {
let filter_rows = u16::from(app.typing || !app.filter.is_empty());
let [header, body, filter, keys] =
Layout::vertical([Constraint::Length(2), Constraint::Min(3), Constraint::Length(filter_rows), Constraint::Length(1)])
.areas(frame.area());
draw_header(frame, app, header);
match (&app.view, app.tab) {
(Some(view), _) => draw_view(frame, view, body),
(None, Tab::Summary) => draw_summary(frame, app, body),
(None, Tab::Secrets) => draw_secrets(frame, app, body),
(None, Tab::Egress) => draw_egress(frame, app, body),
}
if filter_rows > 0 {
let cursor = if app.typing { "â–ˆ" } else { "" };
let hint = if app.typing { " enter keeps it, esc clears it" } else { " esc clears it" };
frame.render_widget(
Paragraph::new(Line::from(vec![bold(" filter: ", WARN), plain(format!("{}{cursor}", app.filter)), dim(hint)])),
filter,
);
}
draw_keys(frame, app, keys);
if let Some(modal) = &app.modal {
draw_modal(frame, modal);
}
}
fn draw_header(frame: &mut Frame, app: &App, area: Rect) {
let mut spans = vec![bold(" egrix ", ACCENT), plain(" ")];
for (i, tab) in Tab::ALL.iter().enumerate() {
let label = format!(" {} {} ", i + 1, tab.title());
spans.push(if *tab == app.tab {
Span::styled(label, Style::default().fg(Color::Black).bg(ACCENT).add_modifier(Modifier::BOLD))
} else {
plain(label)
});
}
let open = app.report.open_secrets().count();
let flagged = app.report.flagged_hosts().count();
let mut status = vec![dim(format!("period: {} · ", PERIODS[app.period].1))];
status.push(colored(format!("{} open", plural(open, "secret")), if open > 0 { BAD } else { GOOD }));
status.push(dim(" · "));
status.push(colored(plural(flagged, "flagged host"), if flagged > 0 { BAD } else { GOOD }));
status.push(plain(" "));
let [left, right] =
Layout::horizontal([Constraint::Min(10), Constraint::Length(status.iter().map(|s| s.content.chars().count() as u16).sum())])
.areas(area);
let block = Block::default().borders(Borders::BOTTOM).border_style(fg(DIM));
frame.render_widget(Paragraph::new(Line::from(spans)).block(block.clone()), left);
frame.render_widget(Paragraph::new(Line::from(status)).block(block), right);
}
fn draw_list(frame: &mut Frame, area: Rect, title: String, mut lines: Vec<Line<'static>>, selected: Option<usize>, empty: &str) {
let inner = Rect { x: area.x + 1, y: area.y, width: area.width.saturating_sub(2), height: area.height };
let [head, list] = Layout::vertical([Constraint::Length(1), Constraint::Min(1)]).areas(inner);
frame.render_widget(Paragraph::new(heading(title)), head);
if lines.is_empty() {
frame.render_widget(Paragraph::new(dim(empty.to_string())), list);
return;
}
if let Some(i) = selected {
lines[i] = std::mem::take(&mut lines[i]).patch_style(Style::default().add_modifier(Modifier::REVERSED));
}
let height = list.height as usize;
let scroll = selected.map_or(0, |i| i.saturating_sub(height.saturating_sub(2)));
frame.render_widget(Paragraph::new(lines).scroll((scroll as u16, 0)), list);
}
fn draw_detail(frame: &mut Frame, area: Rect, lines: Vec<Line<'static>>) {
let block = Block::default().borders(Borders::LEFT).border_style(fg(DIM)).padding(ratatui::widgets::Padding::horizontal(1));
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }).block(block), area);
}
fn field(key: &str, value: Vec<Span<'static>>) -> Line<'static> {
let mut spans = vec![dim(cell(key, 12))];
spans.extend(value);
Line::from(spans)
}
fn split(area: Rect) -> [Rect; 2] {
if area.width < 90 {
Layout::vertical([Constraint::Percentage(50), Constraint::Percentage(50)]).areas(area)
} else {
Layout::horizontal([Constraint::Percentage(58), Constraint::Percentage(42)]).areas(area)
}
}
fn draw_summary(frame: &mut Frame, app: &App, area: Rect) {
let r = &app.report;
let secrets: Vec<&Secret> = r.secrets.iter().collect();
let live = |f: fn(&&&Secret) -> bool| secrets.iter().filter(|s| !s.progress.ignored).filter(f).count();
let (unrotated, unmasked) = (live(|s| !s.progress.rotated), live(|s| !s.progress.masked));
let count = |v: Verdict| r.hosts.iter().filter(|h| h.verdict == v).count();
let agents: Vec<&str> = r.agents.iter().map(|a| a.name()).collect();
let stat = |label: &str, value: String, color: Color| Line::from(vec![dim(cell(label, 30)), colored(value, color)]);
let level = |n: usize, bad: Color| if n > 0 { bad } else { GOOD };
let mut lines = vec![
heading(format!("Last scan · {} · period: {}", time::format(r.today), PERIODS[app.period].1)),
stat("files read", r.scanned_files.to_string(), Color::Reset),
stat("agents", if agents.is_empty() { "none found".into() } else { agents.join(" ") }, Color::Reset),
stat("open secrets", r.open_secrets().count().to_string(), level(r.open_secrets().count(), BAD)),
stat("credential not rotated", unrotated.to_string(), level(unrotated, BAD)),
stat("history not masked", unmasked.to_string(), level(unmasked, WARN)),
stat("ignored (false positives)", secrets.iter().filter(|s| s.progress.ignored).count().to_string(), Color::Reset),
stat("flagged hosts", count(Verdict::Flagged).to_string(), level(count(Verdict::Flagged), BAD)),
stat("unknown hosts", count(Verdict::Unknown).to_string(), level(count(Verdict::Unknown), WARN)),
Line::default(),
heading("By repository"),
];
let rows = app.repos();
let width = rows.iter().map(|r| r.label.chars().count()).max().unwrap_or(10).clamp(10, (area.width as usize).saturating_sub(40));
lines.push(Line::from(vec![
dim(cell(if app.show_remote { "repository (remote)" } else { "repository (name)" }, width + 2)),
dim(" open high flagged unknown"),
]));
let first_row = lines.len();
for row in &rows {
let num = |n: usize, w: usize, color: Color| colored(format!("{n:>w$}"), if n > 0 { color } else { DIM });
lines.push(Line::from(vec![
plain(cell(&row.label, width + 2)),
num(row.open, 7, BAD),
num(row.high, 7, BAD),
num(row.flagged, 9, BAD),
num(row.unknown, 9, WARN),
]));
}
lines.push(Line::default());
lines.push(if r.scanned_files == 0 {
Line::from(dim("No agent history found on this machine."))
} else if r.open_secrets().next().is_some() {
Line::from(vec![
bold("Next: ", Color::Reset),
colored("enter", ACCENT),
dim(" on a repository opens its secrets. Rotate the credentials, then mask the history."),
])
} else {
Line::from(dim("No open secrets. Review the unknown hosts on the Egress screen."))
});
let inner = Rect { x: area.x + 1, y: area.y, width: area.width.saturating_sub(2), height: area.height };
if !rows.is_empty() {
let i = first_row + app.cursor();
lines[i] = std::mem::take(&mut lines[i]).patch_style(Style::default().add_modifier(Modifier::REVERSED));
}
frame.render_widget(Paragraph::new(lines), inner);
}
fn draw_secrets(frame: &mut Frame, app: &App, area: Rect) {
let [list, detail] = split(area);
let rows = app.secrets();
let (mut lines, mut selected, mut last) = (Vec::new(), None, None::<String>);
for (n, &i) in rows.iter().enumerate() {
let s = &app.report.secrets[i];
let key = if s.progress.ignored { "ignored (false positives)".to_string() } else { app.group.key(s) };
if last.as_ref() != Some(&key) {
let members = rows.iter().filter(|&&j| {
let o = &app.report.secrets[j];
if o.progress.ignored {
key.starts_with("ignored")
} else {
!key.starts_with("ignored") && app.group.key(o) == key
}
});
lines.push(Line::from(vec![
bold(key.clone(), if s.progress.ignored { DIM } else { ACCENT }),
dim(format!(" ({})", members.count())),
]));
last = Some(key);
}
if n == app.cursor() {
selected = Some(lines.len());
}
let (glyph, color) = if s.progress.ignored {
("–", DIM)
} else if !s.is_open() {
("✓", GOOD)
} else {
(s.severity.glyph(), severity_color(s.severity))
};
let body = if s.is_open() { Color::Reset } else { DIM };
lines.push(Line::from(vec![
colored(format!(" {glyph} "), color),
colored(cell(&s.rule, 26), body),
colored("t", if s.progress.rotated { GOOD } else { DIM }),
colored("m ", if s.progress.masked { GOOD } else { DIM }),
dim(cell(app.display_value(s), 30)),
dim(format!(
" {}",
if app.group == crate::cli::Group::Agent { s.location.repo_name().to_string() } else { s.location.agent.to_string() }
)),
]));
}
draw_list(
frame,
list,
format!("Secrets by {} · t rotated · m masked", app.group.name()),
lines,
selected,
"Nothing matches this filter and period.",
);
let Some(s) = app.selected_secret() else { return draw_detail(frame, detail, vec![heading("Detail")]) };
let loc = &s.location;
let revealed = app.revealed.contains(&s.id);
let mut lines = vec![
heading("Detail"),
field("rule", vec![plain(s.rule.clone())]),
field("severity", vec![colored(format!("{} {}", s.severity.glyph(), s.severity.name()), severity_color(s.severity))]),
field("value", vec![colored(app.display_value(s).to_string(), if revealed { BAD } else { Color::Reset })]),
field("agent", vec![plain(loc.agent.to_string())]),
field(
"repository",
vec![
plain(repo_label(loc.repo.as_ref(), app.show_remote)),
dim(loc.branch.as_ref().map(|b| format!(" @ {b}")).unwrap_or_default()),
],
),
field("file", vec![plain(format!("{}:{}", app.env.paths.tilde(&loc.file), loc.line))]),
field(
"exposed",
vec![
plain(time::ago(loc.day, app.report.today)),
dim(format!(" ({})", time::format(loc.day))),
colored(if s.new { " new" } else { "" }, WARN),
],
),
field("id", vec![dim(s.id.clone())]),
Line::default(),
];
if s.progress.ignored {
lines.push(Line::from(vec![dim("Marked as a false positive. "), colored("i", ACCENT), dim(" undoes it.")]));
} else {
let step = |done: bool, text: &str, key: &str| {
Line::from(vec![
colored(format!("[{}] {text} ", if done { "x" } else { " " }), if done { GOOD } else { Color::Reset }),
colored(key.to_string(), ACCENT),
])
};
lines.push(step(s.progress.rotated, "1. Rotate the credential at the provider", "t"));
lines.push(step(s.progress.masked, "2. Mask it in the history", if s.progress.masked { "u undoes" } else { "m" }));
lines.push(Line::default());
lines.push(Line::from(match (s.progress.rotated, s.progress.masked) {
(true, true) => vec![colored("Resolved.", GOOD)],
(false, true) => vec![colored("Masked, but the credential is still valid until you rotate it.", WARN)],
_ => vec![colored("enter", ACCENT), dim(" shows the transcript. "), colored("i", ACCENT), dim(" marks a false positive.")],
}));
}
draw_detail(frame, detail, lines);
}
fn draw_egress(frame: &mut Frame, app: &App, area: Rect) {
let [list, detail] = split(area);
let rows = app.hosts();
let (mut lines, mut selected, mut last) = (Vec::new(), None, None::<Verdict>);
for (n, &i) in rows.iter().enumerate() {
let h = &app.report.hosts[i];
if last != Some(h.verdict) {
let members = rows.iter().filter(|&&j| app.report.hosts[j].verdict == h.verdict).count();
lines.push(Line::from(vec![
bold(format!("{} {}", h.verdict.glyph(), h.verdict.name()), verdict_color(h.verdict)),
dim(format!(" ({members})")),
]));
last = Some(h.verdict);
}
if n == app.cursor() {
selected = Some(lines.len());
}
lines.push(Line::from(vec![
colored(format!(" {} ", h.verdict.glyph()), verdict_color(h.verdict)),
plain(cell(&h.host, 28)),
dim(cell(&h.reason, 18)),
dim(format!("{:>5}x {}", h.occurrences, h.repo_name())),
]));
}
draw_list(frame, list, "External destinations".into(), lines, selected, "No hosts match this filter and period.");
let Some(h) = app.selected_host() else { return draw_detail(frame, detail, vec![heading("Detail")]) };
let key = |k: &str| colored(k.to_string(), ACCENT);
let advice = match h.verdict {
Verdict::Unknown => vec![
dim("Do you know this host? "),
key("a"),
dim(" allows it, "),
key("d"),
dim(" flags it. The choice holds for later scans."),
],
Verdict::Flagged => vec![key("enter"), dim(" shows what was sent or fetched. "), key("a"), dim(" if it is a false positive.")],
Verdict::Allowed => vec![dim("Allowed. "), key("d"), dim(" flags it instead.")],
};
draw_detail(frame, detail, host_detail(h, app, advice));
}
fn host_detail(h: &Host, app: &App, advice: Vec<Span<'static>>) -> Vec<Line<'static>> {
let agents: std::collections::BTreeSet<&str> = h.locations.iter().map(|l| l.agent.name()).collect();
vec![
heading("Detail"),
field("host", vec![plain(h.host.clone())]),
field("verdict", vec![colored(format!("{} {}", h.verdict.glyph(), h.verdict.name()), verdict_color(h.verdict))]),
field("reason", vec![plain(h.reason.clone())]),
field("occurrences", vec![plain(h.occurrences.to_string())]),
field("agents", vec![plain(agents.into_iter().collect::<Vec<_>>().join(" "))]),
field("repository", vec![plain(repo_label(h.locations.first().and_then(|l| l.repo.as_ref()), app.show_remote))]),
field("last seen", vec![plain(time::ago(h.last_seen, app.report.today)), dim(format!(" ({})", time::format(h.last_seen)))]),
Line::default(),
Line::from(advice),
]
}
fn draw_view(frame: &mut Frame, view: &View, area: Rect) {
let inner = Rect { x: area.x + 1, y: area.y, width: area.width.saturating_sub(2), height: area.height };
let shown = view.pages.len();
let more = if view.total > shown { format!(" (of {} in total)", view.total) } else { String::new() };
let mut lines = vec![heading(format!("Transcript · {} · sighting {} of {shown}{more}", view.title, view.page + 1))];
let Some(page) = view.pages.get(view.page) else {
lines.push(Line::from(dim("The transcript file can no longer be read.")));
return frame.render_widget(Paragraph::new(lines), inner);
};
lines.push(Line::from(dim(page.header.clone())));
lines.push(Line::default());
for l in &page.lines {
let mut spans = vec![dim(format!("{:>6} {} ", l.number, cell(&l.role, 10)))];
let lower = l.text.to_lowercase();
match lower.find(&view.needle.to_lowercase()).filter(|_| !view.needle.is_empty() && lower.len() == l.text.len()) {
Some(at) => {
let end = at + view.needle.len();
spans.push(plain(l.text[..at].to_string()));
spans.push(Span::styled(l.text[at..end].to_string(), Style::default().fg(Color::Black).bg(WARN)));
spans.push(plain(l.text[end..].to_string()));
}
None => spans.push(if l.hit { plain(l.text.clone()) } else { dim(l.text.clone()) }),
}
lines.push(Line::from(spans));
}
if page.lines.is_empty() {
lines.push(Line::from(dim("The transcript file can no longer be read.")));
}
lines.push(Line::default());
lines.push(Line::from(dim("Read-only. Secrets in the excerpt are redacted.")));
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}
fn draw_keys(frame: &mut Frame, app: &App, area: Rect) {
let keys: Vec<(&str, &str)> = if app.view.is_some() {
vec![("n", "next"), ("p", "previous"), ("esc", "back")]
} else {
let mut k = vec![("1-3", "screens"), ("↑↓", "move")];
k.extend(match app.tab {
Tab::Summary => vec![("enter", "open repository"), ("u", if app.show_remote { "show name" } else { "show remote" })],
Tab::Secrets => {
vec![("enter", "transcript"), ("t", "rotated"), ("m", "mask"), ("M", "mask all"), ("i", "ignore"), ("/", "filter")]
}
Tab::Egress => vec![("enter", "transcript"), ("a", "allow"), ("d", "deny"), ("/", "filter")],
});
k.extend([("s", "period"), ("?", "help"), ("q", "quit")]);
k
};
let mut spans = vec![plain(" ")];
for (key, label) in keys {
spans.push(bold(key, ACCENT));
spans.push(dim(format!(" {label} ")));
}
frame.render_widget(Paragraph::new(Line::from(spans)), area);
}
fn draw_modal(frame: &mut Frame, modal: &Modal) {
let (title, lines, footer) = match modal {
Modal::Confirm { lines, label, .. } => (" Confirm ", lines, format!("enter {label} esc cancel")),
Modal::Info { title, lines } => (*title, lines, "esc close".to_string()),
};
let area = frame.area();
let width = (lines.iter().map(|l| l.chars().count()).max().unwrap_or(20).max(footer.len()) as u16 + 4)
.min(area.width.saturating_sub(4))
.max(24);
let wrapped: u16 = lines.iter().map(|l| (l.chars().count() as u16 / width.saturating_sub(4).max(1)) + 1).sum();
let height = (wrapped + 4).min(area.height.saturating_sub(2));
let rect =
Rect { x: area.x + (area.width.saturating_sub(width)) / 2, y: area.y + (area.height.saturating_sub(height)) / 2, width, height };
let mut text: Vec<Line> = lines.iter().map(|l| Line::from(plain(l.clone()))).collect();
text.push(Line::default());
text.push(Line::from(colored(footer, ACCENT)));
let block =
Block::default().borders(Borders::ALL).border_style(fg(ACCENT)).title(title).padding(ratatui::widgets::Padding::horizontal(1));
frame.render_widget(Clear, rect);
frame.render_widget(Paragraph::new(text).wrap(Wrap { trim: false }).block(block), rect);
}