envseal 0.3.13

Write-only secret vault with process-level access control — post-agent secret management
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
//! On-disk persistence for [`SecurityConfig`].
//!
//! Canonical layout in 0.3.0+: `<root>/security.sealed` —
//! AES-256-GCM authenticated encryption with an HKDF-derived
//! per-domain key (`b"security_config.v1"`) off the master key.
//! AEAD provides integrity AND confidentiality; an attacker who
//! reads the file learns nothing about which tier you're on, what
//! relay endpoint you've paired with, or which signal IDs you've
//! overridden.
//!
//! Back-compat read path honors the v0.2.x plaintext-with-HMAC
//! layout (`<root>/security.toml` + `# hmac = "..."` comment); the
//! next save migrates by writing `security.sealed` and deleting the
//! plaintext.
//!
//! `/etc/envseal/system.toml` (enterprise-wide override channel)
//! stays plaintext — it's owned by root, not the user, and covers
//! force-lockdown / fleet-management knobs that are themselves
//! public policy.

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

use super::tiers::{SecurityConfig, SecurityTier};
use crate::error::Error;
use crate::hex;
use crate::vault::sealed_blob;

/// Domain string for the security config sealed blob. Must not
/// collide with any other `sealed_blob::seal` consumer.
const SECURITY_CONFIG_DOMAIN: &[u8] = b"security_config.v1";

/// Legacy plaintext path within a vault root. Read-only on the
/// migration path; writes always target [`security_config_sealed_path`].
#[must_use]
pub fn security_config_path(root: &Path) -> PathBuf {
    root.join("security.toml")
}

/// Canonical sealed-blob path within a vault root.
#[must_use]
pub fn security_config_sealed_path(root: &Path) -> PathBuf {
    root.join("security.sealed")
}

/// Tripwire path within a vault root. C1 (audit, May 2026): if a
/// same-UID attacker deletes `security.sealed`, the next vault open
/// silently fell back to `SecurityConfig::default()` which has
/// `totp_required = false`. The tripwire is an HMAC-SHA256 of the
/// canonical config bytes, signed with a key derived from the
/// master key (which is hardware-sealed and never leaves the
/// device). Asymmetry: an attacker who deletes `security.sealed`
/// CAN also delete the tripwire, but they cannot forge a fresh
/// tripwire that matches a downgraded config without the master
/// key. Combined with the `load_config` contract below ("tripwire
/// present + sealed absent ⇒ refuse"), this turns a silent
/// downgrade into a loud refusal that audits the tamper.
#[must_use]
pub fn security_config_tripwire_path(root: &Path) -> PathBuf {
    root.join("security.tripwire")
}

/// Compute the C1 tripwire HMAC over the canonical sealed-config
/// bytes. The HMAC key is derived from the master key via HKDF
/// with a domain string distinct from every other derivation, so a
/// leaked tripwire reveals nothing about the master key or any
/// other derived key.
fn compute_security_tripwire(
    master_key: &[u8; 32],
    sealed_bytes: &[u8],
) -> Result<[u8; 32], Error> {
    use hkdf::Hkdf;
    use hmac::{Hmac, Mac};
    use sha2::Sha256;
    type HmacSha256 = Hmac<Sha256>;
    let hk = Hkdf::<Sha256>::new(Some(b"envseal-security-tripwire-v1"), master_key);
    let mut hmac_key = zeroize::Zeroizing::new([0u8; 32]);
    hk.expand(b"envseal-security-tripwire", hmac_key.as_mut())
        .map_err(|_| Error::CryptoFailure("HKDF expand for tripwire failed".to_string()))?;
    let mut mac = HmacSha256::new_from_slice(hmac_key.as_ref())
        .map_err(|e| Error::CryptoFailure(format!("HMAC init for tripwire failed: {e}")))?;
    mac.update(sealed_bytes);
    let tag = mac.finalize().into_bytes();
    let mut out = [0u8; 32];
    out.copy_from_slice(&tag);
    Ok(out)
}

/// Load the system defaults for the vault.
///
/// Returns a baseline configuration upgraded by `/etc/envseal/system.toml` if it exists.
#[must_use]
pub fn load_system_defaults() -> SecurityConfig {
    let mut config = SecurityConfig::default();
    let _ = apply_system_overrides(&mut config, None);
    config
}

/// Load the security config from disk, or return default if not found.
///
/// The config file is HMAC-signed. If the signature is invalid,
/// returns `PolicyTampered` to prevent an attacker from modifying
/// the security config to downgrade protections.
pub fn load_config(root: &Path, master_key: &[u8; 32]) -> Result<SecurityConfig, Error> {
    // Audit L11: cap the sealed-config read at 10 MiB. The actual
    // serialized config is on the order of hundreds of bytes; 10
    // MiB is a 100,000x safety margin and stops a /dev/zero
    // substitution from making envseal allocate unbounded memory.
    const MAX_SEALED_CONFIG_BYTES: u64 = 10 * 1024 * 1024;

    let lock_path = root.join("security.lock");
    crate::guard::verify_not_symlink(&lock_path)?;
    let _lock = advisory_lock::acquire(&lock_path, false)?;
    let mut config = load_system_defaults();

    // C1 (audit, May 2026): enforce the tripwire BEFORE we
    // fall back to defaults. If a previous save_config wrote a
    // tripwire and someone deleted `security.sealed`, refuse the
    // load and audit-log the tamper. The tripwire itself is signed
    // with a key derived from `master_key`, so an attacker who
    // can't unseal master.key can't forge a matching tripwire for
    // a weaker config.
    let tripwire_path = security_config_tripwire_path(root);
    let sealed_path = security_config_sealed_path(root);
    crate::guard::verify_not_symlink(&tripwire_path)?;
    let tripwire_present = tripwire_path.exists();
    let sealed_present = sealed_path.exists();
    if tripwire_present && !sealed_present {
        let _ = crate::audit::log_required_at(
            root,
            &crate::audit::AuditEvent::SignalRecorded {
                tier: "Lockdown".to_string(),
                classification: "critical [security.tripwire.deleted_sealed] \
                    security.tripwire present but security.sealed missing — \
                    deletion attack against the security config detected"
                    .to_string(),
            },
        );
        return Err(Error::PolicyTampered(format!(
            "security.tripwire is present at {} but security.sealed is missing. \
             Someone deleted the security config; envseal refuses to fall back \
             to defaults (which would silently disable TOTP / relay / lockdown \
             tier). Restore security.sealed from backup, or run \
             `envseal security reset` if you intentionally want to start over.",
            tripwire_path.display()
        )));
    }

    // Try the canonical sealed file first.
    if sealed_path.exists() {
        crate::guard::verify_not_symlink(&sealed_path)?;
        let meta = std::fs::metadata(&sealed_path)?;
        if meta.len() > MAX_SEALED_CONFIG_BYTES {
            return Err(Error::PolicyTampered(format!(
                "security.sealed at {} is {} bytes (limit {MAX_SEALED_CONFIG_BYTES}); \
                 refusing to read — a real config is on the order of 1 KiB.",
                sealed_path.display(),
                meta.len(),
            )));
        }
        let blob = std::fs::read(&sealed_path)?;
        // C1: verify the tripwire matches the on-disk sealed bytes
        // BEFORE we attempt to decrypt. An attacker who replaced
        // sealed with a stale (weaker) version they previously
        // captured would otherwise pass the AEAD check (it's still
        // sealed under master_key) but fail this match.
        if tripwire_present {
            let expected = compute_security_tripwire(master_key, &blob)?;
            let on_disk = std::fs::read(&tripwire_path)?;
            if on_disk.len() != expected.len()
                || !crate::guard::constant_time_eq(&on_disk, &expected)
            {
                let _ = crate::audit::log_required_at(
                    root,
                    &crate::audit::AuditEvent::SignalRecorded {
                        tier: "Lockdown".to_string(),
                        classification: "critical [security.tripwire.mismatch] \
                            tripwire HMAC does not match on-disk security.sealed \
                            — replay or partial-write tamper detected"
                            .to_string(),
                    },
                );
                return Err(Error::PolicyTampered(
                    "security.tripwire HMAC does not match security.sealed; \
                     a stale sealed file was substituted (replay attack) or a \
                     write was interrupted. Restore from backup or run \
                     `envseal security reset`."
                        .to_string(),
                ));
            }
        }
        let plaintext = sealed_blob::unseal(&blob, master_key, SECURITY_CONFIG_DOMAIN)?;
        let body = std::str::from_utf8(&plaintext)
            .map_err(|e| Error::PolicyTampered(format!("security.sealed not utf-8: {e}")))?;
        config = toml::from_str(body)
            .map_err(|e| Error::PolicyTampered(format!("security.sealed parse failed: {e}")))?;
    } else {
        // v0.2.x back-compat: plaintext security.toml + HMAC
        // comment. The next save_config call will migrate by
        // writing security.sealed and deleting this file.
        let path = security_config_path(root);
        crate::guard::verify_not_symlink(&path)?;
        if path.exists() {
            // Cap the legacy plaintext config read at 1 MiB. Real
            // security.toml is < 4 KiB; the cap stops a hostile
            // substitution from forcing the whole file into RAM
            // before HMAC verification has a chance to refuse.
            use std::io::Read;
            let f = std::fs::File::open(&path)?;
            let mut content = String::new();
            f.take(1024 * 1024).read_to_string(&mut content)?;
            let (body, expected_hmac) = split_signed_content(&content)?;
            let computed = compute_hmac(master_key, body.as_bytes())?;
            if !crate::guard::constant_time_eq(computed.as_bytes(), expected_hmac.as_bytes()) {
                return Err(Error::PolicyTampered(
                    "security.toml HMAC mismatch (tamper detected)".to_string(),
                ));
            }
            config = toml::from_str(body)
                .map_err(|e| Error::PolicyTampered(format!("security.toml parse failed: {e}")))?;
        }
    }

    // SECURITY: If the loaded config is weaker than the system's
    // default (e.g., files were deleted by an attacker), the
    // enterprise override replay below will re-apply force_lockdown.
    // We also clamp tier so it can never silently drop below
    // Standard without explicit user action.
    if config.tier < SecurityTier::Standard {
        config.tier = SecurityTier::Standard;
    }

    // Replay enterprise-level System Configuration overrides to ensure
    // they supersede the user's local security config.
    // This is the defense against Catch-22 UI Configuration Splitting.
    apply_system_overrides(&mut config, Some(master_key))?;

    Ok(config)
}

/// Persist the security config to disk as an AES-256-GCM sealed
/// blob at `<root>/security.sealed`. AEAD covers both integrity
/// (replaces HMAC) and confidentiality (defeats the v0.2.x leak
/// where reading the file revealed your tier / relay endpoint /
/// signal overrides).
///
/// Migration: if a legacy `security.toml` exists, it is removed
/// AFTER the sealed write succeeds.
pub fn save_config(
    root: &Path,
    config: &SecurityConfig,
    master_key: &[u8; 32],
) -> Result<(), Error> {
    let lock_path = root.join("security.lock");
    crate::guard::verify_not_symlink(&lock_path)?;
    let _lock = advisory_lock::acquire(&lock_path, true)?;
    let body = toml::to_string_pretty(config)
        .map_err(|e| Error::CryptoFailure(format!("failed to serialize security config: {e}")))?;
    let blob = sealed_blob::seal(body.as_bytes(), master_key, SECURITY_CONFIG_DOMAIN)?;

    let sealed_path = security_config_sealed_path(root);
    // Atomic write: temp file + rename so crashes or concurrent
    // writers never leave a truncated config on disk.
    let rnd = rand::random::<u64>();
    let tmp_path = sealed_path.with_extension(format!("sealed.{rnd:016x}.tmp"));
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let mut f = std::fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .mode(0o600)
            .open(&tmp_path)
            .map_err(Error::StorageIo)?;
        f.write_all(&blob).map_err(Error::StorageIo)?;
        f.sync_all().map_err(Error::StorageIo)?;
    }
    #[cfg(windows)]
    {
        // Audit M18: Windows had used `std::fs::write`, which
        // creates the file with whatever ACL the parent directory
        // hands down. On a multi-user box that could leave the
        // sealed config readable by other accounts during the
        // brief window before the rename. We now open with
        // `create_new(true)` (refuses any pre-existing file) and
        // write through that handle, then set an owner-only DACL
        // before the rename.
        use std::io::Write;
        let mut f = std::fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(&tmp_path)
            .map_err(Error::StorageIo)?;
        f.write_all(&blob).map_err(Error::StorageIo)?;
        f.sync_all().map_err(Error::StorageIo)?;
        crate::policy::windows_acl::set_owner_only_dacl(&tmp_path)?;
    }
    #[cfg(not(any(unix, windows)))]
    {
        use std::io::Write;
        let mut f = std::fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(&tmp_path)
            .map_err(Error::StorageIo)?;
        f.write_all(&blob).map_err(Error::StorageIo)?;
        f.sync_all().map_err(Error::StorageIo)?;
    }

    std::fs::rename(&tmp_path, &sealed_path)?;

    // C1: write the tripwire HMAC over the sealed bytes we just
    // committed. load_config will refuse to fall back to defaults
    // if this file later disappears (deletion attack) or fails to
    // verify (replay / partial-write attack). Done AFTER the
    // sealed rename so a crash between the two leaves a sealed
    // file with no tripwire — the next save migrates by writing
    // both, the next load accepts the sealed because tripwire is
    // absent (legacy / mid-migration semantics).
    let tripwire_path = security_config_tripwire_path(root);
    let tripwire_tmp = tripwire_path.with_extension(format!("tripwire.{rnd:016x}.tmp"));
    let tripwire = compute_security_tripwire(master_key, &blob)?;
    {
        use std::io::Write;
        let mut opts = std::fs::OpenOptions::new();
        opts.create_new(true).write(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
        }
        let mut f = opts.open(&tripwire_tmp).map_err(Error::StorageIo)?;
        f.write_all(&tripwire).map_err(Error::StorageIo)?;
        f.sync_all().map_err(Error::StorageIo)?;
    }
    #[cfg(windows)]
    {
        crate::policy::windows_acl::set_owner_only_dacl(&tripwire_tmp)?;
    }
    if let Err(e) = std::fs::rename(&tripwire_tmp, &tripwire_path) {
        let _ = std::fs::remove_file(&tripwire_tmp);
        return Err(Error::StorageIo(e));
    }

    // Migration: drop the legacy plaintext now that the sealed file
    // is durably on disk. Best-effort — a permission failure here
    // doesn't lose data because the sealed file is canonical.
    let legacy_path = security_config_path(root);
    if legacy_path.exists() {
        let _ = std::fs::remove_file(&legacy_path);
    }

    Ok(())
}

/// Subset of `/etc/envseal/system.toml` we honor. Adding a field
/// here is the entire diff for a new enterprise override.
#[derive(Deserialize)]
struct SysOverride {
    force_lockdown: Option<bool>,
    custom_ui_cmd: Option<String>,
}

/// Apply the enterprise system overrides (`/etc/envseal/system.toml`)
/// onto an existing [`SecurityConfig`]. Used by both initial load and
/// the post-user-config replay so deployment-level decisions can't be
/// silently undone by a per-vault `security.toml`.
fn apply_system_overrides(
    config: &mut SecurityConfig,
    master_key: Option<&[u8; 32]>,
) -> Result<(), Error> {
    use std::io::Read;
    let sys_path = Path::new("/etc/envseal/system.toml");
    if !sys_path.exists() {
        return Ok(());
    }
    if crate::guard::verify_not_symlink(sys_path).is_err() {
        return Ok(());
    }
    // Audit L13: refuse to honor /etc/envseal/system.toml unless it
    // is owned by root (uid 0) and not group/world writable. This
    // is a *system-wide enterprise override* — its whole purpose is
    // to be authoritative over per-user config. If a non-privileged
    // user can modify it, the privilege gradient is inverted.
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        let Ok(meta) = std::fs::metadata(sys_path) else {
            return Ok(());
        };
        if meta.uid() != 0 {
            // Not root-owned. Treat as missing.
            return Ok(());
        }
        // 0o022 = group-write or world-write. Either makes the file
        // forgeable by a non-root local user, defeating the override.
        if meta.mode() & 0o022 != 0 {
            return Ok(());
        }
    }
    // System override file: 1 MiB cap (real file < 4 KiB). Defense
    // against a hostile sysadmin replacing /etc/envseal/system.toml
    // with /dev/zero before envseal reads it.
    let Ok(content) = (|| -> std::io::Result<String> {
        let f = std::fs::File::open(sys_path)?;
        let mut s = String::new();
        f.take(1024 * 1024).read_to_string(&mut s)?;
        Ok(s)
    })() else {
        return Ok(());
    };

    // Integrity verification for system overrides (Audit L13).
    let sig_path = Path::new("/etc/envseal/system.toml.sig");
    if sig_path.exists() {
        if let Some(key) = master_key {
            // Signature is a single hex line — 64 KiB cap is paranoid.
            let sig = (|| -> std::io::Result<String> {
                let f = std::fs::File::open(sig_path)?;
                let mut s = String::new();
                f.take(64 * 1024).read_to_string(&mut s)?;
                Ok(s)
            })()
            .map_err(Error::StorageIo)?;
            let sig = sig.trim();
            let computed = compute_hmac(key, content.as_bytes())?;
            if !crate::guard::constant_time_eq(computed.as_bytes(), sig.as_bytes()) {
                return Err(Error::PolicyTampered(
                    "system.toml HMAC mismatch (tamper detected)".to_string(),
                ));
            }
        } else {
            // Signature exists but no key available to verify — reject.
            return Err(Error::PolicyTampered(
                "system.toml.sig exists but no master key available for verification".to_string(),
            ));
        }
    } else {
        eprintln!(
            "envseal: warning: /etc/envseal/system.toml has no .sig file; \
             integrity verification is recommended"
        );
    }

    let Ok(sys_overrides) = toml::from_str::<SysOverride>(&content) else {
        return Ok(());
    };

    if sys_overrides.force_lockdown == Some(true) {
        config.apply_preset(SecurityTier::Lockdown);
    }
    if sys_overrides.custom_ui_cmd.is_some() {
        config.custom_ui_cmd = sys_overrides.custom_ui_cmd;
    }

    Ok(())
}

/// Compute HMAC-SHA256 for content signing.
fn compute_hmac(key: &[u8; 32], data: &[u8]) -> Result<String, Error> {
    use hmac::{Hmac, Mac};
    use sha2::Sha256;

    type HmacSha256 = Hmac<Sha256>;

    let hmac_key = crate::keychain::derive_hmac_key(key)?;
    let mut mac = HmacSha256::new_from_slice(hmac_key.as_ref())
        .map_err(|e| Error::CryptoFailure(format!("HMAC init failed (unexpected): {e}")))?;
    mac.update(data);
    let result = mac.finalize();
    Ok(hex::encode(result.into_bytes()))
}

/// Split signed content into body and HMAC.
fn split_signed_content(content: &str) -> Result<(&str, &str), Error> {
    // HMAC is on the last line: # hmac = "..."
    if let Some(pos) = content.rfind("\n# hmac = \"") {
        let body = &content[..pos];
        let hmac_line = &content[pos..];

        // Extract the hex string between quotes
        if let Some(start) = hmac_line.find('"') {
            if let Some(end) = hmac_line.rfind('"') {
                if start < end {
                    return Ok((body, &hmac_line[start + 1..end]));
                }
            }
        }
    }

    Err(Error::PolicyTampered(
        "security.toml missing HMAC signature".to_string(),
    ))
}

/// Advisory file-locking helper — prevents lost-update races when
/// multiple envseal processes read-modify-write the security config
/// concurrently. Uses `flock` on Unix and `LockFile` on Windows.
///
/// Audit M19: also reused by `execution::context::prepare_execution`
/// for the policy.toml read-modify-save sequence, which had the
/// same lost-update problem.
pub(crate) mod advisory_lock {
    use crate::error::Error;
    use std::fs::File;
    use std::path::Path;

    pub fn acquire(path: &Path, exclusive: bool) -> Result<LockGuard, Error> {
        let mut opts = File::options();
        opts.create(true).truncate(false).read(true).write(true);

        // Defense in depth: refuse FILE_SHARE_DELETE on Windows so
        // an attacker who can write to the parent dir can't delete
        // the lock file out from under us mid-operation, which would
        // sever the synchronization between concurrent writers
        // without anyone noticing. We still allow FILE_SHARE_READ +
        // FILE_SHARE_WRITE because the cross-process protocol is to
        // *open* the lock file from each process and then call
        // LockFileEx — peer opens must succeed for the lock to be
        // contestable in the first place.
        #[cfg(windows)]
        {
            use std::os::windows::fs::OpenOptionsExt;
            use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE};
            opts.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
        }

        let file = opts.open(path).map_err(Error::StorageIo)?;

        #[cfg(unix)]
        {
            use std::os::unix::io::AsRawFd;
            let op = if exclusive {
                libc::LOCK_EX
            } else {
                libc::LOCK_SH
            };
            let rc = unsafe { libc::flock(file.as_raw_fd(), op) };
            if rc != 0 {
                return Err(Error::StorageIo(std::io::Error::last_os_error()));
            }
        }

        #[cfg(windows)]
        {
            use std::os::windows::io::AsRawHandle;
            use windows_sys::Win32::Storage::FileSystem::{LockFileEx, LOCKFILE_EXCLUSIVE_LOCK};
            // LockFileEx with no LOCKFILE_FAIL_IMMEDIATELY flag is
            // *blocking*: the call waits until the requested range
            // is granted, matching Unix `flock` semantics. The
            // older `LockFile` API returned ERROR_LOCK_VIOLATION
            // immediately on contention, which broke the audit
            // log's append serialization the moment two threads
            // raced — a real bug, not just a test artifact.
            let flags = if exclusive {
                LOCKFILE_EXCLUSIVE_LOCK
            } else {
                0
            };
            unsafe {
                let handle = file.as_raw_handle();
                let mut overlapped: windows_sys::Win32::System::IO::OVERLAPPED = std::mem::zeroed();
                if LockFileEx(handle, flags, 0, 0xFFFF_FFFF, 0xFFFF_FFFF, &mut overlapped) == 0 {
                    return Err(Error::StorageIo(std::io::Error::last_os_error()));
                }
            }
        }

        #[cfg(not(any(unix, windows)))]
        {
            let _ = exclusive;
        }

        Ok(LockGuard(file))
    }

    pub struct LockGuard(File);

    impl Drop for LockGuard {
        fn drop(&mut self) {
            #[cfg(unix)]
            {
                use std::os::unix::io::AsRawFd;
                unsafe {
                    libc::flock(self.0.as_raw_fd(), libc::LOCK_UN);
                }
            }

            #[cfg(windows)]
            {
                use std::os::windows::io::AsRawHandle;
                use windows_sys::Win32::Storage::FileSystem::UnlockFile;
                unsafe {
                    let handle = self.0.as_raw_handle();
                    UnlockFile(handle, 0, 0, 0xFFFF_FFFF, 0xFFFF_FFFF);
                }
            }
        }
    }
}