Skip to main content

pacsea/logic/
doas_persist_setup.rs

1//! Helpers for the optional `doas` persist setup wizard.
2
3use ratatui::style::{Modifier, Style};
4use ratatui::text::{Line, Span};
5
6use crate::state::AppState;
7use crate::state::modal::DoasPersistChoice;
8use crate::theme::theme;
9
10/// Visible instruction lines in the doas persist wizard (scroll viewport height).
11pub const DOAS_PERSIST_INSTRUCTION_VIEWPORT_LINES: usize = 10;
12
13/// What: Best-effort current username resolution for display-only snippet guidance.
14///
15/// Inputs: None.
16///
17/// Output:
18/// - Username string to embed in suggested user-scoped `doas.conf` snippets.
19///
20/// Details:
21/// - Prefers `$USER`, then `$LOGNAME`.
22/// - Falls back to `id -un` when env vars are unavailable.
23/// - Final fallback is `"youruser"` to keep guidance deterministic.
24fn current_username_for_snippet() -> String {
25    let from_env = std::env::var("USER")
26        .or_else(|_| std::env::var("LOGNAME"))
27        .ok()
28        .map(|s| s.trim().to_string())
29        .filter(|s| !s.is_empty());
30    if let Some(name) = from_env {
31        return name;
32    }
33    let from_id = std::process::Command::new("id")
34        .args(["-un"])
35        .output()
36        .ok()
37        .filter(|out| out.status.success())
38        .and_then(|out| String::from_utf8(out.stdout).ok())
39        .map(|s| s.trim().to_string())
40        .filter(|s| !s.is_empty());
41    from_id.unwrap_or_else(|| "youruser".to_string())
42}
43
44/// What: Check whether a parsed `doas.conf` body has at least one active `permit persist` rule.
45///
46/// Inputs:
47/// - `contents`: Raw text contents from `doas.conf`.
48///
49/// Output:
50/// - `true` if a non-comment rule line includes both `permit` and `persist`.
51///
52/// Details:
53/// - Ignores blank lines and comments (`# ...`).
54/// - Uses token matching to avoid false positives from unrelated substrings.
55#[must_use]
56pub fn doas_conf_has_persist_rule(contents: &str) -> bool {
57    contents.lines().any(|line| {
58        let trimmed = line.trim();
59        if trimmed.is_empty() || trimmed.starts_with('#') {
60            return false;
61        }
62        let without_inline_comment = trimmed
63            .split_once('#')
64            .map_or(trimmed, |(rule, _)| rule.trim());
65        let tokens: Vec<&str> = without_inline_comment.split_whitespace().collect();
66        tokens.contains(&"permit") && tokens.contains(&"persist")
67    })
68}
69
70/// What: Detect whether the system `doas.conf` appears configured with a persist rule.
71///
72/// Inputs: None.
73///
74/// Output:
75/// - `true` when `/etc/doas.conf` exists and contains an active `permit persist` rule.
76///
77/// Details:
78/// - Read-only check; never mutates system files.
79/// - Returns `false` on missing/unreadable config or parse mismatch.
80#[must_use]
81pub fn pacsea_doas_persist_configured() -> bool {
82    std::fs::read_to_string("/etc/doas.conf")
83        .is_ok_and(|contents| doas_conf_has_persist_rule(&contents))
84}
85
86/// What: Build a recommended `doas.conf` persist snippet for the selected profile.
87///
88/// Inputs:
89/// - `choice`: Selected snippet profile.
90///
91/// Output:
92/// - A single-line `permit persist` recommendation.
93///
94/// Details:
95/// - Generated text is guidance only. The app never writes `/etc/doas.conf` automatically.
96#[must_use]
97pub fn doas_persist_snippet(choice: DoasPersistChoice, username: &str) -> String {
98    match choice {
99        DoasPersistChoice::WheelScoped => "permit persist :wheel as root".to_string(),
100        DoasPersistChoice::UserScoped => format!("permit persist {username} as root"),
101        DoasPersistChoice::Skip => "# Skip setup".to_string(),
102    }
103}
104
105/// What: Build shell commands for validating doas policy configuration.
106///
107/// Inputs: None.
108///
109/// Output:
110/// - Validation command list (`doas -C`, optional non-interactive probe).
111///
112/// Details:
113/// - `doas -C /etc/doas.conf` validates syntax and rule matching.
114/// - `doas -n true` is a non-interactive capability probe and may fail when `nopass` is not configured.
115#[must_use]
116pub fn validation_commands() -> Vec<&'static str> {
117    vec!["doas -C /etc/doas.conf", "doas -n true"]
118}
119
120/// What: Build scrollable instruction lines for the doas persist setup wizard.
121///
122/// Inputs:
123/// - `app`: Application state for localized strings.
124/// - `choice`: Selected persist setup profile.
125///
126/// Output:
127/// - Owned lines for the instructions pane.
128///
129/// Details:
130/// - Used by the renderer and key handler for scroll clamping.
131#[must_use]
132#[allow(clippy::vec_init_then_push)]
133pub fn doas_persist_instruction_lines(
134    app: &AppState,
135    choice: DoasPersistChoice,
136) -> Vec<Line<'static>> {
137    let th = theme();
138    let user = current_username_for_snippet();
139    let snippet = doas_persist_snippet(choice, &user);
140    let mut lines: Vec<Line<'static>> = Vec::new();
141    lines.push(Line::from(Span::styled(
142        crate::i18n::t(app, "app.modals.doas_persist_setup.instructions_heading"),
143        Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
144    )));
145    lines.push(Line::from(""));
146    lines.push(Line::from(Span::styled(
147        crate::i18n::t(app, "app.modals.doas_persist_setup.instructions_note"),
148        Style::default().fg(th.text),
149    )));
150    lines.push(Line::from(""));
151    lines.push(Line::from(Span::styled(
152        crate::i18n::t(app, "app.modals.doas_persist_setup.label_snippet"),
153        Style::default()
154            .fg(th.overlay1)
155            .add_modifier(Modifier::BOLD),
156    )));
157    lines.push(Line::from(Span::styled(
158        snippet,
159        Style::default().fg(th.lavender),
160    )));
161    lines.push(Line::from(""));
162    lines.push(Line::from(Span::styled(
163        crate::i18n::t(app, "app.modals.doas_persist_setup.label_checks"),
164        Style::default()
165            .fg(th.overlay1)
166            .add_modifier(Modifier::BOLD),
167    )));
168    for cmd in validation_commands() {
169        lines.push(Line::from(Span::styled(
170            format!("  {cmd}"),
171            Style::default().fg(th.subtext1),
172        )));
173    }
174    lines.push(Line::from(""));
175    lines.push(Line::from(Span::styled(
176        crate::i18n::t(app, "app.modals.doas_persist_setup.instructions_footer"),
177        Style::default().fg(th.overlay1),
178    )));
179    lines
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    #[test]
187    fn snippet_generation_uses_expected_forms() {
188        assert_eq!(
189            doas_persist_snippet(DoasPersistChoice::WheelScoped, "alice"),
190            "permit persist :wheel as root"
191        );
192        assert_eq!(
193            doas_persist_snippet(DoasPersistChoice::UserScoped, "alice"),
194            "permit persist alice as root"
195        );
196    }
197
198    #[test]
199    fn validation_commands_include_required_checks() {
200        let cmds = validation_commands();
201        assert!(cmds.iter().any(|c| c.contains("doas -C /etc/doas.conf")));
202        assert!(cmds.iter().any(|c| c.contains("doas -n true")));
203    }
204
205    #[test]
206    fn doas_conf_parser_detects_active_persist_rule() {
207        let conf = r"
208            # comment
209            permit persist :wheel as root
210        ";
211        assert!(doas_conf_has_persist_rule(conf));
212    }
213
214    #[test]
215    fn doas_conf_parser_ignores_commented_persist_rule() {
216        let conf = r"
217            # permit persist :wheel as root
218            permit :wheel as root
219        ";
220        assert!(!doas_conf_has_persist_rule(conf));
221    }
222}