airgap 0.1.4

Security for the modern age of AI: defend against bad AI agents and malicious npm packages
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
//! A directory-level passthrough FUSE overlay.
//!
//! The whole working directory is mounted through this filesystem, so every file
//! access — including files created *after* launch — is observed dynamically.
//! Ordinary files are proxied to the real filesystem; files that match a handler
//! (`.env` by name, private keys by content) are redacted on read and, for
//! `.env`, merged back on write.
//!
//! The backend reaches the real files through a captured dir fd to the working
//! directory (`root`, opened `O_PATH` before the mount shadowed the path) using
//! `*at` syscalls, so reads/writes of the real bytes never recurse back through
//! FUSE. Everything fails closed: a handler that can't redact/merge serves `EIO`
//! and never the raw bytes, and never corrupts the original.

use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use fuser::{
    BsdFileFlags, Errno, FileAttr, FileHandle, FileType, Filesystem, FopenFlags, Generation,
    INodeNo, InitFlags, KernelConfig, LockOwner, OpenFlags, RenameFlags, ReplyAttr, ReplyCreate,
    ReplyData, ReplyDirectory, ReplyEmpty, ReplyEntry, ReplyOpen, ReplyWrite, Request, TimeOrNow,
    WriteFlags,
};
use nix::dir::{Dir, Type};
use nix::fcntl::{AtFlags, OFlag, openat, readlinkat, renameat};
use nix::libc;
use nix::sys::stat::{FileStat, Mode, SFlag, fstatat, mkdirat};
use nix::sys::uio::{pread, pwrite};
use nix::unistd::{UnlinkatFlags, ftruncate, symlinkat, unlinkat};

use crate::redact::{self, HandlerKind};

/// How long the kernel may cache attributes/entries before asking again.
const TTL: Duration = Duration::from_secs(1);

/// The mount root inode.
const ROOT_INO: u64 = 1;

/// Map a `nix` errno to the `fuser` errno type used in replies.
fn errno(e: nix::errno::Errno) -> Errno {
    Errno::from_i32(e as i32)
}

/// The path to hand an `*at` call: the relative path, or `.` for the root itself
/// (an empty path would be `ENOENT`).
fn at(rel: &Path) -> &Path {
    if rel.as_os_str().is_empty() {
        Path::new(".")
    } else {
        rel
    }
}

/// What `read` should serve for a file, decided from its real contents.
enum View {
    /// Proxy the real file unchanged.
    Passthrough,
    /// A mergeable text secret (`.env` / `.npmrc`): serve these redacted bytes;
    /// writes are merged back through the matching handler.
    Redacted(HandlerKind, Vec<u8>),
    /// Private key: serve these redacted bytes; read-only.
    Key(Vec<u8>),
    /// A handler matched but failed to redact; fail closed (serve `EIO`).
    Failed,
}

/// State for one open file handle.
enum Handle {
    /// Passthrough: I/O goes straight to the real fd.
    File { fd: OwnedFd },
    /// A mergeable text secret (`.env` / `.npmrc`): serve `served`; child writes
    /// accumulate in `pending`, merged on flush/release back through `fd` onto
    /// the original via the handler selected by `kind`.
    Redacted {
        kind: HandlerKind,
        fd: OwnedFd,
        served: Vec<u8>,
        pending: Option<Vec<u8>>,
    },
    /// Private key: serve `served`; read-only.
    Key { served: Vec<u8> },
    /// Handler failed: every read fails closed with `EIO`.
    Failed,
}

/// Maps FUSE inodes to real paths (relative to `root`), assigned lazily.
struct InodeTable {
    by_ino: HashMap<u64, PathBuf>,
    by_path: HashMap<PathBuf, u64>,
    next: u64,
}

impl InodeTable {
    fn new() -> Self {
        let mut by_ino = HashMap::new();
        let mut by_path = HashMap::new();
        by_ino.insert(ROOT_INO, PathBuf::new());
        by_path.insert(PathBuf::new(), ROOT_INO);
        Self {
            by_ino,
            by_path,
            next: ROOT_INO + 1,
        }
    }

    fn intern(&mut self, path: PathBuf) -> u64 {
        if let Some(&ino) = self.by_path.get(&path) {
            return ino;
        }
        let ino = self.next;
        self.next += 1;
        self.by_ino.insert(ino, path.clone());
        self.by_path.insert(path, ino);
        ino
    }

    fn forget_path(&mut self, path: &Path) {
        if let Some(ino) = self.by_path.remove(path) {
            self.by_ino.remove(&ino);
        }
    }

    fn rename(&mut self, from: &Path, to: &Path) {
        if let Some(ino) = self.by_path.remove(from) {
            self.by_path.remove(to);
            self.by_ino.insert(ino, to.to_path_buf());
            self.by_path.insert(to.to_path_buf(), ino);
        }
    }
}

/// Allocates and stores open file handles.
struct Handles {
    next: u64,
    map: HashMap<u64, Handle>,
}

impl Handles {
    fn new() -> Self {
        Self {
            next: 1,
            map: HashMap::new(),
        }
    }

    fn insert(&mut self, handle: Handle) -> u64 {
        let id = self.next;
        self.next += 1;
        self.map.insert(id, handle);
        id
    }
}

/// What the wrapped program is trying to do to a file, passed to [`DirAccess`]
/// so a gate can tell the user exactly what triggered a prompt. Only file
/// operations are gated; directory listing is not.
#[derive(Clone, Copy, Debug)]
pub enum Access {
    /// Open a file for reading.
    Read,
    /// Open a file for writing.
    Write,
    /// Create a new file.
    Create,
}

/// A policy hook the overlay consults before letting the wrapped program access
/// a file. Implementations may block (e.g. to prompt the user). `path` is the
/// absolute path of the file being accessed; the implementation may grant at
/// coarser (directory) granularity. Used to gate package managers; AI agents run
/// with no gate.
pub trait DirAccess: Send + Sync {
    /// Return `true` to permit the access, `false` to deny it (the op returns
    /// `EACCES`).
    fn allow(&self, path: &Path, access: Access) -> bool;
}

/// The overlay filesystem.
pub struct OverlayFs {
    /// `O_PATH` dir fd to the real working directory, captured before the mount.
    root: OwnedFd,
    /// Absolute path of this overlay's mount root, used to form the absolute
    /// directory paths handed to the access `gate`.
    mount_root: PathBuf,
    /// Whether to redact secret files. When `false`, every file is passed
    /// through unchanged (the overlay is then transparent except for the gate).
    redact: bool,
    /// Optional directory-access gate (see [`DirAccess`]). `None` ⇒ unrestricted.
    gate: Option<Arc<dyn DirAccess>>,
    inodes: Mutex<InodeTable>,
    handles: Mutex<Handles>,
}

impl OverlayFs {
    pub fn new(
        root: OwnedFd,
        mount_root: PathBuf,
        redact: bool,
        gate: Option<Arc<dyn DirAccess>>,
    ) -> Self {
        Self {
            root,
            mount_root,
            redact,
            gate,
            inodes: Mutex::new(InodeTable::new()),
            handles: Mutex::new(Handles::new()),
        }
    }

    fn root_fd(&self) -> BorrowedFd<'_> {
        self.root.as_fd()
    }

    /// Whether the access gate permits `access` to `rel` (relative to the mount
    /// root). No gate ⇒ always allowed. The gate is consulted with the absolute
    /// path so decisions are consistent across multiple overlays.
    fn gate_allows(&self, rel: &Path, access: Access) -> bool {
        match &self.gate {
            Some(gate) => gate.allow(&self.mount_root.join(rel), access),
            None => true,
        }
    }

    fn path_of(&self, ino: INodeNo) -> Option<PathBuf> {
        self.inodes.lock().unwrap().by_ino.get(&ino.0).cloned()
    }

    fn intern(&self, path: PathBuf) -> u64 {
        self.inodes.lock().unwrap().intern(path)
    }

    fn open_real(&self, rel: &Path, oflag: OFlag, mode: Mode) -> nix::Result<OwnedFd> {
        openat(self.root_fd(), at(rel), oflag, mode)
    }

    fn stat(&self, rel: &Path) -> nix::Result<FileStat> {
        fstatat(self.root_fd(), at(rel), AtFlags::AT_SYMLINK_NOFOLLOW)
    }

    /// Decide the read view for a regular file from its real contents.
    fn view_for(&self, rel: &Path, file_name: &OsStr) -> nix::Result<View> {
        // Redaction disabled ⇒ never inspect contents; serve the real file.
        if !self.redact {
            return Ok(View::Passthrough);
        }
        let fd = self.open_real(rel, OFlag::O_RDONLY | OFlag::O_CLOEXEC, Mode::empty())?;
        let mut prefix = [0u8; 64];
        let n = pread(fd.as_fd(), &mut prefix, 0).unwrap_or(0);
        match redact::detect(file_name, &prefix[..n]) {
            None => Ok(View::Passthrough),
            Some(kind @ (HandlerKind::Env | HandlerKind::Npmrc)) => {
                let original = read_all(fd.as_fd())?;
                Ok(match redact::redact(kind, &original) {
                    Ok(bytes) => View::Redacted(kind, bytes),
                    Err(_) => View::Failed,
                })
            }
            Some(HandlerKind::PrivateKey) => {
                let original = read_all(fd.as_fd())?;
                Ok(match redact::redact_private_key(&original) {
                    Some(bytes) => View::Key(bytes),
                    None => View::Passthrough,
                })
            }
        }
    }

    /// Live attributes: real metadata, but with the size of regular files that
    /// have a handler overridden to the redacted (served) length.
    fn attr(&self, ino: u64, rel: &Path) -> nix::Result<FileAttr> {
        let st = self.stat(rel)?;
        let name = rel.file_name().unwrap_or_default();
        let ftype = SFlag::from_bits_truncate(st.st_mode) & SFlag::S_IFMT;

        // A symlink whose target is a secret must NOT be presented as a symlink:
        // the kernel would resolve it to the target — possibly outside this
        // overlay (e.g. `~/.npmrc -> /opt/dotfiles/.npmrc`) — and read it raw,
        // bypassing redaction entirely. So follow it ourselves (`view_for` opens
        // through the link) and, if it resolves to a secret, present a redacted
        // *regular file*: the kernel then issues FUSE read()/write() against this
        // node instead of chasing the link out of the mount. The policy is thus
        // applied to the link, not its target. Ordinary (non-secret) symlinks,
        // and links we can't resolve, are left as symlinks.
        if ftype == SFlag::S_IFLNK {
            let redacted_len = match self.view_for(rel, name) {
                Ok(View::Redacted(_, bytes)) | Ok(View::Key(bytes)) => Some(bytes.len()),
                Ok(View::Failed) => Some(0),
                Ok(View::Passthrough) | Err(_) => None,
            };
            if let Some(len) = redacted_len {
                // Base attrs on the target (its perms/owner/times), then override
                // kind and size for the redacted regular-file view.
                let target = fstatat(self.root_fd(), at(rel), AtFlags::empty())?;
                let mut attr = attr_from_stat(INodeNo(ino), &target);
                attr.kind = FileType::RegularFile;
                attr.size = len as u64;
                attr.blocks = attr.size.div_ceil(512);
                return Ok(attr);
            }
            return Ok(attr_from_stat(INodeNo(ino), &st));
        }

        let mut attr = attr_from_stat(INodeNo(ino), &st);
        if ftype == SFlag::S_IFREG {
            match self.view_for(rel, name)? {
                View::Passthrough => {}
                View::Redacted(_, bytes) | View::Key(bytes) => {
                    attr.size = bytes.len() as u64;
                    attr.blocks = attr.size.div_ceil(512);
                }
                View::Failed => {
                    attr.size = 0;
                    attr.blocks = 0;
                }
            }
        }
        Ok(attr)
    }

    /// Merge a redacted handle's pending writes back onto the original. Fails
    /// closed: a bad parse leaves the original untouched and drops the buffer.
    fn persist(&self, fh: u64) -> Result<(), Errno> {
        let mut handles = self.handles.lock().unwrap();
        let Some(Handle::Redacted { kind, fd, served, pending }) = handles.map.get_mut(&fh) else {
            return Ok(());
        };
        let kind = *kind;
        let Some(written) = pending.take() else {
            return Ok(());
        };
        let original = read_all(fd.as_fd()).map_err(errno)?;
        // Parse/merge BEFORE touching the original — never corrupt on error.
        let merged = redact::merge(kind, &original, &written).map_err(|_| Errno::EIO)?;
        let view = redact::redact(kind, &merged).map_err(|_| Errno::EIO)?;
        ftruncate(fd.as_fd(), 0).map_err(errno)?;
        write_all_at(fd.as_fd(), &merged).map_err(errno)?;
        *served = view;
        Ok(())
    }
}

/// Read an entire fd from offset 0 via `pread`, without disturbing its offset.
pub fn read_all(fd: BorrowedFd) -> nix::Result<Vec<u8>> {
    let mut out = Vec::new();
    let mut buf = [0u8; 8192];
    let mut offset = 0i64;
    loop {
        let n = pread(fd, &mut buf, offset)?;
        if n == 0 {
            break;
        }
        out.extend_from_slice(&buf[..n]);
        offset += n as i64;
    }
    Ok(out)
}

/// Write `data` to `fd` starting at offset 0 via `pwrite`.
fn write_all_at(fd: BorrowedFd, data: &[u8]) -> nix::Result<()> {
    let mut written = 0;
    while written < data.len() {
        let n = pwrite(fd, &data[written..], written as i64)?;
        if n == 0 {
            break;
        }
        written += n;
    }
    Ok(())
}

/// Build a `SystemTime` from a (seconds, nanoseconds) pair, as found in `stat`.
fn system_time(secs: i64, nsecs: i64) -> SystemTime {
    let nsecs = nsecs.clamp(0, 999_999_999) as u32;
    if secs >= 0 {
        UNIX_EPOCH + Duration::new(secs as u64, nsecs)
    } else {
        UNIX_EPOCH - Duration::new((-secs) as u64, 0) + Duration::new(0, nsecs)
    }
}

/// Translate a `stat` result into FUSE attributes, faithful to the real file
/// except for the inode number, which is the one we expose.
fn attr_from_stat(ino: INodeNo, st: &FileStat) -> FileAttr {
    let kind = match SFlag::from_bits_truncate(st.st_mode) & SFlag::S_IFMT {
        SFlag::S_IFDIR => FileType::Directory,
        SFlag::S_IFLNK => FileType::Symlink,
        SFlag::S_IFIFO => FileType::NamedPipe,
        SFlag::S_IFCHR => FileType::CharDevice,
        SFlag::S_IFBLK => FileType::BlockDevice,
        SFlag::S_IFSOCK => FileType::Socket,
        _ => FileType::RegularFile,
    };
    FileAttr {
        ino,
        size: st.st_size as u64,
        blocks: st.st_blocks as u64,
        atime: system_time(st.st_atime, st.st_atime_nsec),
        mtime: system_time(st.st_mtime, st.st_mtime_nsec),
        ctime: system_time(st.st_ctime, st.st_ctime_nsec),
        crtime: UNIX_EPOCH,
        kind,
        perm: (st.st_mode & 0o7777) as u16,
        nlink: st.st_nlink as u32,
        uid: st.st_uid,
        gid: st.st_gid,
        rdev: st.st_rdev as u32,
        blksize: st.st_blksize as u32,
        flags: 0,
    }
}

/// Map a `nix` directory entry type to a FUSE file type.
fn dir_type(t: Option<Type>) -> FileType {
    match t {
        Some(Type::Directory) => FileType::Directory,
        Some(Type::Symlink) => FileType::Symlink,
        Some(Type::Fifo) => FileType::NamedPipe,
        Some(Type::CharacterDevice) => FileType::CharDevice,
        Some(Type::BlockDevice) => FileType::BlockDevice,
        Some(Type::Socket) => FileType::Socket,
        _ => FileType::RegularFile,
    }
}

/// Open flags for proxying a passthrough open: same access mode, plus append /
/// truncate if requested. Never `O_CREAT` (that path is `create`).
fn passthrough_oflag(flags: OpenFlags) -> OFlag {
    let mut oflag = OFlag::O_CLOEXEC;
    match flags.0 & libc::O_ACCMODE {
        libc::O_WRONLY => oflag |= OFlag::O_WRONLY,
        libc::O_RDWR => oflag |= OFlag::O_RDWR,
        _ => oflag |= OFlag::O_RDONLY,
    }
    if flags.0 & libc::O_APPEND != 0 {
        oflag |= OFlag::O_APPEND;
    }
    if flags.0 & libc::O_TRUNC != 0 {
        oflag |= OFlag::O_TRUNC;
    }
    oflag
}

impl Filesystem for OverlayFs {
    fn init(&mut self, _req: &Request, config: &mut KernelConfig) -> std::io::Result<()> {
        // Ask the kernel to deliver `O_TRUNC` in `open` (so we reset the pending
        // redacted buffer there) rather than as a separate fh-less `setattr`.
        let _ = config.add_capabilities(InitFlags::FUSE_ATOMIC_O_TRUNC);
        Ok(())
    }

    fn lookup(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEntry) {
        let Some(parent_path) = self.path_of(parent) else {
            reply.error(Errno::ENOENT);
            return;
        };
        let rel = parent_path.join(name);
        match self.stat(&rel) {
            Ok(_) => {
                let ino = self.intern(rel.clone());
                match self.attr(ino, &rel) {
                    Ok(attr) => reply.entry(&TTL, &attr, Generation(0)),
                    Err(e) => reply.error(errno(e)),
                }
            }
            Err(e) => reply.error(errno(e)),
        }
    }

    fn getattr(&self, _req: &Request, ino: INodeNo, _fh: Option<FileHandle>, reply: ReplyAttr) {
        let Some(rel) = self.path_of(ino) else {
            reply.error(Errno::ENOENT);
            return;
        };
        match self.attr(ino.0, &rel) {
            Ok(attr) => reply.attr(&TTL, &attr),
            Err(e) => reply.error(errno(e)),
        }
    }

    fn setattr(
        &self,
        _req: &Request,
        ino: INodeNo,
        _mode: Option<u32>,
        _uid: Option<u32>,
        _gid: Option<u32>,
        size: Option<u64>,
        _atime: Option<TimeOrNow>,
        _mtime: Option<TimeOrNow>,
        _ctime: Option<SystemTime>,
        fh: Option<FileHandle>,
        _crtime: Option<SystemTime>,
        _chgtime: Option<SystemTime>,
        _bkuptime: Option<SystemTime>,
        _flags: Option<BsdFileFlags>,
        reply: ReplyAttr,
    ) {
        let Some(rel) = self.path_of(ino) else {
            reply.error(Errno::ENOENT);
            return;
        };
        // A truncate on an open redacted handle (e.g. `open(..., "w")`, delivered
        // as setattr(size) when atomic_o_trunc is off) resizes its pending
        // redacted view; the merge on flush reconciles it back to the original.
        if let (Some(sz), Some(fh)) = (size, fh) {
            let mut handles = self.handles.lock().unwrap();
            if let Some(Handle::Redacted { served, pending, .. }) = handles.map.get_mut(&fh.0) {
                pending.get_or_insert_with(|| served.clone()).resize(sz as usize, 0);
                drop(handles);
                match self.stat(&rel) {
                    Ok(st) => {
                        let mut attr = attr_from_stat(ino, &st);
                        attr.size = sz;
                        attr.blocks = sz.div_ceil(512);
                        reply.attr(&TTL, &attr);
                    }
                    Err(e) => reply.error(errno(e)),
                }
                return;
            }
        }
        // Truncation of a handler file is otherwise driven by open/write/flush; we
        // only act on the real file for passthrough, and refuse to truncate a
        // redacted key (which would mutate the original).
        if let Some(sz) = size {
            let name = rel.file_name().unwrap_or_default();
            match self.view_for(&rel, name) {
                Ok(View::Passthrough) => {
                    match self.open_real(&rel, OFlag::O_WRONLY | OFlag::O_CLOEXEC, Mode::empty()) {
                        Ok(fd) => {
                            if let Err(e) = ftruncate(fd.as_fd(), sz as i64) {
                                reply.error(errno(e));
                                return;
                            }
                        }
                        Err(e) => {
                            reply.error(errno(e));
                            return;
                        }
                    }
                }
                Ok(View::Redacted(..)) => {} // handled via the open handle's pending buffer
                Ok(View::Key(_)) => {
                    reply.error(Errno::EROFS);
                    return;
                }
                Ok(View::Failed) => {
                    reply.error(Errno::EIO);
                    return;
                }
                Err(e) => {
                    reply.error(errno(e));
                    return;
                }
            }
        }
        match self.attr(ino.0, &rel) {
            Ok(attr) => reply.attr(&TTL, &attr),
            Err(e) => reply.error(errno(e)),
        }
    }

    fn readlink(&self, _req: &Request, ino: INodeNo, reply: ReplyData) {
        let Some(rel) = self.path_of(ino) else {
            reply.error(Errno::ENOENT);
            return;
        };
        match readlinkat(self.root_fd(), at(&rel)) {
            Ok(target) => reply.data(target.as_bytes()),
            Err(e) => reply.error(errno(e)),
        }
    }

    fn open(&self, _req: &Request, ino: INodeNo, flags: OpenFlags, reply: ReplyOpen) {
        let Some(rel) = self.path_of(ino) else {
            reply.error(Errno::ENOENT);
            return;
        };
        // Opening a file is gated (on the directory that contains it); the
        // prompt distinguishes read from write.
        let access = if flags.0 & (libc::O_WRONLY | libc::O_RDWR) != 0 {
            Access::Write
        } else {
            Access::Read
        };
        if !self.gate_allows(&rel, access) {
            reply.error(Errno::EACCES);
            return;
        }
        let name = rel.file_name().unwrap_or_default().to_owned();
        let view = match self.view_for(&rel, &name) {
            Ok(v) => v,
            Err(e) => {
                reply.error(errno(e));
                return;
            }
        };
        let truncate = flags.0 & libc::O_TRUNC != 0;
        let handle = match view {
            View::Passthrough => {
                match self.open_real(&rel, passthrough_oflag(flags), Mode::empty()) {
                    Ok(fd) => Handle::File { fd },
                    Err(e) => {
                        reply.error(errno(e));
                        return;
                    }
                }
            }
            View::Redacted(kind, served) => {
                // Need read+write to merge the edited view back on flush.
                match self.open_real(&rel, OFlag::O_RDWR | OFlag::O_CLOEXEC, Mode::empty()) {
                    Ok(fd) => {
                        Handle::Redacted {
                            kind,
                            fd,
                            // O_TRUNC means the child replaces the whole file:
                            // start its pending buffer empty.
                            pending: truncate.then(Vec::new),
                            served,
                        }
                    }
                    Err(e) => {
                        reply.error(errno(e));
                        return;
                    }
                }
            }
            View::Key(served) => Handle::Key { served },
            View::Failed => Handle::Failed,
        };
        let fh = self.handles.lock().unwrap().insert(handle);
        reply.opened(FileHandle(fh), FopenFlags::empty());
    }

    fn create(
        &self,
        _req: &Request,
        parent: INodeNo,
        name: &OsStr,
        mode: u32,
        umask: u32,
        flags: i32,
        reply: ReplyCreate,
    ) {
        let Some(parent_path) = self.path_of(parent) else {
            reply.error(Errno::ENOENT);
            return;
        };
        // Creating a file is gated on the directory it would be created in.
        let rel = parent_path.join(name);
        if !self.gate_allows(&rel, Access::Create) {
            reply.error(Errno::EACCES);
            return;
        }
        let mut oflag = OFlag::O_CREAT | OFlag::O_RDWR | OFlag::O_CLOEXEC;
        if flags & libc::O_TRUNC != 0 {
            oflag |= OFlag::O_TRUNC;
        }
        let perm = Mode::from_bits_truncate((mode & !umask) & 0o7777);
        let fd = match self.open_real(&rel, oflag, perm) {
            Ok(fd) => fd,
            Err(e) => {
                reply.error(errno(e));
                return;
            }
        };
        let ino = self.intern(rel.clone());
        // A freshly created file is empty, so only by-name handlers (`.env`,
        // `.npmrc`) apply — a new key file has no header to sniff yet. Its
        // redacted view starts empty too. With redaction disabled it's a plain
        // passthrough.
        let kind = if self.redact {
            if redact::is_env_file(name) {
                Some(HandlerKind::Env)
            } else if redact::is_npmrc_file(name) {
                Some(HandlerKind::Npmrc)
            } else {
                None
            }
        } else {
            None
        };
        let handle = match kind {
            Some(kind) => Handle::Redacted {
                kind,
                fd,
                served: Vec::new(),
                pending: Some(Vec::new()),
            },
            None => Handle::File { fd },
        };
        let fh = self.handles.lock().unwrap().insert(handle);
        match self.attr(ino, &rel) {
            Ok(attr) => reply.created(&TTL, &attr, Generation(0), FileHandle(fh), FopenFlags::empty()),
            Err(e) => reply.error(errno(e)),
        }
    }

    fn read(
        &self,
        _req: &Request,
        _ino: INodeNo,
        fh: FileHandle,
        offset: u64,
        size: u32,
        _flags: OpenFlags,
        _lock_owner: Option<LockOwner>,
        reply: ReplyData,
    ) {
        let handles = self.handles.lock().unwrap();
        match handles.map.get(&fh.0) {
            Some(Handle::File { fd }) => {
                let mut buf = vec![0u8; size as usize];
                match pread(fd.as_fd(), &mut buf, offset as i64) {
                    Ok(n) => reply.data(&buf[..n]),
                    Err(e) => reply.error(errno(e)),
                }
            }
            Some(Handle::Redacted { served, pending, .. }) => {
                let bytes = pending.as_ref().unwrap_or(served);
                let start = (offset as usize).min(bytes.len());
                let end = start.saturating_add(size as usize).min(bytes.len());
                reply.data(&bytes[start..end]);
            }
            Some(Handle::Key { served }) => {
                let start = (offset as usize).min(served.len());
                let end = start.saturating_add(size as usize).min(served.len());
                reply.data(&served[start..end]);
            }
            Some(Handle::Failed) => reply.error(Errno::EIO),
            None => reply.error(Errno::EBADF),
        }
    }

    fn write(
        &self,
        _req: &Request,
        _ino: INodeNo,
        fh: FileHandle,
        offset: u64,
        data: &[u8],
        _write_flags: WriteFlags,
        _flags: OpenFlags,
        _lock_owner: Option<LockOwner>,
        reply: ReplyWrite,
    ) {
        let mut handles = self.handles.lock().unwrap();
        match handles.map.get_mut(&fh.0) {
            Some(Handle::File { fd }) => match pwrite(fd.as_fd(), data, offset as i64) {
                Ok(n) => reply.written(n as u32),
                Err(e) => reply.error(errno(e)),
            },
            // Accumulate into the pending (redacted) buffer; merged on flush.
            Some(Handle::Redacted { served, pending, .. }) => {
                let buf = pending.get_or_insert_with(|| served.clone());
                let end = offset as usize + data.len();
                if buf.len() < end {
                    buf.resize(end, 0);
                }
                buf[offset as usize..end].copy_from_slice(data);
                reply.written(data.len() as u32);
            }
            Some(Handle::Key { .. }) => reply.error(Errno::EROFS),
            Some(Handle::Failed) => reply.error(Errno::EIO),
            None => reply.error(Errno::EBADF),
        }
    }

    fn flush(
        &self,
        _req: &Request,
        _ino: INodeNo,
        fh: FileHandle,
        _lock_owner: LockOwner,
        reply: ReplyEmpty,
    ) {
        // Merge here so a parse failure surfaces as a failed close().
        match self.persist(fh.0) {
            Ok(()) => reply.ok(),
            Err(e) => reply.error(e),
        }
    }

    fn fsync(
        &self,
        _req: &Request,
        _ino: INodeNo,
        fh: FileHandle,
        _datasync: bool,
        reply: ReplyEmpty,
    ) {
        match self.persist(fh.0) {
            Ok(()) => reply.ok(),
            Err(e) => reply.error(e),
        }
    }

    fn release(
        &self,
        _req: &Request,
        _ino: INodeNo,
        fh: FileHandle,
        _flags: OpenFlags,
        _lock_owner: Option<LockOwner>,
        _flush: bool,
        reply: ReplyEmpty,
    ) {
        // Safety net for writers that skip flush; if flush already merged, the
        // pending buffer is empty and this is a no-op.
        let result = self.persist(fh.0);
        self.handles.lock().unwrap().map.remove(&fh.0);
        match result {
            Ok(()) => reply.ok(),
            Err(e) => reply.error(e),
        }
    }

    fn readdir(
        &self,
        _req: &Request,
        ino: INodeNo,
        _fh: FileHandle,
        offset: u64,
        mut reply: ReplyDirectory,
    ) {
        let Some(dir_rel) = self.path_of(ino) else {
            reply.error(Errno::ENOENT);
            return;
        };
        let mut dir = match Dir::openat(
            self.root_fd(),
            at(&dir_rel),
            OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC,
            Mode::empty(),
        ) {
            Ok(dir) => dir,
            Err(e) => {
                reply.error(errno(e));
                return;
            }
        };

        let mut entries: Vec<(u64, FileType, OsString)> = vec![
            (ino.0, FileType::Directory, OsString::from(".")),
            (ino.0, FileType::Directory, OsString::from("..")),
        ];
        for entry in dir.iter() {
            let Ok(entry) = entry else { continue };
            let raw = entry.file_name().to_bytes();
            if raw == b"." || raw == b".." {
                continue;
            }
            let name = OsStr::from_bytes(raw).to_owned();
            let child_ino = self.intern(dir_rel.join(&name));
            entries.push((child_ino, dir_type(entry.file_type()), name));
        }

        for (i, (entry_ino, kind, name)) in entries.iter().enumerate().skip(offset as usize) {
            if reply.add(INodeNo(*entry_ino), (i + 1) as u64, *kind, name) {
                break;
            }
        }
        reply.ok();
    }

    fn mkdir(
        &self,
        _req: &Request,
        parent: INodeNo,
        name: &OsStr,
        mode: u32,
        umask: u32,
        reply: ReplyEntry,
    ) {
        let Some(parent_path) = self.path_of(parent) else {
            reply.error(Errno::ENOENT);
            return;
        };
        let rel = parent_path.join(name);
        let perm = Mode::from_bits_truncate((mode & !umask) & 0o7777);
        match mkdirat(self.root_fd(), at(&rel), perm) {
            Ok(()) => {
                let ino = self.intern(rel.clone());
                match self.attr(ino, &rel) {
                    Ok(attr) => reply.entry(&TTL, &attr, Generation(0)),
                    Err(e) => reply.error(errno(e)),
                }
            }
            Err(e) => reply.error(errno(e)),
        }
    }

    fn unlink(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {
        let Some(parent_path) = self.path_of(parent) else {
            reply.error(Errno::ENOENT);
            return;
        };
        let rel = parent_path.join(name);
        match unlinkat(self.root_fd(), at(&rel), UnlinkatFlags::NoRemoveDir) {
            Ok(()) => {
                self.inodes.lock().unwrap().forget_path(&rel);
                reply.ok();
            }
            Err(e) => reply.error(errno(e)),
        }
    }

    fn rmdir(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {
        let Some(parent_path) = self.path_of(parent) else {
            reply.error(Errno::ENOENT);
            return;
        };
        let rel = parent_path.join(name);
        match unlinkat(self.root_fd(), at(&rel), UnlinkatFlags::RemoveDir) {
            Ok(()) => {
                self.inodes.lock().unwrap().forget_path(&rel);
                reply.ok();
            }
            Err(e) => reply.error(errno(e)),
        }
    }

    fn rename(
        &self,
        _req: &Request,
        parent: INodeNo,
        name: &OsStr,
        newparent: INodeNo,
        newname: &OsStr,
        _flags: RenameFlags,
        reply: ReplyEmpty,
    ) {
        let (Some(parent_path), Some(newparent_path)) =
            (self.path_of(parent), self.path_of(newparent))
        else {
            reply.error(Errno::ENOENT);
            return;
        };
        let from = parent_path.join(name);
        let to = newparent_path.join(newname);
        match renameat(self.root_fd(), at(&from), self.root_fd(), at(&to)) {
            Ok(()) => {
                self.inodes.lock().unwrap().rename(&from, &to);
                reply.ok();
            }
            Err(e) => reply.error(errno(e)),
        }
    }

    fn symlink(
        &self,
        _req: &Request,
        parent: INodeNo,
        link_name: &OsStr,
        target: &Path,
        reply: ReplyEntry,
    ) {
        let Some(parent_path) = self.path_of(parent) else {
            reply.error(Errno::ENOENT);
            return;
        };
        let rel = parent_path.join(link_name);
        match symlinkat(target, self.root_fd(), at(&rel)) {
            Ok(()) => {
                let ino = self.intern(rel.clone());
                match self.attr(ino, &rel) {
                    Ok(attr) => reply.entry(&TTL, &attr, Generation(0)),
                    Err(e) => reply.error(errno(e)),
                }
            }
            Err(e) => reply.error(errno(e)),
        }
    }
}