envseal 0.3.8

Write-only secret vault with process-level access control — post-agent secret management
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
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
//! Bash / Zsh / Fish preexec hook scripts and the install/uninstall
//! logic that wires them into a user's shell rc file.
//!
//! The hook runs `envseal __preexec "$cmd"` in the background before
//! every interactive command. The CLI's `__preexec` mode parses the
//! line and (for high-confidence matches) opens a GUI popup offering
//! to migrate the secret. The user's command runs in foreground
//! unaffected — there is no measurable latency cost in the no-match
//! case (background process, stdout/stderr discarded).
//!
//! Idempotent: install rewrites the block between BEGIN/END markers,
//! uninstall removes everything between them.

use std::fs;
use std::path::{Path, PathBuf};

use crate::error::Error;

/// The three shells we generate hooks for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shell {
    /// GNU Bash. Hook installed via `trap '...' DEBUG` + `PROMPT_COMMAND`
    /// armament so it fires once per user-typed line, not per
    /// expanded simple command.
    Bash,
    /// Zsh. Hook installed via `preexec_functions` array.
    Zsh,
    /// Fish. Hook installed via the `fish_preexec` event.
    Fish,
}

impl Shell {
    /// Parse from a CLI argument. Accepts case-insensitive `bash`,
    /// `zsh`, `fish`.
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "bash" => Some(Self::Bash),
            "zsh" => Some(Self::Zsh),
            "fish" => Some(Self::Fish),
            _ => None,
        }
    }

    /// Display name for messages.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Bash => "bash",
            Self::Zsh => "zsh",
            Self::Fish => "fish",
        }
    }

    /// Default rc file path under `$HOME` for an interactive shell of
    /// this type. Returns `None` if `$HOME` is unset.
    pub fn default_rc_path(&self) -> Option<PathBuf> {
        let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
        let home = PathBuf::from(home);
        Some(match self {
            Self::Bash => home.join(".bashrc"),
            Self::Zsh => home.join(".zshrc"),
            Self::Fish => home.join(".config").join("fish").join("config.fish"),
        })
    }

    /// The shell-specific hook snippet, ready to drop between the
    /// BEGIN/END markers in an rc file.
    pub fn snippet(&self) -> &'static str {
        match self {
            Self::Bash => BASH_SNIPPET,
            Self::Zsh => ZSH_SNIPPET,
            Self::Fish => FISH_SNIPPET,
        }
    }
}

/// Marker that opens an envseal-managed block in an rc file.
pub const BEGIN_MARKER: &str = "# >>> envseal preexec hook (auto-managed — do not edit) >>>";
/// Marker that closes an envseal-managed block in an rc file.
pub const END_MARKER: &str = "# <<< envseal preexec hook <<<";

/// Bash snippet.
///
/// Bash's `DEBUG` trap fires for every simple command — including
/// every command in a pipeline, every iteration of a loop, and every
/// command inside a function. We only want to inspect what the user
/// actually typed at the prompt. The arming flag is reset by
/// `PROMPT_COMMAND` (which fires once per prompt redisplay), so the
/// trap fires effectively once per user-typed line.
pub const BASH_SNIPPET: &str = r#"if command -v envseal >/dev/null 2>&1; then
    __envseal_armed=1
    __envseal_preexec() {
        [[ "$__envseal_armed" -ne 1 ]] && return
        __envseal_armed=0
        envseal __preexec "$BASH_COMMAND" </dev/null >/dev/null 2>&1 &
        disown 2>/dev/null
    }
    __envseal_post() { __envseal_armed=1; }
    trap '__envseal_preexec' DEBUG
    case "$PROMPT_COMMAND" in
        *__envseal_post*) ;;
        *) PROMPT_COMMAND="__envseal_post${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
    esac
fi"#;

/// Zsh snippet — uses the native `preexec_functions` array hook so we
/// don't fight `DEBUG`-trap quirks.
pub const ZSH_SNIPPET: &str = r#"if command -v envseal >/dev/null 2>&1; then
    __envseal_preexec() {
        envseal __preexec "$1" </dev/null >/dev/null 2>&1 &!
    }
    typeset -a preexec_functions
    if [[ -z "${preexec_functions[(r)__envseal_preexec]}" ]]; then
        preexec_functions+=( __envseal_preexec )
    fi
fi"#;

/// Fish snippet — uses the `fish_preexec` event.
pub const FISH_SNIPPET: &str = r#"if command -v envseal >/dev/null 2>&1
    function __envseal_preexec --on-event fish_preexec
        envseal __preexec "$argv" >/dev/null 2>&1 &
        disown 2>/dev/null
    end
end"#;

/// Status of a one-shot install operation.
#[derive(Debug, Clone)]
pub struct InstallReport {
    /// Path that was modified.
    pub rc_path: PathBuf,
    /// `true` if the rc file already had an envseal block (we rewrote it).
    pub replaced_existing: bool,
    /// `true` if the rc file did not exist; we created it.
    pub created_file: bool,
}

/// Install (or refresh) the preexec hook in `rc_path`.
///
/// - If the file does not exist, it is created with the hook block.
/// - If the file contains existing envseal block(s), **all** of them
///   are removed and a single fresh block is appended at the end. This
///   makes install idempotent even when a previous tool/install
///   produced duplicates (e.g. a manual copy by the user).
/// - If the file exists with no block, the block is appended.
pub fn install(shell: Shell, rc_path: &Path) -> Result<InstallReport, Error> {
    let block = build_block(shell);

    let (existed, content) = match fs::read_to_string(rc_path) {
        Ok(c) => (true, c),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => (false, String::new()),
        Err(e) => return Err(Error::StorageIo(e)),
    };

    let (had_blocks, mut stripped) = strip_all_blocks(&content);

    // Append the canonical block at the end, separated by a blank line
    // unless the file is empty.
    if !stripped.is_empty() && !stripped.ends_with('\n') {
        stripped.push('\n');
    }
    if !stripped.is_empty() {
        stripped.push('\n');
    }
    stripped.push_str(&block);

    if let Some(parent) = rc_path.parent() {
        fs::create_dir_all(parent).map_err(Error::StorageIo)?;
    }
    fs::write(rc_path, stripped).map_err(Error::StorageIo)?;

    Ok(InstallReport {
        rc_path: rc_path.to_path_buf(),
        replaced_existing: had_blocks,
        created_file: !existed,
    })
}

/// Remove **every** envseal block from `rc_path`. Returns `true` if at
/// least one block was removed. Leaves the rest of the file untouched.
pub fn uninstall(rc_path: &Path) -> Result<bool, Error> {
    let content = match fs::read_to_string(rc_path) {
        Ok(c) => c,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(e) => return Err(Error::StorageIo(e)),
    };
    let (had_blocks, stripped) = strip_all_blocks(&content);
    if !had_blocks {
        return Ok(false);
    }
    fs::write(rc_path, stripped).map_err(Error::StorageIo)?;
    Ok(true)
}

/// Remove every BEGIN…END envseal block from `content`. Returns
/// `(any_removed, cleaned_content)`. The cleaned content has the
/// surrounding line breaks of each removed block normalized so we
/// don't leave behind triple-blank-line gaps.
fn strip_all_blocks(content: &str) -> (bool, String) {
    let mut current = content.to_string();
    let mut removed_any = false;
    while let Some((before, after)) = split_around_block(&current) {
        removed_any = true;
        let mut next = String::with_capacity(before.len() + after.len() + 1);
        next.push_str(before.trim_end_matches('\n'));
        if !after.is_empty() {
            // Preserve a single newline between the surviving "before"
            // and "after" sections instead of running them together.
            next.push('\n');
            next.push_str(after.trim_start_matches('\n'));
        } else if !next.is_empty() {
            next.push('\n');
        }
        current = next;
    }
    (removed_any, current)
}

fn build_block(shell: Shell) -> String {
    let mut out = String::new();
    out.push_str(BEGIN_MARKER);
    out.push('\n');
    out.push_str(shell.snippet());
    out.push('\n');
    out.push_str(END_MARKER);
    out.push('\n');
    out
}

/// Find an envseal-managed block in `content` and return `(before, after)`
/// slices. The returned `before` ends just before the BEGIN marker line
/// (with its trailing newline preserved if present), and `after` starts
/// just after the END marker line (with its leading newline consumed).
fn split_around_block(content: &str) -> Option<(&str, &str)> {
    let begin_idx = content.find(BEGIN_MARKER)?;
    // Walk back to the start of the line containing BEGIN.
    let line_start = content[..begin_idx].rfind('\n').map_or(0, |i| i + 1);
    let after_begin = begin_idx + BEGIN_MARKER.len();
    let end_search_start = after_begin;
    let end_idx = content[end_search_start..]
        .find(END_MARKER)
        .map(|i| end_search_start + i)?;
    let after_end = end_idx + END_MARKER.len();
    // Consume one trailing newline if present.
    let after_end = if content.as_bytes().get(after_end) == Some(&b'\n') {
        after_end + 1
    } else {
        after_end
    };
    Some((&content[..line_start], &content[after_end..]))
}

/// Best-effort detection of the user's interactive shell. Reads
/// `$SHELL`; falls back to `None`.
pub fn detect_user_shell() -> Option<Shell> {
    let s = std::env::var_os("SHELL")?;
    let path = PathBuf::from(s);
    let stem = path.file_name()?.to_str()?;
    Shell::parse(stem)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn parse_round_trip() {
        for s in ["bash", "zsh", "fish"] {
            let sh = Shell::parse(s).unwrap();
            assert_eq!(sh.name(), s);
        }
        assert!(Shell::parse("ksh").is_none());
        assert_eq!(Shell::parse("BASH"), Some(Shell::Bash));
    }

    #[test]
    fn snippets_mention_envseal_and_preexec_subcommand() {
        for sh in [Shell::Bash, Shell::Zsh, Shell::Fish] {
            let s = sh.snippet();
            assert!(s.contains("envseal"), "{}: must call envseal", sh.name());
            assert!(
                s.contains("__preexec"),
                "{}: must invoke __preexec",
                sh.name()
            );
        }
    }

    #[test]
    fn install_creates_missing_file() {
        let dir = tempdir().unwrap();
        let rc = dir.path().join(".bashrc");
        let report = install(Shell::Bash, &rc).unwrap();
        assert!(report.created_file);
        assert!(!report.replaced_existing);
        let content = fs::read_to_string(&rc).unwrap();
        assert!(content.contains(BEGIN_MARKER));
        assert!(content.contains(END_MARKER));
        assert!(content.contains("__envseal_preexec"));
    }

    #[test]
    fn install_appends_to_existing_file() {
        let dir = tempdir().unwrap();
        let rc = dir.path().join(".zshrc");
        fs::write(&rc, "alias ll='ls -la'\nexport PATH=\"$HOME/bin:$PATH\"\n").unwrap();
        let report = install(Shell::Zsh, &rc).unwrap();
        assert!(!report.created_file);
        assert!(!report.replaced_existing);
        let content = fs::read_to_string(&rc).unwrap();
        assert!(content.contains("alias ll"));
        assert!(content.contains(BEGIN_MARKER));
    }

    #[test]
    fn install_replaces_existing_block() {
        let dir = tempdir().unwrap();
        let rc = dir.path().join(".zshrc");
        // Pre-existing block plus other content.
        let initial = format!(
            "alias ll='ls -la'\n\n{BEGIN_MARKER}\nold contents that should disappear\n{END_MARKER}\n\nexport PATH=foo\n"
        );
        fs::write(&rc, &initial).unwrap();
        let report = install(Shell::Zsh, &rc).unwrap();
        assert!(report.replaced_existing);
        let content = fs::read_to_string(&rc).unwrap();
        assert!(!content.contains("old contents"));
        assert!(content.contains("__envseal_preexec"));
        // Surrounding content preserved.
        assert!(content.contains("alias ll"));
        assert!(content.contains("export PATH=foo"));
    }

    #[test]
    fn uninstall_removes_block_only() {
        let dir = tempdir().unwrap();
        let rc = dir.path().join(".bashrc");
        let initial = format!(
            "alias ll='ls -la'\n\n{BEGIN_MARKER}\nstuff\n{END_MARKER}\n\nexport PATH=foo\n"
        );
        fs::write(&rc, &initial).unwrap();
        let removed = uninstall(&rc).unwrap();
        assert!(removed);
        let content = fs::read_to_string(&rc).unwrap();
        assert!(content.contains("alias ll"));
        assert!(content.contains("export PATH=foo"));
        assert!(!content.contains(BEGIN_MARKER));
    }

    #[test]
    fn uninstall_no_block_returns_false() {
        let dir = tempdir().unwrap();
        let rc = dir.path().join(".zshrc");
        fs::write(&rc, "alias ll='ls -la'\n").unwrap();
        let removed = uninstall(&rc).unwrap();
        assert!(!removed);
    }

    #[test]
    fn uninstall_missing_file_returns_false() {
        let dir = tempdir().unwrap();
        let rc = dir.path().join(".zshrc");
        let removed = uninstall(&rc).unwrap();
        assert!(!removed);
    }

    #[test]
    fn install_then_uninstall_restores_file_close_to_original() {
        let dir = tempdir().unwrap();
        let rc = dir.path().join(".bashrc");
        let original = "alias ll='ls -la'\nexport PATH=\"$HOME/bin:$PATH\"\n";
        fs::write(&rc, original).unwrap();
        install(Shell::Bash, &rc).unwrap();
        uninstall(&rc).unwrap();
        let content = fs::read_to_string(&rc).unwrap();
        assert!(content.contains("alias ll"));
        assert!(content.contains("export PATH"));
        assert!(!content.contains("__envseal_preexec"));
    }

    #[test]
    fn install_collapses_duplicate_blocks() {
        // Simulate a file where the user manually copied the block,
        // producing two identical envseal blocks. Install should
        // collapse them down to exactly one.
        let dir = tempdir().unwrap();
        let rc = dir.path().join(".bashrc");
        let block = build_block(Shell::Bash);
        let initial = format!("alias ll='ls -la'\n\n{block}\n{block}\n# trailing line\n");
        fs::write(&rc, &initial).unwrap();

        let report = install(Shell::Bash, &rc).unwrap();
        assert!(report.replaced_existing);

        let content = fs::read_to_string(&rc).unwrap();
        let begin_count = content.matches(BEGIN_MARKER).count();
        let end_count = content.matches(END_MARKER).count();
        assert_eq!(begin_count, 1, "should have exactly one BEGIN marker");
        assert_eq!(end_count, 1, "should have exactly one END marker");
        // Surrounding content preserved.
        assert!(content.contains("alias ll"));
        assert!(content.contains("# trailing line"));
    }

    #[test]
    fn uninstall_removes_all_duplicate_blocks() {
        let dir = tempdir().unwrap();
        let rc = dir.path().join(".zshrc");
        let block = build_block(Shell::Zsh);
        let initial = format!("alias ll='ls -la'\n\n{block}\nbetween\n{block}\nfinal\n");
        fs::write(&rc, &initial).unwrap();

        let removed = uninstall(&rc).unwrap();
        assert!(removed);

        let content = fs::read_to_string(&rc).unwrap();
        assert!(!content.contains(BEGIN_MARKER));
        assert!(!content.contains(END_MARKER));
        assert!(content.contains("alias ll"));
        assert!(content.contains("between"));
        assert!(content.contains("final"));
    }

    #[test]
    fn install_is_idempotent() {
        let dir = tempdir().unwrap();
        let rc = dir.path().join(".zshrc");
        install(Shell::Zsh, &rc).unwrap();
        let after_first = fs::read_to_string(&rc).unwrap();
        install(Shell::Zsh, &rc).unwrap();
        let after_second = fs::read_to_string(&rc).unwrap();
        assert_eq!(after_first, after_second);
    }

    #[test]
    fn fish_default_path_is_under_config_fish() {
        let old_home = std::env::var_os("HOME");
        std::env::set_var("HOME", "/home/test");
        let p = Shell::Fish.default_rc_path().unwrap();
        assert!(p.ends_with("config.fish"));
        assert!(p.to_string_lossy().contains("fish"));
        match old_home {
            Some(v) => std::env::set_var("HOME", v),
            None => std::env::remove_var("HOME"),
        }
    }
}