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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Read-only queries against the vault directory.
//!
//! Most functions in this file work on the filesystem only — no
//! `Vault::open*` call, no master key in memory. Used by the
//! desktop GUI's filesystem-only refresh paths (Secrets list,
//! Audit log, Dashboard counters), the CLI's `list` / `status`
//! commands, and the MCP server's status endpoints.
//!
//! The two read-only operations that *do* need an unlocked vault
//! ([`peek_secret`], [`peek_secret_default`]) live here too because
//! they're the natural counterpart to `list_secrets` from a
//! consumer's standpoint — knowing a secret exists is one step
//! short of seeing its redacted preview.

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

use zeroize::Zeroize;

use crate::audit::extract_json_field;
use crate::error::Error;
use crate::vault::Vault;

/// Get the default vault root directory without opening or unlocking.
///
/// Respects `XDG_CONFIG_HOME`, falls back to `$HOME/.config/envseal`.
pub fn vault_root() -> Result<PathBuf, Error> {
    let config_dir = if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
        PathBuf::from(xdg)
    } else {
        let home = std::env::var("HOME").map_err(|_| {
            Error::StorageIo(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "HOME not set",
            ))
        })?;
        PathBuf::from(home).join(".config")
    };
    Ok(config_dir.join("envseal"))
}

// ── Secret listing (no passphrase — filesystem only) ──────────────

/// Information about a stored secret (no decryption needed).
#[derive(Debug, Clone)]
pub struct SecretInfo {
    /// Secret name (derived from filename).
    pub name: String,
    /// Last modification time.
    pub modified: Option<std::time::SystemTime>,
}

/// List all secrets in the vault with metadata.
///
/// Does NOT require a passphrase — just scans `.seal` files.
/// Use this for `list`, `status`, pre-validation, etc.
pub fn list_secrets(root: &Path) -> Result<Vec<SecretInfo>, Error> {
    let vault_dir = root.join("vault");
    crate::guard::verify_not_symlink(&vault_dir)?;
    let mut entries = Vec::new();

    if vault_dir.exists() {
        for entry in std::fs::read_dir(&vault_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) == Some("seal") {
                if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                    crate::guard::verify_not_symlink(&path)?;
                    let modified = std::fs::symlink_metadata(&path)
                        .ok()
                        .and_then(|m| m.modified().ok());
                    entries.push(SecretInfo {
                        name: stem.to_string(),
                        modified,
                    });
                }
            }
        }
    }

    entries.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(entries)
}

/// List secret names only (convenience wrapper).
pub fn list_secret_names(root: &Path) -> Result<Vec<String>, Error> {
    Ok(list_secrets(root)?.into_iter().map(|s| s.name).collect())
}

/// Check if a specific secret exists without passphrase.
pub fn secret_exists(root: &Path, name: &str) -> Result<bool, Error> {
    let path = root.join("vault").join(format!("{name}.seal"));
    crate::guard::verify_not_symlink(&path)?;
    Ok(path.exists())
}

// ── Format helpers ────────────────────────────────────────────────

/// Format a duration as a human-readable age string.
#[must_use]
pub fn format_age(modified: std::time::SystemTime) -> String {
    std::time::SystemTime::now()
        .duration_since(modified)
        .ok()
        .map_or_else(
            || "".to_string(),
            |d| {
                let secs = d.as_secs();
                if secs < 60 {
                    "just now".to_string()
                } else if secs < 3600 {
                    format!("{}m ago", secs / 60)
                } else if secs < 86400 {
                    format!("{}h ago", secs / 3600)
                } else {
                    format!("{}d ago", secs / 86400)
                }
            },
        )
}

// ── Secret type detection ─────────────────────────────────────────

/// Detect the type of a secret by its value prefix.
///
/// Returns a human-readable label (for example, an `OpenAI` API key) or `None`.
#[must_use]
pub fn detect_secret_type(value: &str) -> Option<&'static str> {
    // Order matters — more specific prefixes first
    static DETECTIONS: &[(&str, &str)] = &[
        ("sk-proj-", "OpenAI Project Key"),
        ("sk-ant-", "Anthropic API Key"),
        ("sk-", "OpenAI API Key"),
        ("ghp_", "GitHub PAT"),
        ("gho_", "GitHub OAuth"),
        ("github_pat_", "GitHub Fine-Grained PAT"),
        ("glpat-", "GitLab PAT"),
        ("AKIA", "AWS Access Key"),
        ("xoxb-", "Slack Bot Token"),
        ("xoxp-", "Slack User Token"),
        ("sk_live_", "Stripe Secret Key"),
        ("sk_test_", "Stripe Test Key"),
        ("pk_live_", "Stripe Publishable Key"),
        ("pk_test_", "Stripe Test Publishable Key"),
        ("rk_live_", "Stripe Restricted Key"),
        ("SG.", "SendGrid API Key"),
        ("key-", "Mailgun API Key"),
        ("AIza", "Google API Key"),
        ("npm_", "npm Token"),
        ("pypi-", "PyPI Token"),
        ("eyJ", "JWT Token"),
        ("https://", "URL"),
        ("http://", "URL"),
        ("postgresql://", "PostgreSQL URL"),
        ("postgres://", "PostgreSQL URL"),
        ("mysql://", "MySQL URL"),
        ("redis://", "Redis URL"),
        ("mongodb://", "MongoDB URL"),
        ("mongodb+srv://", "MongoDB Atlas URL"),
    ];

    DETECTIONS
        .iter()
        .find(|(prefix, _)| value.starts_with(prefix))
        .map(|(_, label)| *label)
}

// ── Peek (redacted preview — needs unlocked vault) ────────────────

/// Result of peeking at a secret (redacted preview).
#[derive(Debug, Clone)]
pub struct PeekResult {
    /// Secret name.
    pub name: String,
    /// Redacted value (e.g., "sk-p...X84f").
    pub redacted: String,
    /// Character count of the full value.
    pub length: usize,
    /// Detected secret type, if any.
    pub secret_type: Option<&'static str>,
}

/// Get a redacted preview of a secret.
///
/// Shows first 4 and last 4 characters. Detects secret type by prefix.
/// NEVER returns the full value.
pub fn peek_secret(vault: &Vault, name: &str) -> Result<PeekResult, Error> {
    let mut plaintext = vault.decrypt(name)?;
    let vec = std::mem::take(&mut *plaintext);
    let s = match String::from_utf8(vec) {
        Ok(s) => s,
        Err(e) => {
            let mut vec = e.into_bytes();
            vec.zeroize();
            return Err(Error::CryptoFailure(
                "secret is not valid UTF-8".to_string(),
            ));
        }
    };
    let mut value = zeroize::Zeroizing::new(s);

    let redacted = if value.len() <= 10 {
        let mut prefix = value.chars().take(2).collect::<String>();
        let res = format!("{prefix}***");
        prefix.zeroize();
        res
    } else {
        let mut prefix = value.chars().take(4).collect::<String>();
        let mut suffix_rev = value.chars().rev().take(4).collect::<String>();
        let mut suffix = suffix_rev.chars().rev().collect::<String>();
        let res = format!("{prefix}...{suffix}");
        prefix.zeroize();
        suffix_rev.zeroize();
        suffix.zeroize();
        res
    };

    let length = value.len();
    let secret_type = detect_secret_type(&value);

    value.shrink_to_fit();
    value.zeroize();

    Ok(PeekResult {
        name: name.to_string(),
        redacted,
        length,
        secret_type,
    })
}

/// Peek at a secret in the default vault (redacted preview only).
pub fn peek_secret_default(name: &str) -> Result<PeekResult, Error> {
    let vault = Vault::open_default()?;
    peek_secret(&vault, name)
}

/// Peek at a secret in the default vault, requiring GUI approval for full value.
pub fn peek_secret_full_default(name: &str) -> Result<String, Error> {
    let vault = Vault::open_default()?;
    let config = crate::security_config::load_config(vault.root(), vault.master_key_bytes())?;
    let binary_path = std::env::current_exe()
        .map_err(|e| Error::BinaryResolution(format!("cannot determine current executable: {e}")))?
        .to_string_lossy()
        .to_string();

    let approval = crate::gui::request_approval(
        &binary_path,
        &[
            String::from("envseal"),
            String::from("peek"),
            name.to_string(),
            String::from("--full"),
        ],
        name,
        "",
        &config,
    )?;

    match approval {
        crate::gui::Approval::AllowOnce | crate::gui::Approval::AllowAlways => {
            let mut plaintext = vault.decrypt(name)?;
            match String::from_utf8(std::mem::take(&mut *plaintext)) {
                Ok(s) => Ok(s),
                Err(e) => {
                    let mut vec = e.into_bytes();
                    vec.zeroize();
                    Err(Error::CryptoFailure(
                        "secret is not valid UTF-8".to_string(),
                    ))
                }
            }
        }
        crate::gui::Approval::Deny => Err(Error::UserDenied),
    }
}

// ── .envseal file checking ────────────────────────────────────────

/// Result of checking a .envseal file against the vault.
#[derive(Debug, Clone)]
pub struct CheckResult {
    /// Secrets that are present in the vault.
    pub satisfied: Vec<EnvMapping>,
    /// Secrets that are missing from the vault.
    pub missing: Vec<EnvMapping>,
}

/// A single env var → secret name mapping.
#[derive(Debug, Clone)]
pub struct EnvMapping {
    /// Environment variable name.
    pub env_var: String,
    /// Secret name in the vault.
    pub secret_name: String,
    /// Whether this secret exists in the vault.
    pub present: bool,
}

/// Check a .envseal file against the vault (no passphrase needed).
pub fn check_envseal_file(root: &Path, envseal_path: &Path) -> Result<CheckResult, Error> {
    let mappings = crate::envseal_file::parse_envseal_file(envseal_path)?;
    let names = list_secret_names(root)?;

    let mut satisfied = Vec::new();
    let mut missing = Vec::new();

    for m in mappings {
        let present = names.contains(&m.secret_name);
        let mapping = EnvMapping {
            env_var: m.env_var.clone(),
            secret_name: m.secret_name.clone(),
            present,
        };
        if present {
            satisfied.push(mapping);
        } else {
            missing.push(mapping);
        }
    }

    Ok(CheckResult { satisfied, missing })
}

/// Dry-run: show what env vars would be injected (no passphrase needed).
pub fn env_dry_run(root: &Path, cwd: &Path) -> Result<CheckResult, Error> {
    let mappings = if let Some(m) = crate::envseal_file::discover_and_load(cwd)? {
        m
    } else {
        let names = list_secret_names(root)?;
        crate::envseal_file::auto_map_from_names(&names)
    };

    let names = list_secret_names(root)?;
    let mut satisfied = Vec::new();
    let mut missing = Vec::new();

    for m in mappings {
        let present = names.contains(&m.secret_name);
        let mapping = EnvMapping {
            env_var: m.env_var.clone(),
            secret_name: m.secret_name.clone(),
            present,
        };
        if present {
            satisfied.push(mapping);
        } else {
            missing.push(mapping);
        }
    }

    Ok(CheckResult { satisfied, missing })
}

// ── Vault status (no passphrase) ──────────────────────────────────

/// High-level vault status overview.
#[derive(Debug, Clone)]
pub struct VaultStatus {
    /// Vault root directory.
    pub root: PathBuf,
    /// Number of secrets stored.
    pub secret_count: usize,
    /// Whether the master key is initialized.
    pub initialized: bool,
    /// Whether a .envseal file was found in cwd.
    pub envseal_found: bool,
    /// Security tier string.
    pub security_tier: String,
    /// Last audit log entry.
    pub last_audit: Option<String>,
}

/// Get vault status overview.
pub fn vault_status(root: &Path) -> Result<VaultStatus, Error> {
    let secrets = list_secrets(root)?;
    let initialized = root.join("master.key").exists();

    let cwd = std::env::current_dir().unwrap_or_default();
    let envseal_found = crate::envseal_file::discover_and_load(&cwd)
        .ok()
        .flatten()
        .is_some();

    let mut corrupted = false;
    if initialized {
        let mk_path = root.join("master.key");
        if let Ok(raw) = std::fs::read(&mk_path) {
            if crate::vault::hardware::parse_v2(&raw).is_err() {
                let min_v1_len = 16 + 12; // ARGON2_SALT_LEN + NONCE_LEN
                if raw.len() < min_v1_len {
                    corrupted = true;
                }
            }
        } else {
            corrupted = true;
        }
    }

    // Do not call Vault::open(root) here as it prompts the user for a passphrase!
    let security_tier = if corrupted {
        "Corrupted".to_string()
    } else if !initialized {
        "Standard (default)".to_string()
    } else if root.join("security.sealed").exists() {
        // v0.3.0+ sealed config exists but requires the master key to decrypt.
        "Locked (passphrase required)".to_string()
    } else if root.join("security.toml").exists() {
        // v0.2.x legacy: try to read the tier field without verifying HMAC.
        // This is acceptable for a status command that makes no security decisions.
        std::fs::read_to_string(root.join("security.toml"))
            .ok()
            .and_then(|content| {
                content
                    .lines()
                    .find(|l| l.trim_start().starts_with("tier"))
                    .map(|l| {
                        l.split('=').nth(1).map_or_else(
                            || "Standard".to_string(),
                            |v| v.trim().trim_matches('"').to_string(),
                        )
                    })
            })
            .unwrap_or_else(|| "Standard (default)".to_string())
    } else {
        "Standard (default)".to_string()
    };

    let last_audit = crate::audit::read_last(1).into_iter().next().map(|raw| {
        let ts = extract_json_field(&raw, "ts").unwrap_or_default();
        let event = extract_json_field(&raw, "event").unwrap_or_default();
        let binary = extract_json_field(&raw, "binary").unwrap_or_default();
        let secret = extract_json_field(&raw, "secret").unwrap_or_default();

        let ts_short = ts.get(..16).unwrap_or(&ts).replace('T', " ");

        if !binary.is_empty() && !secret.is_empty() {
            format!(" {ts_short}  {event:<22} {binary}{secret}")
        } else if !secret.is_empty() {
            format!(" {ts_short}  {event:<22} {secret}")
        } else {
            format!(" {ts_short}  {event}")
        }
    });

    Ok(VaultStatus {
        root: root.to_path_buf(),
        secret_count: secrets.len(),
        initialized: initialized && !corrupted,
        envseal_found,
        security_tier,
        last_audit,
    })
}

/// Return the last `n` audit entries from the default vault as raw
/// JSON lines. Used by `envseal audit` and any external consumer
/// that wants newline-delimited JSON unchanged.
#[must_use]
pub fn audit_log(n: usize) -> Vec<String> {
    crate::audit::read_last(n)
}

/// Return the last `n` audit entries from the default vault, parsed
/// into typed [`crate::audit::ParsedEntry`] values. Used by the
/// desktop GUI (and any structured renderer) so per-event icons,
/// summaries, and timestamps can be rendered without re-parsing
/// JSON in every consumer.
#[must_use]
pub fn audit_log_parsed(n: usize) -> crate::audit::ParsedReadResult {
    let Ok(dir) = crate::audit::log::default_audit_dir() else {
        return crate::audit::ParsedReadResult::default();
    };
    crate::audit::read_last_parsed_at(&dir, n)
}

/// Return the last `n` audit entries from the default vault that
/// match `filter`, as raw JSON lines.
#[must_use]
pub fn audit_log_filtered(n: usize, filter: &crate::audit::AuditFilter) -> Vec<String> {
    crate::audit::read_last_filtered(n, filter)
}

/// Return the last `n` audit entries from the default vault that
/// match `filter`, parsed into typed [`crate::audit::ParsedEntry`]
/// values. Used by the desktop GUI's filter bar.
#[must_use]
pub fn audit_log_parsed_filtered(
    n: usize,
    filter: &crate::audit::AuditFilter,
) -> crate::audit::ParsedReadResult {
    let Ok(dir) = crate::audit::log::default_audit_dir() else {
        return crate::audit::ParsedReadResult::default();
    };
    crate::audit::read_last_parsed_filtered_at(&dir, n, filter)
}