envseal 0.3.12

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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
//! Encrypted secret vault.
//!
//! Stores secrets encrypted with AES-256-GCM. The encryption key is a
//! passphrase-protected master key (see [`crate::keychain`]) that CANNOT be
//! reconstructed from disk alone — it requires a GUI-entered passphrase.
//!
//! # Security Properties
//!
//! - Master key protected by Argon2id-wrapped passphrase (GUI-only entry)
//! - Key material held in `mlock`'d memory, zeroized on drop
//! - File permissions restricted to owner only (0o600)
//! - Secret file names validated against path traversal attacks
//!
//! # Storage Layout
//!
//! ```text
//! ~/.config/envseal/
//! ├── vault/
//! │   ├── <name>.seal    # encrypted secret (nonce || ciphertext || tag)
//! │   └── ...
//! ├── master.key         # passphrase-wrapped master key
//! ├── policy.toml        # whitelist rules
//! └── policy.sig         # HMAC signature of policy.toml
//! ```

use std::fs;
use std::io::{Read, Seek, SeekFrom, Write};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};

use aes_gcm::aead::{Aead, OsRng};
use aes_gcm::{AeadCore, Aes256Gcm, KeyInit};
use zeroize::Zeroizing;

use crate::error::Error;
use crate::keychain::MasterKey;

/// Size of the AES-256-GCM nonce in bytes.
const NONCE_SIZE: usize = 12;

/// Maximum permitted plaintext size for a single secret. The vault
/// is the canonical owner of this limit — every other layer
/// (`ops::store_secret`, MCP tools) re-uses this constant rather
/// than redefining it.
pub const MAX_SECRET_SIZE_BYTES: usize = 64 * 1024;

/// The encrypted secret vault.
///
/// Holds a reference to the root directory and the unlocked master key.
/// The master key is zeroized when the vault is dropped.
#[derive(Debug)]
pub struct Vault {
    /// Root directory for all vault data.
    root: PathBuf,
    /// The unlocked master key (mlock'd, zeroized on drop).
    master_key: MasterKey,
}

impl Vault {
    /// Validate a vault root path — rejects world-writable dirs, /tmp, etc.
    ///
    /// This is the public API for the internal `reject_unsafe_vault_root` check.
    /// Used by security test suites.
    pub fn validate_root(root: &Path) -> Result<(), Error> {
        reject_unsafe_vault_root(root)
    }

    /// Open or initialize the vault at the default location.
    ///
    /// Prompts for the passphrase via GUI popup.
    pub fn open_default() -> Result<Self, Error> {
        let root = default_vault_root()?;
        Self::open(&root)
    }

    /// Open or initialize the vault at the default location using a
    /// caller-supplied passphrase. Never spawns a platform GUI dialog.
    ///
    /// Used by the desktop GUI worker thread so the passphrase entry
    /// stays inside the egui window and never blocks the render thread
    /// on a `PowerShell` / zenity / osascript subprocess.
    ///
    /// # TOTP
    /// If the loaded security config has TOTP enabled, this returns
    /// `Error::CryptoFailure("vault has TOTP enabled — use envseal CLI
    /// to unlock; GUI TOTP support is planned for v0.3")`. Vaults
    /// without TOTP unlock fully through this API.
    ///
    /// # Errors
    /// Same as [`Vault::open`] plus the TOTP deferral noted above.
    pub fn open_default_with_passphrase(
        passphrase: &zeroize::Zeroizing<String>,
    ) -> Result<Self, Error> {
        let root = default_vault_root()?;
        Self::open_with_passphrase(&root, passphrase)
    }

    /// Open or initialize the vault at `root` using a caller-supplied
    /// passphrase. See [`Vault::open_default_with_passphrase`] for
    /// the design rationale.
    ///
    /// # Errors
    /// Same as [`Vault::open`] plus the TOTP deferral.
    pub fn open_with_passphrase(
        root: &Path,
        passphrase: &zeroize::Zeroizing<String>,
    ) -> Result<Self, Error> {
        Self::open_inner(root, Some(passphrase))
    }

    /// Open or initialize the vault at the given root directory.
    ///
    /// If the vault doesn't exist, prompts for a new passphrase.
    /// If it does, prompts for the existing passphrase to unlock.
    pub fn open(root: &Path) -> Result<Self, Error> {
        Self::open_inner(root, None)
    }

    /// Shared open path. When `passphrase` is `Some`, never prompts via
    /// the platform GUI; when `None`, falls back to the historical
    /// GUI-prompting flow used by CLI/MCP.
    fn open_inner(
        root: &Path,
        passphrase: Option<&zeroize::Zeroizing<String>>,
    ) -> Result<Self, Error> {
        // GUARD: Hard-block vault in world-writable directories (ALWAYS ON — not configurable)
        reject_unsafe_vault_root(root)?;

        // GUARD: Check for library injection on this process itself
        crate::guard::check_self_preload()?;

        // GUARD: Harden process before touching any key material
        crate::guard::harden_process();

        // GUARD: Verify vault root isn't a symlink
        crate::guard::verify_not_symlink(root)?;

        let vault_dir = root.join("vault");
        crate::guard::verify_not_symlink(&vault_dir)?;
        // Atomic-ish directory creation: set restrictive permissions
        // at creation time on Unix so there's no race window where the
        // directory is world-readable.
        #[cfg(unix)]
        {
            use std::os::unix::fs::DirBuilderExt;
            if !vault_dir.exists() {
                // `recursive(true)` auto-creates any missing parent
                // directories. Without it, opening a vault at a path
                // like `~/.cache/foo/bar/vault-root/` fails on Linux
                // when the intermediate `bar/` doesn't exist — even
                // though the equivalent Windows path uses
                // `create_dir_all` and works. Match Windows semantics
                // so callers don't have to special-case Unix.
                fs::DirBuilder::new()
                    .recursive(true)
                    .mode(0o700)
                    .create(&vault_dir)
                    .map_err(Error::StorageIo)?;
            }
        }
        #[cfg(not(unix))]
        {
            fs::create_dir_all(&vault_dir).map_err(Error::StorageIo)?;
        }

        // GUARD: Harden directory permissions (prevent other users from reading)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            // Set vault root and vault dir to 0o700 (owner only)
            fs::set_permissions(root, fs::Permissions::from_mode(0o700))
                .map_err(Error::StorageIo)?;
            fs::set_permissions(&vault_dir, fs::Permissions::from_mode(0o700))
                .map_err(Error::StorageIo)?;
        };

        // GUARD: Verify master.key isn't a symlink
        let mk_path = root.join("master.key");
        crate::guard::verify_not_symlink(&mk_path)?;
        crate::guard::verify_not_symlink(&root.join("policy.toml"))?;
        crate::guard::verify_not_symlink(&root.join("security.toml"))?;

        let master_key = match passphrase {
            Some(p) => crate::keychain::open_master_key_with_passphrase(root, p)?,
            None => crate::keychain::open_master_key(root)?,
        };

        // TOTP verification — second factor after passphrase
        let sec_config = crate::security_config::load_config(root, master_key.as_bytes())?;

        if sec_config.totp_required {
            if passphrase.is_some() {
                // Caller supplied passphrase non-interactively (desktop GUI
                // worker). TOTP entry is also a GUI prompt that we don't
                // yet route through the egui modal — defer with a clear
                // pointer to the CLI rather than spawning the platform
                // dialog (which is what made the GUI freeze in the first
                // place).
                return Err(Error::CryptoFailure(
                    "this vault has TOTP enabled — use the `envseal` CLI \
                     to unlock; in-window TOTP entry is planned for v0.3"
                        .to_string(),
                ));
            }
            verify_totp_factor(root, &sec_config, master_key.as_bytes())?;
        }

        Ok(Self {
            root: root.to_path_buf(),
            master_key,
        })
    }

    /// Open a vault with a provided master key — **test / fuzzing only**.
    ///
    /// Skips the GUI passphrase and TOTP flow. See the security
    /// warning on [`MasterKey::from_test_bytes`] (audit M21) for the
    /// runtime guard that aborts this function outside a recognized
    /// test / fuzz / bench harness.
    #[cfg(any(test, feature = "test-backdoors"))]
    #[doc(hidden)]
    pub fn open_with_key(root: &Path, master_key: MasterKey) -> Result<Self, Error> {
        crate::test_backdoors::assert_test_backdoor_safe();
        reject_unsafe_vault_root(root)?;
        crate::guard::check_self_preload()?;
        crate::guard::harden_process();
        crate::guard::verify_not_symlink(root)?;

        let vault_dir = root.join("vault");
        crate::guard::verify_not_symlink(&vault_dir)?;
        fs::create_dir_all(&vault_dir)?;

        let mk_path = root.join("master.key");
        crate::guard::verify_not_symlink(&mk_path)?;
        crate::guard::verify_not_symlink(&root.join("policy.toml"))?;
        crate::guard::verify_not_symlink(&root.join("security.toml"))?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = fs::set_permissions(root, fs::Permissions::from_mode(0o700));
            let _ = fs::set_permissions(&vault_dir, fs::Permissions::from_mode(0o700));
        }

        Ok(Self {
            root: root.to_path_buf(),
            master_key,
        })
    }

    /// Store a secret. The value is encrypted and written to disk.
    ///
    /// Returns an error if a secret with this name already exists
    /// and `force` is false.
    pub fn store(&self, name: &str, value: &[u8], force: bool) -> Result<(), 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
            )));
        }
        validate_name(name)?;
        let path = self.secret_path(name);
        crate::guard::verify_not_symlink(&path)?;

        let cipher = Aes256Gcm::new(self.master_key.as_aes_key());
        let nonce = Aes256Gcm::generate_nonce(&mut OsRng);

        let ciphertext = cipher
            .encrypt(
                &nonce,
                aes_gcm::aead::Payload {
                    msg: value,
                    aad: name.as_bytes(),
                },
            )
            .map_err(|e| Error::CryptoFailure(format!("encryption failed: {e}")))?;

        // Write: nonce (12 bytes) || ciphertext+tag
        let mut sealed = Vec::with_capacity(NONCE_SIZE + ciphertext.len());
        sealed.extend_from_slice(&nonce);
        sealed.extend_from_slice(&ciphertext);

        if force {
            // The tmp filename must be unique across concurrent stores in
            // the same process. PID + nanos alone collides under load
            // (multiple threads in one millisecond on coarse clocks). We
            // also include the OS thread id and a process-wide atomic
            // counter so the chance of two stores ever picking the same
            // tmp_name is zero.
            use std::sync::atomic::{AtomicU64, Ordering};
            static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
            let counter = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
            let thread_id = format!("{:?}", std::thread::current().id());
            let tmp_name = format!(
                ".{}.seal.tmp.{}.{}.{counter}.{thread_id}",
                name,
                std::process::id(),
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_nanos(),
            );
            let tmp_path = self.root.join("vault").join(tmp_name);
            let mut file = open_secret_for_create(&tmp_path, name)?;
            file.write_all(&sealed).map_err(Error::StorageIo)?;
            file.sync_all().map_err(Error::StorageIo)?;
            fs::rename(&tmp_path, &path)?;
        } else {
            let mut file = open_secret_for_create(&path, name)?;
            file.write_all(&sealed).map_err(Error::StorageIo)?;
            file.sync_all().map_err(Error::StorageIo)?;
        }

        Ok(())
    }

    /// Decrypt a secret by name. Returns the plaintext bytes.
    ///
    /// The plaintext is returned in a [`Zeroizing`] wrapper that
    /// scrubs memory on drop.
    pub fn decrypt(&self, name: &str) -> Result<Zeroizing<Vec<u8>>, Error> {
        // CTF integrity: the flag is write-once, verify-only-via-hash.
        // Refusing decrypt at the vault level closes off every leak path
        // that would otherwise need its own block — peek (4-char prefix
        // leak), copy/rename (launder to another name then peek), health
        // (entropy report), execution injection, and any future caller.
        // `ctf_setup` writes via `store`; `ctf_verify` reads `ctf-hash.txt`;
        // `ctf_reset` deletes the sealed file without decrypting. No
        // legitimate path needs the plaintext.
        // Case-insensitive: NTFS (Windows) and HFS+/APFS-default (macOS)
        // are case-insensitive, so `vault/CTF-FLAG.seal` resolves to the
        // same file as `vault/ctf-flag.seal`. A case-sensitive `==` here
        // would let `vault.decrypt("CTF-FLAG")` slip past the gate and
        // leak the plaintext via the underlying open(). Compare ASCII-
        // case-insensitively so the structural refusal holds on every
        // platform regardless of FS quirks.
        if name.eq_ignore_ascii_case("ctf-flag") {
            crate::audit::log_required_at(
                self.root(),
                &crate::audit::AuditEvent::SignalRecorded {
                    tier: "Lockdown".to_string(),
                    classification:
                        "critical [ctf.flag.decrypt_attempt] refused vault.decrypt(\"ctf-flag\")"
                            .to_string(),
                },
            )
            .map_err(|e| Error::AuditLogFailed(e.to_string()))?;
            return Err(Error::CryptoFailure(
                "ctf-flag is non-decryptable by design. The CTF flag can only \
                 be checked via `envseal ctf verify <flag>`, which compares \
                 SHA-256 hashes — never the plaintext. Tear down the challenge \
                 with `envseal ctf reset` if you need to clear it."
                    .to_string(),
            ));
        }
        let path = self.secret_path(name);
        // SECURITY (audit C1): open atomically with no-traverse
        // semantics. Unix gets O_NOFOLLOW + O_CLOEXEC; Windows gets
        // FILE_FLAG_OPEN_REPARSE_POINT plus a post-open check that
        // the handle's attributes do NOT include
        // FILE_ATTRIBUTE_REPARSE_POINT. This eliminates the TOCTOU
        // window where an attacker could replace a secret file with
        // a junction / symlink between `verify_not_symlink` and the
        // actual read — leaking secrets to the redirected target,
        // or DOSing reads via /dev/zero-style targets.
        let handle = match crate::file::atomic_open::open_read_no_traverse(&path) {
            Ok(h) => h,
            Err(Error::StorageIo(e)) if e.kind() == std::io::ErrorKind::NotFound => {
                return Err(Error::SecretNotFound(name.to_string()));
            }
            Err(e) => return Err(e),
        };

        let mut sealed = Vec::new();
        // Limit read size to prevent DoS via /dev/zero symlink (if O_NOFOLLOW failed)
        handle
            .take(MAX_SECRET_SIZE_BYTES as u64 + 100)
            .read_to_end(&mut sealed)
            .map_err(Error::StorageIo)?;

        if sealed.len() < NONCE_SIZE {
            return Err(Error::CryptoFailure(
                "sealed file too short: possible corruption".to_string(),
            ));
        }

        let (nonce_bytes, ciphertext) = sealed.split_at(NONCE_SIZE);
        let nonce = aes_gcm::Nonce::from_slice(nonce_bytes);

        let cipher = Aes256Gcm::new(self.master_key.as_aes_key());
        let plaintext = cipher
            .decrypt(
                nonce,
                aes_gcm::aead::Payload {
                    msg: ciphertext,
                    aad: name.as_bytes(),
                },
            )
            .map_err(|e| Error::CryptoFailure(format!("decryption failed: {e}")))?;

        Ok(Zeroizing::new(plaintext))
    }

    /// List all secret names in the vault.
    pub fn list(&self) -> Result<Vec<String>, Error> {
        let vault_dir = self.root.join("vault");
        let mut names = Vec::new();

        if vault_dir.exists() {
            for entry in fs::read_dir(&vault_dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.extension().and_then(|e| e.to_str()) == Some("seal") {
                    crate::guard::verify_not_symlink(&path)?;
                    if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                        names.push(stem.to_string());
                    }
                }
            }
        }

        names.sort();
        Ok(names)
    }

    /// Delete a secret from the vault.
    ///
    /// Overwrites the file with zeros before deleting (best-effort secure
    /// delete to prevent recovery from filesystem journal/snapshots).
    pub fn revoke(&self, name: &str) -> Result<(), Error> {
        let path = self.secret_path(name);
        crate::guard::verify_not_symlink(&path)?;
        let mut file = open_secret_for_revoke(&path).map_err(|e| match e {
            Error::StorageIo(ref io) if io.kind() == std::io::ErrorKind::NotFound => {
                Error::SecretNotFound(name.to_string())
            }
            other => other,
        })?;
        let len = usize::try_from(file.metadata().map_err(Error::StorageIo)?.len()).unwrap_or(0);
        if len > 0 {
            file.seek(SeekFrom::Start(0)).map_err(Error::StorageIo)?;
            let buf = [0u8; 8192];
            let mut remaining = len;
            while remaining > 0 {
                let n = remaining.min(buf.len());
                file.write_all(&buf[..n]).map_err(Error::StorageIo)?;
                remaining -= n;
            }
            file.sync_all().map_err(Error::StorageIo)?;
        }
        drop(file);
        fs::remove_file(&path)?;

        Ok(())
    }

    /// Path to the policy file.
    pub fn policy_path(&self) -> PathBuf {
        self.root.join("policy.toml")
    }

    /// Path to the policy signature file.
    pub fn policy_sig_path(&self) -> PathBuf {
        self.root.join("policy.sig")
    }

    /// Get a reference to the master key (for HMAC signing).
    pub fn master_key(&self) -> &MasterKey {
        &self.master_key
    }

    /// Path to a specific secret file.
    pub fn secret_path(&self, name: &str) -> PathBuf {
        self.root.join("vault").join(format!("{name}.seal"))
    }

    /// Cheap membership test — does a sealed file with this name
    /// exist on disk? Equivalent to `secret_path(name).exists()`
    /// but more readable at call sites that just want a boolean
    /// (e.g. preflighting `.envseal` mappings before prompting).
    /// Doesn't decrypt; the secret could be present-but-corrupt
    /// and `has_secret` would still report `true`.
    #[must_use]
    pub fn has_secret(&self, name: &str) -> bool {
        self.secret_path(name).exists()
    }

    /// Get the master key bytes for HMAC operations.
    ///
    /// Used internally by the inject pipeline to sign/verify policy files.
    pub fn master_key_bytes(&self) -> &[u8; 32] {
        self.master_key.as_bytes()
    }

    /// Get the vault root directory.
    pub fn root(&self) -> &std::path::Path {
        &self.root
    }
}

fn open_secret_for_revoke(path: &Path) -> Result<std::fs::File, Error> {
    #[cfg(unix)]
    {
        std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
            .open(path)
            .map_err(Error::StorageIo)
    }
    #[cfg(not(unix))]
    {
        std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
            .map_err(Error::StorageIo)
    }
}

fn open_secret_for_create(path: &Path, secret_name: &str) -> Result<std::fs::File, Error> {
    let mut opts = std::fs::OpenOptions::new();
    opts.write(true).truncate(true);
    opts.create_new(true);
    #[cfg(unix)]
    {
        opts.mode(0o600)
            .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC);
    }
    opts.open(path).map_err(|e| {
        if e.kind() == std::io::ErrorKind::AlreadyExists {
            Error::SecretAlreadyExists(secret_name.to_string())
        } else {
            Error::StorageIo(e)
        }
    })
}

/// Validate that a secret name is safe for use as a filename.
///
/// Rejects:
/// - Empty names
/// - Path separators (/, \, ..)
/// - Hidden files (.name)
/// - Shell metacharacters that could be misinterpreted
/// - Non-ASCII (prevents encoding confusion attacks)
/// - Overly long names (filesystem limits)
fn validate_name(name: &str) -> Result<(), Error> {
    // Block shell metacharacters that could cause issues if names are
    // ever interpolated into shell commands or log messages
    const BLOCKED_CHARS: &[char] = &[
        '$', '`', '!', '&', '|', ';', '(', ')', '{', '}', '<', '>', '"', '\'', '\n', '\r', '\t',
        '*', '?', '[', ']', '~', '#',
    ];

    if name.is_empty() {
        return Err(Error::CryptoFailure(
            "secret name must not be empty".to_string(),
        ));
    }
    if name.len() > 200 {
        return Err(Error::CryptoFailure(format!(
            "secret name too long ({} chars, max 200)",
            name.len()
        )));
    }
    if name.contains('/') || name.contains('\\') || name.contains('\0') || name.starts_with('.') {
        return Err(Error::CryptoFailure(format!(
            "invalid secret name '{name}': must not contain path separators or start with '.'"
        )));
    }
    if name.contains("..") {
        return Err(Error::CryptoFailure(format!(
            "invalid secret name '{name}': path traversal detected"
        )));
    }
    for ch in BLOCKED_CHARS {
        if name.contains(*ch) {
            return Err(Error::CryptoFailure(format!(
                "invalid secret name '{name}': contains forbidden character '{ch}'"
            )));
        }
    }
    // Only allow ASCII printable (alphanumeric, hyphens, underscores, dots, @, +, =, commas)
    if !name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || "-_.@+=,".contains(c))
    {
        return Err(Error::CryptoFailure(format!(
            "invalid secret name '{name}': only ASCII alphanumeric, hyphens, underscores, \
             dots, @, +, =, and commas are allowed"
        )));
    }
    Ok(())
}

/// ALWAYS-ON: Reject vault roots in world-writable or agent-accessible directories.
///
/// This is NOT configurable — it has zero convenience impact (no real user would
/// store a vault in /tmp) and prevents a critical attack where an agent sets
/// `XDG_CONFIG_HOME=/tmp/evil` to create a vault it controls.
fn reject_unsafe_vault_root(root: &Path) -> Result<(), Error> {
    // Hard-block known dangerous prefixes
    const BLOCKED_PREFIXES: &[&str] = &[
        "/tmp",
        "/var/tmp",
        "/dev/shm",
        "/dev/mqueue",
        "/run/user", // systemd tmpfiles — often world-readable
    ];

    let root_str = root.to_string_lossy();

    for prefix in BLOCKED_PREFIXES {
        if root_str.starts_with(prefix) {
            return Err(Error::EnvironmentCompromised(format!(
                "vault root '{}' is in a world-writable directory ({prefix}). \
                 this is a hard block — envseal will never store secrets here. \
                 use the default location (~/.config/envseal) instead.",
                root.display()
            )));
        }
    }

    // On Unix, also check if the directory is world-writable
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        if root.exists() {
            if let Ok(meta) = fs::metadata(root) {
                let mode = meta.mode();
                // world-writable (o+w)
                if mode & 0o002 != 0 {
                    return Err(Error::EnvironmentCompromised(format!(
                        "vault root '{}' is world-writable (mode={mode:04o}). \
                         this is a hard block — secrets must not be stored in \
                         world-writable directories.",
                        root.display()
                    )));
                }
                // Not owned by current user
                if meta.uid() != unsafe { libc::geteuid() } {
                    return Err(Error::EnvironmentCompromised(format!(
                        "vault root '{}' is not owned by the current user (uid={}). \
                         this is a hard block.",
                        root.display(),
                        meta.uid()
                    )));
                }
            }
        }
    }

    Ok(())
}

/// Get the default vault root directory.
pub(crate) fn default_vault_root() -> Result<PathBuf, Error> {
    let config_dir = dirs_path()?;
    Ok(config_dir.join("envseal"))
}

/// Get the platform config directory.
///
/// Validates `XDG_CONFIG_HOME` against poisoning attacks:
/// - Must not be in /tmp, /var/tmp, or other world-writable locations
/// - Must be owned by the current user
/// - Falls back to `$HOME/.config` if invalid
fn dirs_path() -> Result<PathBuf, Error> {
    if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
        let xdg_path = PathBuf::from(&xdg);

        // GUARD: Reject obviously hostile paths
        let xdg_str = xdg_path.to_string_lossy();
        if xdg_str.starts_with("/tmp")
            || xdg_str.starts_with("/var/tmp")
            || xdg_str.starts_with("/dev/shm")
        {
            // Route through the unified policy/render pipeline so the
            // user's `security.toml` can demote this to `log` (CI use
            // case) or promote to `block` (paranoid setup) — and so
            // the audit trail records the rejection alongside every
            // other Signal.
            let _ = crate::guard::emit_signal_inline(
                crate::guard::Signal::new(
                    crate::guard::SignalId::new("disk.xdg_config.untrusted_prefix"),
                    crate::guard::Category::DiskPermissions,
                    crate::guard::Severity::Warn,
                    "XDG_CONFIG_HOME points to a world-writable location",
                    format!(
                        "XDG_CONFIG_HOME='{xdg}' resolves under /tmp, /var/tmp, or /dev/shm — \
                         falling back to $HOME/.config"
                    ),
                    "unset XDG_CONFIG_HOME or point it at a user-owned directory",
                ),
                &crate::security_config::load_system_defaults(),
            );
            // Fall through to $HOME/.config
        } else {
            #[cfg(unix)]
            {
                if xdg_path.exists() {
                    use std::os::unix::fs::MetadataExt;
                    if let Ok(meta) = std::fs::metadata(&xdg_path) {
                        if meta.uid() != unsafe { libc::geteuid() } {
                            return Err(Error::StorageIo(std::io::Error::new(
                                std::io::ErrorKind::PermissionDenied,
                                format!("XDG_CONFIG_HOME ({xdg}) is not owned by the current user"),
                            )));
                        }
                        // Reject world-writable directories
                        let mode = meta.mode();
                        if mode & 0o002 != 0 {
                            let _ = crate::guard::emit_signal_inline(
                                crate::guard::Signal::new(
                                    crate::guard::SignalId::new("disk.xdg_config.world_writable"),
                                    crate::guard::Category::DiskPermissions,
                                    crate::guard::Severity::Warn,
                                    "XDG_CONFIG_HOME is world-writable",
                                    format!(
                                        "XDG_CONFIG_HOME='{xdg}' has mode {mode:04o} — \
                                         falling back to $HOME/.config"
                                    ),
                                    "chmod o-w on the directory or unset XDG_CONFIG_HOME",
                                ),
                                &crate::security_config::load_system_defaults(),
                            );
                        } else {
                            return Ok(xdg_path);
                        }
                    }
                } else {
                    return Ok(xdg_path);
                }
            }
            #[cfg(not(unix))]
            {
                return Ok(xdg_path);
            }
        }
    }
    // Cross-platform home: HOME on Unix and Git-for-Windows shells;
    // USERPROFILE on plain cmd.exe / PowerShell. Without the
    // USERPROFILE fallback, a clean Windows install (no Git Bash)
    // dies with "HOME not set" the first time the user runs envseal.
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .map_err(|_| {
            Error::StorageIo(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "neither HOME nor USERPROFILE is set",
            ))
        })?;
    Ok(PathBuf::from(home).join(".config"))
}

/// Verify TOTP second factor during vault open.
///
/// Decrypts the stored TOTP secret, shows a GUI popup asking for
/// the 6-digit code, and verifies it. Up to 3 attempts are allowed.
fn verify_totp_factor(
    root: &Path,
    config: &crate::security_config::SecurityConfig,
    master_key: &[u8; 32],
) -> Result<(), Error> {
    let encrypted_secret = config.totp_secret_encrypted.as_deref().ok_or_else(|| {
        Error::CryptoFailure(
            "TOTP is required but no secret is configured. \
             Run `envseal security totp-setup` first."
                .to_string(),
        )
    })?;

    let secret_b32 = crate::totp::decrypt_secret(encrypted_secret, master_key)?;

    // Allow up to 3 attempts
    for attempt in 1..=3 {
        let user_code = crate::gui::request_totp_code(attempt)?;

        match crate::totp::verify_code(&secret_b32, &user_code) {
            Ok(true) => {
                crate::audit::log_required_at(
                    root,
                    &crate::audit::AuditEvent::ChallengeAttempted { passed: true },
                )?;
                return Ok(());
            }
            Ok(false) => {
                crate::audit::log_required_at(
                    root,
                    &crate::audit::AuditEvent::ChallengeAttempted { passed: false },
                )?;
                if attempt < 3 {
                    eprintln!("envseal: invalid TOTP code (attempt {attempt}/3)");
                }
            }
            Err(e) => return Err(e),
        }
    }

    Err(Error::CryptoFailure(
        "TOTP verification failed after 3 attempts".to_string(),
    ))
}