envseal 0.3.10

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
//! Secret-mutation operations: store / revoke / copy / rename /
//! rotate / emergency-revoke / shred / import-from-`.env`.
//!
//! Everything here writes either to vault `.seal` files or to
//! `policy.toml`. All ops that hold a `&Vault` log to the vault's
//! own audit trail via `audit::log_required_at(vault.root(), ...)`
//! so the audit log and the secrets it audits stay co-located —
//! see `audit::log_at` for the why.

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

use zeroize::Zeroize;

use crate::audit;
use crate::error::Error;
use crate::secret_health;
use crate::security_config;
use crate::vault::store::MAX_SECRET_SIZE_BYTES;
use crate::vault::Vault;
use crate::{gui, policy};

// ── Vault-handle ops (caller already unlocked the vault) ──────────

/// Revoke a secret and clean up associated policy rules.
///
/// This removes every rule that could grant access to `name`, including
/// `AllowAll`-scoped rules, because those implicitly cover the secret being
/// revoked. Binaries that held `AllowAll` approval lose that approval entirely
/// and must be re-approved per-secret if they still need access to other secrets.
pub fn revoke_with_policy(vault: &Vault, name: &str) -> Result<(), Error> {
    // Clean up policy rules — MUST use load_sealed to prevent
    // trust-laundering: an attacker who tampers `policy.sealed` and
    // then triggers a revoke would otherwise get the tampered rules
    // re-sealed as legitimate by envseal. We don't gate on
    // `policy_path.exists()` because that's the legacy plaintext
    // location (gone after migration); `load_sealed` returns
    // `Self::default()` when neither sealed nor legacy file is on
    // disk, so an absent-policy vault is still cheap.
    let policy_path = vault.policy_path();
    let sealed_path = policy::sealed_path_for(&policy_path);
    if sealed_path.exists() || policy_path.exists() {
        let mut policy = policy::Policy::load_sealed(&policy_path, vault.master_key_bytes())?;
        let before_count = policy.rules.len();
        policy.revoke_secret(name);
        let removed = before_count - policy.rules.len();
        if removed > 0 {
            eprintln!("envseal: removed {removed} policy rule(s) referencing '{name}'");
        }
        policy.save_sealed(&policy_path, vault.master_key_bytes())?;
    }

    vault.revoke(name)?;

    audit::log_required_at(
        vault.root(),
        &audit::AuditEvent::SecretRevoked {
            name: name.to_string(),
        },
    )?;

    Ok(())
}

/// Copy a secret to a new name (keeps original).
pub fn copy_secret(vault: &Vault, source: &str, dest: &str, force: bool) -> Result<(), Error> {
    let value = vault.decrypt(source)?;
    vault.store(dest, &value, force)?;

    audit::log_required_at(
        vault.root(),
        &audit::AuditEvent::SecretStored {
            name: dest.to_string(),
        },
    )?;

    Ok(())
}

/// Copy a secret to a new name in the default vault (keeps original).
pub fn copy_secret_default(source: &str, dest: &str, force: bool) -> Result<(), Error> {
    let vault = Vault::open_default()?;
    copy_secret(&vault, source, dest, force)
}

/// Rename a secret and migrate policy rules.
pub fn rename_secret(
    vault: &Vault,
    old_name: &str,
    new_name: &str,
    force: bool,
) -> Result<(), Error> {
    let value = vault.decrypt(old_name)?;
    vault.store(new_name, &value, force)?;

    // Migrate policy rules — MUST use load_sealed to prevent
    // trust-laundering. See `revoke_with_policy` for the analogous
    // gate-on-either-path explanation.
    let policy_path = vault.policy_path();
    let sealed_path = policy::sealed_path_for(&policy_path);
    if sealed_path.exists() || policy_path.exists() {
        let mut policy = policy::Policy::load_sealed(&policy_path, vault.master_key_bytes())?;
        let old_rules: Vec<_> = policy
            .rules
            .iter()
            .filter(|r| r.scope == policy::RuleScope::Key && r.secret == old_name)
            .cloned()
            .collect();
        for mut rule in old_rules {
            rule.secret = new_name.to_string();
            if !policy.rules.iter().any(|r| {
                r.binary == rule.binary
                    && r.scope == rule.scope
                    && r.secret == rule.secret
                    && r.binary_hash == rule.binary_hash
            }) {
                policy.rules.push(rule);
            }
        }
        policy.revoke_secret(old_name);
        policy.save_sealed(&policy_path, vault.master_key_bytes())?;
    }

    vault.revoke(old_name)?;

    audit::log_required_at(
        vault.root(),
        &audit::AuditEvent::SecretStored {
            name: new_name.to_string(),
        },
    )?;
    audit::log_required_at(
        vault.root(),
        &audit::AuditEvent::SecretRevoked {
            name: old_name.to_string(),
        },
    )?;

    Ok(())
}

/// Rename a secret in the default vault.
pub fn rename_secret_default(old_name: &str, new_name: &str, force: bool) -> Result<(), Error> {
    let vault = Vault::open_default()?;
    rename_secret(&vault, old_name, new_name, force)
}

/// Store a secret in an *already-unlocked* vault, audit-log the
/// event, and return any entropy warnings.
///
/// Same guarantees as [`store_secret`] but without re-opening the
/// vault — used by the desktop GUI worker thread which holds the
/// unlocked vault for the session, and would otherwise either
/// re-prompt for passphrase on every store or duplicate the
/// audit / entropy / size-cap logic in the GUI codebase.
///
/// # Errors
/// `Error::CryptoFailure` if the value exceeds the size cap;
/// vault store and audit-log errors propagate.
pub fn store_secret_in(
    vault: &Vault,
    name: &str,
    value: &[u8],
    force: bool,
) -> Result<Vec<crate::guard::Signal>, Error> {
    if value.len() > MAX_SECRET_SIZE_BYTES {
        return Err(Error::CryptoFailure(format!(
            "secret exceeds max size: {} bytes > {} bytes",
            value.len(),
            MAX_SECRET_SIZE_BYTES
        )));
    }
    vault.store(name, value, force)?;
    let warnings = secret_health::check_entropy(name, value);
    // Render the entropy signals through the unified policy/stderr
    // pipeline. The structured Signal vec is also returned so MCP /
    // desktop callers that want to surface them in their own UI
    // don't need to scrape stderr.
    let _ = crate::guard::emit_signals_inline(
        warnings.clone(),
        &crate::security_config::load_system_defaults(),
    );
    audit::log_required_at(
        vault.root(),
        &audit::AuditEvent::SecretStored {
            name: name.to_string(),
        },
    )?;
    Ok(warnings)
}

// ── Default-vault wrappers (open + delegate) ──────────────────────

/// Store a secret in the default vault, audit-log the event, and return
/// any entropy warnings the consumer should surface.
///
/// The warnings list is non-fatal and never causes the store to fail —
/// the secret is encrypted and persisted before the warnings are
/// computed, so callers can print or discard them at will.
///
/// # Errors
/// `Error::CryptoFailure` if the value exceeds the size cap; otherwise
/// vault open/store and audit-log errors propagate.
pub fn store_secret(
    name: &str,
    value: &[u8],
    force: bool,
) -> Result<Vec<crate::guard::Signal>, Error> {
    let vault = Vault::open_default()?;
    store_secret_in(&vault, name, value, force)
}

/// Prompt the user for a new secret value via the platform GUI popup.
///
/// Wraps [`crate::gui::request_secret_value`] with the default
/// [`security_config::SecurityConfig`] so CLI/MCP callers don't have to
/// import either. Refuses to return an empty secret.
///
/// # Errors
/// `Error::UserDenied` on cancel; `Error::NoDisplay` in headless
/// environments; other GUI/relay errors as-is.
pub fn request_secret_value_default(
    name: &str,
    description: &str,
) -> Result<zeroize::Zeroizing<String>, Error> {
    let secret = gui::request_secret_value(
        name,
        description,
        &security_config::SecurityConfig::default(),
    )?;
    if secret.is_empty() {
        return Err(Error::CryptoFailure(
            "refusing to store an empty secret".to_string(),
        ));
    }
    Ok(secret)
}

/// Revoke a secret from the default vault and clean policy.
pub fn revoke_secret(name: &str) -> Result<(), Error> {
    let vault = Vault::open_default()?;
    revoke_with_policy(&vault, name)
}

/// Result of an emergency-revoke-all run.
#[derive(Debug, Clone, Default)]
pub struct EmergencyRevokeResult {
    /// Names of secrets we attempted to revoke (full set found in the vault).
    pub attempted: Vec<String>,
    /// Number of secrets successfully revoked.
    pub revoked: usize,
    /// Per-secret failures: `(name, error_message)`.
    pub failures: Vec<(String, String)>,
}

/// Revoke every secret in the default vault.
///
/// The CLI/MCP/desktop layer is responsible for any user confirmation
/// before calling this — `ops` does the work unconditionally.
///
/// # Errors
///
/// Returns the underlying error from opening the vault. Per-secret revoke
/// failures are reported via [`EmergencyRevokeResult::failures`] rather
/// than aborting the loop.
pub fn emergency_revoke_all() -> Result<EmergencyRevokeResult, Error> {
    let vault = Vault::open_default()?;
    let names = vault.list()?;

    let mut result = EmergencyRevokeResult {
        attempted: names.clone(),
        revoked: 0,
        failures: Vec::new(),
    };

    for name in &names {
        match revoke_with_policy(&vault, name) {
            // revoke_with_policy already audit-logs at vault.root().
            Ok(()) => {
                result.revoked += 1;
            }
            Err(e) => result.failures.push((name.clone(), e.to_string())),
        }
    }

    Ok(result)
}

/// Best-effort secure deletion: overwrite with zeros, then remove.
///
/// Filesystem journals and snapshots may still preserve historic blocks;
/// treat this as best-effort hardening rather than secure erasure.
///
/// # Errors
/// Returns `Error::StorageIo` if the final remove call fails.
pub fn shred_file(path: &Path) -> Result<(), Error> {
    crate::guard::verify_not_symlink(path)?;
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        if let Ok(meta) = std::fs::symlink_metadata(path) {
            let len = usize::try_from(meta.len()).unwrap_or(0);
            if len > 0 {
                let cap = len.min(crate::vault::store::MAX_SECRET_SIZE_BYTES);
                let mut file = std::fs::OpenOptions::new()
                    .write(true)
                    .truncate(true)
                    .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
                    .open(path)
                    .map_err(Error::StorageIo)?;
                file.write_all(&vec![0u8; cap]).map_err(Error::StorageIo)?;
                file.sync_all().map_err(Error::StorageIo)?;
            }
        }
    }
    #[cfg(not(unix))]
    {
        if let Ok(meta) = std::fs::metadata(path) {
            let len = usize::try_from(meta.len()).unwrap_or(0);
            if len > 0 {
                let cap = len.min(crate::vault::store::MAX_SECRET_SIZE_BYTES);
                std::fs::write(path, vec![0u8; cap]).map_err(Error::StorageIo)?;
            }
        }
    }
    std::fs::remove_file(path).map_err(Error::StorageIo)?;
    Ok(())
}

/// Re-encrypt and store a new value for an existing secret.
///
/// Reads the new value from the platform GUI prompt and refuses to
/// rotate a secret that doesn't already exist.
///
/// # Errors
/// Vault open / GUI denial / store errors plus `Error::CryptoFailure` if
/// the secret name is unknown.
pub fn rotate_secret(name: &str) -> Result<(), Error> {
    let vault = Vault::open_default()?;
    if !vault.has_secret(name) {
        return Err(Error::CryptoFailure(format!(
            "secret '{name}' does not exist in vault. use `envseal store` to create it."
        )));
    }
    let config = security_config::load_config(vault.root(), vault.master_key_bytes())?;
    let secret = gui::request_secret_value(
        name,
        &format!("Enter new value for secret rotation: {name}"),
        &config,
    )?;
    vault.store(name, secret.as_bytes(), true)?;
    let warnings = secret_health::check_entropy(name, secret.as_bytes());
    // Same unified-pipeline routing as store_secret_in. Don't keep a
    // bespoke "for w in &warnings { eprintln! }" path here that would
    // drift in formatting from the rest of the system.
    let _ = crate::guard::emit_signals_inline(warnings, &config);
    audit::log_required_at(
        vault.root(),
        &audit::AuditEvent::SecretStored {
            name: name.to_string(),
        },
    )?;
    Ok(())
}

// ── .env import ───────────────────────────────────────────────────

/// Result of importing a `.env` file into the vault.
#[derive(Debug, Clone, Default)]
pub struct ImportResult {
    /// Per-secret store result (one entry per non-empty `KEY=value` line).
    pub entries: Vec<ImportEntry>,
    /// `.envseal` mapping lines to write back, in original file order.
    pub envseal_lines: Vec<String>,
    /// Path the `.envseal` file should be written to.
    pub output_path: PathBuf,
    /// Number of secrets newly stored (not skipped).
    pub imported: usize,
}

/// Status of one entry in [`ImportResult::entries`].
#[derive(Debug, Clone)]
pub struct ImportEntry {
    /// Original env-var name from the `.env` line.
    pub env_var: String,
    /// Vault secret name we attempted to store under.
    pub secret_name: String,
    /// `Ok(signals)` on successful store — entropy / quality
    /// signals the caller can render through the unified pipeline;
    /// `Err(message)` if the entry was skipped (already exists, IO
    /// failure, …).
    pub status: Result<Vec<crate::guard::Signal>, String>,
}

/// Parse `.env` file, store each entry, and prepare the corresponding
/// `.envseal` reference content.
///
/// The CLI/MCP layer is responsible for any user-visible logging, writing
/// the `.envseal` file, and (optionally) shredding the original.
///
/// # Errors
/// Returns `Error::StorageIo` on read failure, `Error::CryptoFailure`
/// when no valid entries are found.
pub fn import_env_file(env_path: &Path) -> Result<ImportResult, Error> {
    let content = std::fs::read_to_string(env_path).map_err(Error::StorageIo)?;

    let mut parsed: Vec<(String, String, String)> = Vec::new();
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let parts: Vec<&str> = trimmed.splitn(2, '=').collect();
        if parts.len() != 2 || parts[0].is_empty() {
            continue;
        }
        let env_var = parts[0].trim().to_string();
        let raw_value = parts[1].trim().to_string();
        let value = raw_value
            .strip_prefix('"')
            .and_then(|v| v.strip_suffix('"'))
            .or_else(|| {
                raw_value
                    .strip_prefix('\'')
                    .and_then(|v| v.strip_suffix('\''))
            })
            .unwrap_or(&raw_value)
            .to_string();
        if value.is_empty() {
            continue;
        }
        let secret_name = env_var.to_lowercase().replace('_', "-");
        parsed.push((env_var, secret_name, value));
    }

    if parsed.is_empty() {
        return Err(Error::CryptoFailure(format!(
            "no valid key-value pairs found in {}",
            env_path.display()
        )));
    }

    let vault = Vault::open_default()?;
    let mut entries = Vec::with_capacity(parsed.len());
    let mut envseal_lines = Vec::with_capacity(parsed.len());
    let mut imported = 0_usize;

    for (env_var, secret_name, value) in parsed {
        let status = match vault.store(&secret_name, value.as_bytes(), false) {
            Ok(()) => {
                let warnings = secret_health::check_entropy(&secret_name, value.as_bytes());
                audit::log_required_at(
                    vault.root(),
                    &audit::AuditEvent::SecretStored {
                        name: secret_name.clone(),
                    },
                )?;
                imported += 1;
                Ok(warnings)
            }
            Err(e) => Err(e.to_string()),
        };
        // Best-effort zeroize of the plaintext value so imported secrets
        // don't linger in freed heap memory.
        let mut value_bytes = value.into_bytes();
        value_bytes.zeroize();
        envseal_lines.push(format!("{env_var}={secret_name}"));
        entries.push(ImportEntry {
            env_var,
            secret_name,
            status,
        });
    }

    let output_path = if env_path.file_name().map(|f| f.to_str()) == Some(Some(".env")) {
        env_path.with_file_name(".envseal")
    } else {
        env_path.with_extension("envseal")
    };

    Ok(ImportResult {
        entries,
        envseal_lines,
        output_path,
        imported,
    })
}