envseal 0.3.7

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
//! Deep security tests — adversarial edge cases, crypto boundary conditions,
//! and attack simulation for security-critical paths.
//!
//! These tests focus on:
//! - Vault root safety (XDG_CONFIG_HOME poisoning, /tmp rejection)
//! - Secret name sanitization (path traversal, null bytes, symlinks)
//! - Entropy detection edge cases
//! - Crypto boundary conditions (nonce reuse, corrupted ciphertext)
//! - TOCTOU hardening
//! - Policy HMAC tamper detection

#[path = "common/mod.rs"]
mod common;

// ═══════════════════════════════════════════════════════════════
//  Vault Root Safety
// ═══════════════════════════════════════════════════════════════

mod vault_root_safety {
    //! Tests that vault refuses to operate in unsafe directories.

    use envseal::vault::Vault;

    /// Vault must reject /tmp — prevents XDG_CONFIG_HOME poisoning.
    #[test]
    fn rejects_tmp_root() {
        let result = Vault::validate_root(std::path::Path::new("/tmp/evil-vault"));
        assert!(result.is_err(), "vault should reject /tmp root");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("world-writable") || err.contains("hard block"),
            "error should explain why: {err}"
        );
    }

    /// Vault must reject /var/tmp.
    #[test]
    fn rejects_var_tmp_root() {
        let result = Vault::validate_root(std::path::Path::new("/var/tmp/evil"));
        assert!(result.is_err(), "vault should reject /var/tmp root");
    }

    /// Vault must reject /dev/shm.
    #[test]
    fn rejects_dev_shm_root() {
        let result = Vault::validate_root(std::path::Path::new("/dev/shm/vault"));
        assert!(result.is_err(), "vault should reject /dev/shm root");
    }

    /// Vault must reject nested paths under /tmp.
    #[test]
    fn rejects_nested_tmp_root() {
        let result = Vault::validate_root(std::path::Path::new("/tmp/deep/nested/path/vault"));
        assert!(result.is_err(), "vault should reject nested /tmp paths");
    }

    /// Vault must accept safe paths (user home).
    #[test]
    fn accepts_safe_tmpdir_root() {
        // Use a tempfile dir which is typically under /tmp but
        // we create a safe-named vault dir to test the actual open logic
        let dir = tempfile::tempdir_in(std::env::var("HOME").unwrap_or("/nonexistent".into()));
        if let Ok(d) = dir {
            let passphrase = zeroize::Zeroizing::new("test-passphrase".to_string());
            let result = Vault::open_with_passphrase(d.path(), &passphrase);
            // Should succeed since it's under $HOME
            assert!(
                result.is_ok(),
                "vault should accept home-dir paths: {:?}",
                result.err()
            );
        }
    }
}

// ═══════════════════════════════════════════════════════════════
//  Secret Name Sanitization (attacks via store/decrypt names)
// ═══════════════════════════════════════════════════════════════

mod secret_name_attacks {
    //! Adversarial secret names that try to escape the vault directory.

    use crate::common::temp_vault;

    /// Path traversal with `../` must be rejected.
    #[test]
    fn rejects_path_traversal() {
        let (_dir, vault) = temp_vault();
        let result = vault.store("../../../etc/passwd", b"evil", false);
        assert!(result.is_err());
    }

    /// Null byte in name — could truncate C-level paths.
    #[test]
    fn rejects_null_byte_in_name() {
        let (_dir, vault) = temp_vault();
        let result = vault.store("secret\0evil", b"data", false);
        assert!(result.is_err());
    }

    /// Hidden file names (starting with .) must be rejected.
    #[test]
    fn rejects_hidden_name() {
        let (_dir, vault) = temp_vault();
        let result = vault.store(".hidden-secret", b"data", false);
        assert!(result.is_err());
    }

    /// Names with slashes must be rejected.
    #[test]
    fn rejects_slash_name() {
        let (_dir, vault) = temp_vault();
        assert!(vault.store("path/to/secret", b"data", false).is_err());
        assert!(vault.store("/absolute/path", b"data", false).is_err());
    }

    /// Empty name must be rejected.
    #[test]
    fn rejects_empty_name() {
        let (_dir, vault) = temp_vault();
        assert!(vault.store("", b"data", false).is_err());
    }

    /// Windows-style path separator.
    #[test]
    fn backslash_in_name() {
        let (_dir, vault) = temp_vault();
        let result = vault.store("test\\evil", b"data", false);
        // Should either work (backslash is valid in Unix filenames) or be rejected
        // Key: must NOT create files outside the vault directory
        if result.is_ok() {
            // Verify the secret is readable
            let dec = vault.decrypt("test\\evil").unwrap();
            assert_eq!(&dec[..], b"data");
        }
    }

    /// Name that looks like a seal file.
    #[test]
    fn name_with_seal_extension() {
        let (_dir, vault) = temp_vault();
        // This shouldn't cause confusion with internal file layout
        vault.store("my-key.seal", b"data", false).unwrap();
        let dec = vault.decrypt("my-key.seal").unwrap();
        assert_eq!(&dec[..], b"data");
    }

    /// Very long name (filesystem limit ~255 chars + .seal suffix).
    #[test]
    fn very_long_name_boundary() {
        let (_dir, vault) = temp_vault();
        // 250 chars + ".seal" (5) = 255 — typical FS limit
        let name: String = (0..250).map(|_| 'x').collect();
        let result = vault.store(&name, b"data", false);
        // Should work — we're at the boundary
        if result.is_ok() {
            assert_eq!(&vault.decrypt(&name).unwrap()[..], b"data");
        }
    }

    /// Name that is just whitespace.
    #[test]
    fn whitespace_only_name() {
        let (_dir, vault) = temp_vault();
        // Whitespace-only names should work (they're valid filenames on Unix)
        // but some implementations may trim them
        let result = vault.store("   ", b"data", false);
        // If accepted, verify roundtrip
        if result.is_ok() {
            assert_eq!(&vault.decrypt("   ").unwrap()[..], b"data");
        }
    }
}

// ═══════════════════════════════════════════════════════════════
//  Crypto Boundary Conditions
// ═══════════════════════════════════════════════════════════════

mod crypto_attacks {
    //! Tests that cryptographic operations fail safely under attack.

    use crate::common::{secret_file_path, temp_vault};

    /// Truncated ciphertext must be detected — not silently return garbage.
    #[test]
    fn truncated_ciphertext_detected() {
        let (dir, vault) = temp_vault();
        vault.store("target", b"secret-data", false).unwrap();

        // Truncate the sealed file
        let seal_path = secret_file_path(dir.path(), "target");
        let data = std::fs::read(&seal_path).unwrap();
        std::fs::write(&seal_path, &data[..data.len() / 2]).unwrap();

        let result = vault.decrypt("target");
        assert!(result.is_err(), "truncated ciphertext should fail");
    }

    /// Flipped bit in ciphertext must be detected.
    #[test]
    fn bitflip_in_ciphertext_detected() {
        let (dir, vault) = temp_vault();
        vault.store("target", b"secret-data", false).unwrap();

        let seal_path = secret_file_path(dir.path(), "target");
        let mut data = std::fs::read(&seal_path).unwrap();
        if data.len() > 20 {
            data[20] ^= 0xFF; // Flip bits in the middle
        }
        std::fs::write(&seal_path, &data).unwrap();

        let result = vault.decrypt("target");
        assert!(result.is_err(), "bit-flipped ciphertext should fail");
    }

    /// Completely random garbage file must be detected.
    #[test]
    fn random_garbage_detected() {
        let (dir, vault) = temp_vault();
        vault.store("target", b"secret-data", false).unwrap();

        let seal_path = secret_file_path(dir.path(), "target");
        let garbage: Vec<u8> = (0..64).map(|i| (i * 37 % 256) as u8).collect();
        std::fs::write(&seal_path, &garbage).unwrap();

        let result = vault.decrypt("target");
        assert!(result.is_err(), "random garbage should fail");
    }

    /// Empty sealed file must be detected.
    #[test]
    fn empty_sealed_file_detected() {
        let (dir, vault) = temp_vault();
        vault.store("target", b"secret-data", false).unwrap();

        let seal_path = secret_file_path(dir.path(), "target");
        std::fs::write(&seal_path, b"").unwrap();

        let result = vault.decrypt("target");
        assert!(result.is_err(), "empty sealed file should fail");
    }

    /// Two stores of the same value must produce different ciphertext (nonce uniqueness).
    #[test]
    fn nonce_uniqueness_on_overwrite() {
        let (dir, vault) = temp_vault();
        vault.store("nonce-test", b"same-value", false).unwrap();
        let seal_path = secret_file_path(dir.path(), "nonce-test");
        let ct1 = std::fs::read(&seal_path).unwrap();

        vault.store("nonce-test", b"same-value", true).unwrap();
        let ct2 = std::fs::read(&seal_path).unwrap();

        assert_ne!(
            ct1, ct2,
            "same value encrypted twice must produce different ciphertext (unique nonce)"
        );
    }

    /// Different keys must produce different ciphertext for same plaintext.
    #[test]
    fn different_keys_different_ciphertext() {
        let (_dir1, vault1) = temp_vault();
        let dir2 = tempfile::tempdir_in(std::env::var("HOME").unwrap()).unwrap();
        let pass2 = crate::common::test_passphrase_alt();
        let vault2 = envseal::vault::Vault::open_with_passphrase(dir2.path(), &pass2).unwrap();

        vault1.store("shared", b"same-value", false).unwrap();
        vault2.store("shared", b"same-value", false).unwrap();

        let ct1 = std::fs::read(secret_file_path(vault1.root(), "shared")).unwrap();
        let ct2 = std::fs::read(secret_file_path(dir2.path(), "shared")).unwrap();

        assert_ne!(ct1, ct2, "different keys must produce different ciphertext");
    }
}

// ═══════════════════════════════════════════════════════════════
//  Policy HMAC Tamper Detection
// ═══════════════════════════════════════════════════════════════

mod policy_tampering {
    //! Tests that policy file tampering is detected via HMAC.

    use crate::common::{TEST_KEY_BYTES, TEST_KEY_BYTES_ALT};
    use envseal::policy::Policy;

    /// Modifying the sealed policy file breaks AEAD verification.
    /// Pre-0.3.0 this test substituted "python3" → "evil-bin" in the
    /// plaintext TOML; 0.3.0+ writes a sealed blob with no
    /// recognizable substring, so the targeted edit attack is
    /// impossible. The remaining surface is bit-flip / corruption,
    /// which AEAD must reject.
    #[test]
    fn detect_modified_policy() {
        let dir = tempfile::tempdir_in(std::env::var("HOME").unwrap()).unwrap();
        let legacy_path = dir.path().join("policy.toml");

        let mut policy = Policy::default();
        policy.allow_key("/usr/bin/python3", "openai-key");
        policy.save_sealed(&legacy_path, &TEST_KEY_BYTES).unwrap();

        // Tamper the sealed blob — flip a bit in the AEAD-protected region.
        let sealed_path = envseal::policy::sealed_path_for(&legacy_path);
        let mut bytes = std::fs::read(&sealed_path).unwrap();
        let target = bytes.len() - 1;
        bytes[target] ^= 0x01;
        std::fs::write(&sealed_path, &bytes).unwrap();

        let result = Policy::load_sealed(&legacy_path, &TEST_KEY_BYTES);
        assert!(result.is_err(), "tampered sealed policy must be rejected");
    }

    /// Loading with wrong key always fails.
    #[test]
    fn wrong_key_rejects_policy() {
        let dir = tempfile::tempdir_in(std::env::var("HOME").unwrap()).unwrap();
        let path = dir.path().join("policy.toml");

        let mut policy = Policy::default();
        policy.allow_key("/usr/bin/app", "secret");
        policy.save_signed(&path, &TEST_KEY_BYTES).unwrap();

        let result = Policy::load_verified(&path, &TEST_KEY_BYTES_ALT);
        assert!(result.is_err(), "wrong key should reject policy");
    }

    /// Empty policy roundtrips correctly.
    #[test]
    fn empty_policy_roundtrip() {
        let dir = tempfile::tempdir_in(std::env::var("HOME").unwrap()).unwrap();
        let path = dir.path().join("policy.toml");

        let policy = Policy::default();
        policy.save_signed(&path, &TEST_KEY_BYTES).unwrap();

        let loaded = Policy::load_verified(&path, &TEST_KEY_BYTES).unwrap();
        assert!(!loaded.is_authorized("/any/binary", "any-secret"));
    }
}

// ═══════════════════════════════════════════════════════════════
//  Entropy Detection Edge Cases
// ═══════════════════════════════════════════════════════════════

mod entropy_edge_cases {
    //! Test the secret_health entropy checker with adversarial inputs.

    use envseal::secret_health::{check_entropy, shannon_entropy};

    /// All zeros — minimum entropy.
    #[test]
    fn all_zeros_low_entropy() {
        let e = shannon_entropy(&[0u8; 100]);
        assert!(e < 0.1, "all zeros should be ~0 entropy, got {e}");
    }

    /// All unique bytes — maximum entropy.
    #[test]
    fn all_unique_high_entropy() {
        let data: Vec<u8> = (0..=255u8).collect();
        let e = shannon_entropy(&data);
        assert!(e > 7.9, "all unique bytes should be ~8 bits, got {e}");
    }

    /// Single byte.
    #[test]
    fn single_byte_zero_entropy() {
        let e = shannon_entropy(&[42]);
        assert!(
            (e - 0.0).abs() < f64::EPSILON,
            "single byte has 0 entropy: {e}"
        );
    }

    /// Two distinct bytes, equal frequency.
    #[test]
    fn two_bytes_one_bit_entropy() {
        let data: Vec<u8> = (0..100)
            .map(|i| if i % 2 == 0 { b'a' } else { b'b' })
            .collect();
        let e = shannon_entropy(&data);
        assert!(
            (e - 1.0).abs() < 0.01,
            "50/50 split should be 1 bit, got {e}"
        );
    }

    /// Real-world placeholders must be caught.
    #[test]
    fn detects_changeme() {
        let warnings = check_entropy("test", b"changeme");
        assert!(!warnings.is_empty());
        assert!(warnings
            .iter()
            .any(|w| w.id.as_str().starts_with("secret.entropy.placeholder.")));
    }

    #[test]
    fn detects_replace_me() {
        let warnings = check_entropy("test", b"replace-me");
        assert!(!warnings.is_empty());
    }

    #[test]
    fn detects_xxx() {
        let warnings = check_entropy("test", b"xxx");
        // Should flag as too short
        assert!(!warnings.is_empty());
    }

    /// Real API key — should NOT be flagged as placeholder.
    #[test]
    fn real_openai_key_clean() {
        let key = b"sk-proj-abc123defghijklmnopqrstuvwxyz1234567890abcdef";
        let warnings = check_entropy("openai-key", key);
        let placeholder_warns: Vec<_> = warnings
            .iter()
            .filter(|w| w.id.as_str().starts_with("secret.entropy.placeholder."))
            .collect();
        assert!(
            placeholder_warns.is_empty(),
            "real API key flagged: {placeholder_warns:?}"
        );
    }

    /// URL with credentials — should have decent entropy.
    #[test]
    fn connection_string_not_flagged() {
        let url = b"postgres://user:R4nd0mP@ss!@db.prod.example.com:5432/mydb";
        let warnings = check_entropy("db-url", url);
        let placeholder_warns: Vec<_> = warnings
            .iter()
            .filter(|w| w.id.as_str().starts_with("secret.entropy.placeholder."))
            .collect();
        assert!(placeholder_warns.is_empty());
    }

    /// Binary data (e.g., a token) — should have high entropy.
    #[test]
    fn binary_data_high_entropy() {
        let data: Vec<u8> = (0..64).map(|i| (i * 37 + 19) as u8).collect();
        let e = shannon_entropy(&data);
        assert!(
            e > 4.0,
            "pseudo-random bytes should have decent entropy: {e}"
        );
    }
}

// ═══════════════════════════════════════════════════════════════
//  Guard Module — Environment Hardening
// ═══════════════════════════════════════════════════════════════

mod guard_hardening {
    //! Test environment sanitization and hostile env detection.

    use envseal::guard;

    /// sanitized_env removes known dangerous vars.
    #[test]
    fn sanitized_env_removes_ld_preload() {
        let clean = guard::sanitized_env();
        for k in clean.keys() {
            assert_ne!(k, "LD_PRELOAD", "sanitized_env must strip LD_PRELOAD");
            assert_ne!(
                k, "LD_LIBRARY_PATH",
                "sanitized_env must strip LD_LIBRARY_PATH"
            );
            assert_ne!(k, "DYLD_INSERT_LIBRARIES");
        }
    }

    /// sanitized_env preserves PATH and HOME.
    #[test]
    fn sanitized_env_preserves_essentials() {
        let clean = guard::sanitized_env();
        let keys: Vec<_> = clean.keys().map(|k| k.as_str()).collect();
        assert!(keys.contains(&"PATH"), "sanitized_env must preserve PATH");
        assert!(keys.contains(&"HOME"), "sanitized_env must preserve HOME");
    }

    /// hash_binary produces same hash for same file.
    #[test]
    fn hash_binary_deterministic() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(tmp.path(), b"test content").unwrap();

        let h1 = guard::hash_binary(tmp.path()).unwrap();
        let h2 = guard::hash_binary(tmp.path()).unwrap();
        assert_eq!(h1, h2, "same file must produce same hash");
    }

    /// hash_binary differs for different content.
    #[test]
    fn hash_binary_different_content() {
        let tmp1 = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(tmp1.path(), b"content-a").unwrap();

        let tmp2 = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(tmp2.path(), b"content-b").unwrap();

        let h1 = guard::hash_binary(tmp1.path()).unwrap();
        let h2 = guard::hash_binary(tmp2.path()).unwrap();
        assert_ne!(h1, h2, "different content must produce different hashes");
    }

    /// startup_audit shouldn't panic regardless of environment.
    #[test]
    fn startup_audit_no_panic() {
        let warnings = guard::startup_audit();
        // May have warnings (e.g., X11 vs Wayland), but shouldn't panic
        let _ = warnings;
    }
}

// ═══════════════════════════════════════════════════════════════
//  Concurrent Access Safety
// ═══════════════════════════════════════════════════════════════

mod concurrent_safety {
    //! Verify vault handles concurrent access safely.

    use crate::common::temp_vault;
    use std::sync::Arc;

    /// Concurrent reads don't corrupt data.
    #[test]
    fn concurrent_reads_safe() {
        let (_dir, vault) = temp_vault();
        vault.store("shared", b"shared-value", false).unwrap();

        let vault = Arc::new(vault);
        let mut handles = vec![];

        for _ in 0..10 {
            let v = Arc::clone(&vault);
            handles.push(std::thread::spawn(move || {
                for _ in 0..100 {
                    let dec = v.decrypt("shared").unwrap();
                    assert_eq!(&dec[..], b"shared-value");
                }
            }));
        }

        for h in handles {
            h.join().unwrap();
        }
    }

    /// Concurrent lists don't panic.
    #[test]
    fn concurrent_lists_safe() {
        let (_dir, vault) = temp_vault();
        for i in 0..10 {
            vault.store(&format!("key-{i}"), b"val", false).unwrap();
        }

        let vault = Arc::new(vault);
        let mut handles = vec![];

        for _ in 0..10 {
            let v = Arc::clone(&vault);
            handles.push(std::thread::spawn(move || {
                for _ in 0..50 {
                    let names = v.list().unwrap();
                    assert_eq!(names.len(), 10);
                }
            }));
        }

        for h in handles {
            h.join().unwrap();
        }
    }
}

// ═══════════════════════════════════════════════════════════════
//  TOTP Timing Attack Resistance
// ═══════════════════════════════════════════════════════════════

mod totp_security {
    //! Verify TOTP code verification isn't vulnerable to timing attacks.

    use envseal::totp;

    /// Verify rejects expired-format codes.
    #[test]
    fn rejects_non_numeric_codes() {
        let secret = totp::generate_secret();
        assert!(!totp::verify_code(&secret, "abcdef").unwrap());
        assert!(!totp::verify_code(&secret, "12345a").unwrap());
        assert!(!totp::verify_code(&secret, "!@#$%^").unwrap());
    }

    /// Verify accepts current valid code.
    #[test]
    fn accepts_current_valid_code() {
        let secret = totp::generate_secret();
        let code = totp::generate_code(&secret).unwrap();
        assert!(totp::verify_code(&secret, &code).unwrap());
    }

    /// Encrypt-decrypt TOTP secret roundtrip.
    #[test]
    fn totp_secret_encrypt_decrypt_roundtrip() {
        let secret = totp::generate_secret();
        let key = [0x42u8; 32];
        let encrypted = totp::encrypt_secret(&secret, &key).unwrap();
        let decrypted = totp::decrypt_secret(&encrypted, &key).unwrap();
        assert_eq!(*decrypted, secret);
    }

    /// Different encryption keys produce different ciphertext.
    #[test]
    fn different_keys_different_encrypted_secret() {
        let secret = totp::generate_secret();
        let ct1 = totp::encrypt_secret(&secret, &[1u8; 32]).unwrap();
        let ct2 = totp::encrypt_secret(&secret, &[2u8; 32]).unwrap();
        assert_ne!(ct1, ct2);
    }
}

// ═══════════════════════════════════════════════════════════════
//  File Permissions (Unix-only)
// ═══════════════════════════════════════════════════════════════

#[cfg(unix)]
mod file_permissions {
    //! Verify all vault files have restrictive permissions.

    use crate::common::temp_vault;
    use std::os::unix::fs::PermissionsExt;

    /// Sealed files must be owner-only (0600).
    #[test]
    fn sealed_files_are_0600() {
        let (dir, vault) = temp_vault();
        vault.store("perm-test", b"secret", false).unwrap();

        let seal_path = dir.path().join("vault").join("perm-test.seal");
        let meta = std::fs::metadata(&seal_path).unwrap();
        let mode = meta.permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "seal file should be 0600, got {mode:04o}");
    }

    /// Vault directory must be owner-only (0700).
    #[test]
    fn vault_dir_is_0700() {
        let (dir, vault) = temp_vault();
        vault.store("dir-test", b"x", false).unwrap();

        let vault_dir = dir.path().join("vault");
        let meta = std::fs::metadata(&vault_dir).unwrap();
        let mode = meta.permissions().mode() & 0o777;
        assert_eq!(mode, 0o700, "vault dir should be 0700, got {mode:04o}");
    }
}