aiward 0.5.27

Local-first AI secret firewall for development environments.
Documentation
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
use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use ratatui::{
    layout::{Constraint, Direction, Layout, Margin},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Paragraph, Wrap},
    Frame,
};

use crate::{detection, policy::AccessRequest};

use super::{ApprovalScope, PolicyEvaluation};

// ── Ward design system ────────────────────────────────────────────────────────

const BG: Color = Color::Rgb(13, 13, 15);
const SURFACE: Color = Color::Rgb(20, 20, 22);
const BORDER: Color = Color::Rgb(30, 30, 34);
const TEXT: Color = Color::Rgb(226, 226, 230);
const MUTED: Color = Color::Rgb(90, 90, 106);
const ACCENT: Color = Color::Rgb(124, 110, 245);
const RED: Color = Color::Rgb(248, 113, 113);
const CYAN: Color = Color::Rgb(34, 211, 238);
const MAGENTA: Color = Color::Rgb(192, 132, 252);
const SEL_BG: Color = Color::Rgb(28, 26, 46);

struct State<'a> {
    request: &'a AccessRequest,
    evaluation: &'a PolicyEvaluation,
    choices: Vec<ApprovalScope>,
    selected: usize,
}

impl<'a> State<'a> {
    fn new(
        request: &'a AccessRequest,
        evaluation: &'a PolicyEvaluation,
        choices: Vec<ApprovalScope>,
    ) -> Self {
        Self {
            request,
            evaluation,
            choices,
            selected: 0,
        }
    }

    fn move_up(&mut self) {
        if self.selected > 0 {
            self.selected -= 1;
        }
    }

    fn move_down(&mut self) {
        if self.selected + 1 < self.choices.len() {
            self.selected += 1;
        }
    }

    fn current(&self) -> ApprovalScope {
        self.choices[self.selected]
    }

    fn is_critical(&self) -> bool {
        detection::has_critical_findings(&self.evaluation.findings)
    }
}

pub fn run_approval_tui(
    request: &AccessRequest,
    evaluation: &PolicyEvaluation,
    choices: Vec<ApprovalScope>,
) -> Result<ApprovalScope> {
    let mut terminal = ratatui::init();
    let mut state = State::new(request, evaluation, choices);
    let result = run_loop(&mut terminal, &mut state);
    ratatui::restore();
    result
}

fn run_loop(terminal: &mut ratatui::DefaultTerminal, state: &mut State) -> Result<ApprovalScope> {
    loop {
        terminal.draw(|f| draw(f, state))?;

        if let Event::Key(key) = event::read()? {
            if key.kind != KeyEventKind::Press {
                continue;
            }
            match key.code {
                KeyCode::Up | KeyCode::Char('k') => state.move_up(),
                KeyCode::Down | KeyCode::Char('j') => state.move_down(),
                KeyCode::Enter | KeyCode::Char(' ') => return Ok(state.current()),
                KeyCode::Esc | KeyCode::Char('q') => {
                    // Return Deny on escape/quit if it's in the list, otherwise first choice.
                    let deny = state
                        .choices
                        .iter()
                        .position(|s| *s == ApprovalScope::Deny)
                        .unwrap_or(0);
                    return Ok(state.choices[deny]);
                }
                KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                    let deny = state
                        .choices
                        .iter()
                        .position(|s| *s == ApprovalScope::Deny)
                        .unwrap_or(0);
                    return Ok(state.choices[deny]);
                }
                _ => {}
            }
        }
    }
}

fn draw(f: &mut Frame, state: &State) {
    let area = f.area();
    f.render_widget(
        ratatui::widgets::Block::default().style(Style::default().bg(BG)),
        area,
    );

    // Title bar
    let title_bar_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Min(0)])
        .split(area);

    let title = Paragraph::new(Line::from(vec![
        Span::styled(" ward ", Style::default().fg(TEXT).bold()),
        Span::styled("· access request", Style::default().fg(MUTED)),
    ]))
    .style(Style::default().bg(SURFACE));
    f.render_widget(title, title_bar_chunks[0]);

    // Horizontal split: left command panel / right details panel
    let body = title_bar_chunks[1];
    let panels = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(40), Constraint::Percentage(60)])
        .split(body);

    draw_left(f, state, panels[0]);
    draw_right(f, state, panels[1]);
}

fn draw_left(f: &mut Frame, state: &State, area: ratatui::layout::Rect) {
    let block = Block::default()
        .borders(Borders::RIGHT)
        .border_type(BorderType::Plain)
        .border_style(Style::default().fg(BORDER))
        .style(Style::default().bg(BG));
    f.render_widget(block, area);

    let inner = area.inner(Margin {
        horizontal: 2,
        vertical: 1,
    });

    let agent_label = state.request.agent.as_deref().unwrap_or("agent");
    let badge = Line::from(vec![Span::styled(
        format!("{agent_label} "),
        Style::default()
            .fg(MAGENTA)
            .bg(Color::Rgb(42, 26, 58))
            .add_modifier(Modifier::BOLD),
    )]);

    let cmd_lines = build_command_lines(state.request);

    let mut all_lines = vec![badge, Line::raw("")];
    all_lines.extend(cmd_lines);

    let paragraph = Paragraph::new(all_lines).wrap(Wrap { trim: false });
    f.render_widget(paragraph, inner);
}

fn build_command_lines(request: &AccessRequest) -> Vec<Line<'static>> {
    let agent = request.agent.clone().unwrap_or_default();
    let env_list = request.env.join(" ");
    let action = request.action.clone().unwrap_or_default();
    let command = request.command.clone();

    let prompt = Span::styled("", Style::default().fg(ACCENT).bold());
    let plain = |s: &str| Span::styled(s.to_string(), Style::default().fg(TEXT));
    let cyan_span = |s: &str| Span::styled(s.to_string(), Style::default().fg(CYAN));
    let muted_span = |s: &str| Span::styled(s.to_string(), Style::default().fg(MUTED));
    let cont = || muted_span(" \\");

    let mut lines: Vec<Line<'static>> = vec![Line::from(vec![prompt, plain("ward run"), cont()])];

    if !agent.is_empty() {
        lines.push(Line::from(vec![
            plain("    --agent "),
            cyan_span(&format!("\"{agent}\"")),
            cont(),
        ]));
    }

    if !env_list.is_empty() {
        lines.push(Line::from(vec![
            plain("    --env "),
            cyan_span(&env_list),
            cont(),
        ]));
    }

    if !action.is_empty() {
        lines.push(Line::from(vec![
            plain("    --action "),
            plain(&format!("\"{action}\"")),
            cont(),
        ]));
    }

    // Final line: -- command (no trailing backslash)
    lines.push(Line::from(vec![plain("    -- "), plain(&command)]));

    lines
}

fn draw_right(f: &mut Frame, state: &State, area: ratatui::layout::Rect) {
    let block = Block::default().style(Style::default().bg(BG));
    f.render_widget(block, area);

    let inner = area.inner(Margin {
        horizontal: 2,
        vertical: 1,
    });

    // Stack: title, blank, info table, blank, [warning], scope list
    let critical = state.is_critical();
    let warning_height: u16 = if critical { 3 } else { 0 };
    let info_rows = info_row_count(state.request);
    let scope_height = state.choices.len() as u16;

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),              // "Ward access request" title
            Constraint::Length(1),              // blank
            Constraint::Length(info_rows),      // info table
            Constraint::Length(1),              // blank
            Constraint::Length(warning_height), // critical warning (0 if none)
            Constraint::Length(scope_height),   // scope list
            Constraint::Min(0),
        ])
        .split(inner);

    // Title
    let title = Paragraph::new(Line::from(Span::styled(
        "Ward access request",
        Style::default().fg(ACCENT).bold(),
    )));
    f.render_widget(title, chunks[0]);

    // Info table
    draw_info_table(f, state.request, chunks[2]);

    // Critical warning
    if critical {
        draw_critical_warning(f, chunks[4]);
    }

    // Scope list
    draw_scope_list(f, state, chunks[5]);
}

fn info_row_count(request: &AccessRequest) -> u16 {
    let mut count = 2u16; // project + command always present
    if request.agent.is_some() {
        count += 1;
    }
    if request.branch.is_some() {
        count += 1;
    }
    if request.action.is_some() {
        count += 1;
    }
    if !request.env.is_empty() {
        count += 1;
    }
    count
}

fn draw_info_table(f: &mut Frame, request: &AccessRequest, area: ratatui::layout::Rect) {
    let label_style = Style::default().fg(MUTED).add_modifier(Modifier::BOLD);
    let value_style = Style::default().fg(TEXT);

    let mut lines: Vec<Line<'static>> = Vec::new();

    lines.push(info_row(
        "PROJECT",
        &request.project,
        label_style,
        value_style,
    ));

    if let Some(agent) = &request.agent {
        lines.push(info_row("AGENT", agent, label_style, value_style));
    }
    if let Some(branch) = &request.branch {
        lines.push(info_row("BRANCH", branch, label_style, value_style));
    }
    if let Some(action) = &request.action {
        lines.push(info_row("ACTION", action, label_style, value_style));
    }

    lines.push(info_row(
        "COMMAND",
        &request.command,
        label_style,
        value_style,
    ));

    if !request.env.is_empty() {
        let mut spans: Vec<Span<'static>> = vec![Span::styled(
            format!("{:<14}", "REQUESTED ENV"),
            label_style,
        )];
        for key in &request.env {
            spans.push(Span::styled(
                format!(" {key} "),
                Style::default()
                    .fg(CYAN)
                    .bg(Color::Rgb(14, 42, 58))
                    .add_modifier(Modifier::BOLD),
            ));
            spans.push(Span::raw(" "));
        }
        lines.push(Line::from(spans));
    }

    let paragraph = Paragraph::new(lines);
    f.render_widget(paragraph, area);
}

fn info_row(label: &str, value: &str, label_style: Style, value_style: Style) -> Line<'static> {
    Line::from(vec![
        Span::styled(format!("{:<14}", label), label_style),
        Span::styled(value.to_string(), value_style),
    ])
}

fn draw_critical_warning(f: &mut Frame, area: ratatui::layout::Rect) {
    let warning = Paragraph::new(vec![
        Line::from(Span::styled(
            "CRITICAL  This command matched known secret-exfiltration patterns.",
            Style::default().fg(RED).bold(),
        )),
        Line::from(Span::styled(
            "          Deny unless you explicitly expect this command to inspect secrets.",
            Style::default().fg(RED),
        )),
    ]);
    f.render_widget(warning, area);
}

fn draw_scope_list(f: &mut Frame, state: &State, area: ratatui::layout::Rect) {
    let lines: Vec<Line<'static>> = state
        .choices
        .iter()
        .enumerate()
        .map(|(i, scope)| {
            let is_selected = i == state.selected;
            let is_deny = *scope == ApprovalScope::Deny;
            let label = scope.to_string();

            if is_selected {
                let bg_block =
                    ratatui::widgets::Block::default().style(Style::default().bg(SEL_BG));
                let row_area = ratatui::layout::Rect {
                    x: area.x,
                    y: area.y + i as u16,
                    width: area.width,
                    height: 1,
                };
                // We'll render the highlight as part of the paragraph style below
                let _ = bg_block;
                let _ = row_area;

                Line::from(vec![
                    Span::styled("", Style::default().fg(ACCENT).bold()),
                    Span::styled(
                        label,
                        Style::default()
                            .fg(if is_deny { RED } else { TEXT })
                            .bold()
                            .bg(SEL_BG),
                    ),
                    // Pad the rest of the line to fill the selection highlight
                    Span::styled(" ".repeat(60), Style::default().bg(SEL_BG)),
                ])
            } else {
                Line::from(vec![
                    Span::raw("    "),
                    Span::styled(label, Style::default().fg(if is_deny { RED } else { TEXT })),
                ])
            }
        })
        .collect();

    let paragraph = Paragraph::new(lines);
    f.render_widget(paragraph, area);
}