rdsh 0.12.0

Rust port/shim for dsh: fast launcher, token saver, zero behavior breakage via passthrough
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
//! Read repository files through no-follow, directory-relative handles.
//! Callers pass an absolute, canonical root and target; unavailable hosts fail closed.
//!
//! Unix closes the check/open race: every component is opened with
//! `openat`/`O_NOFOLLOW` under a held directory fd. Windows opens the target
//! without following a final reparse point, then checks the opened handle's
//! final path and hard-link count before returning it. Hosts without a secure
//! handle path fail closed.
use std::path::Path;
#[cfg(any(unix, windows))]
use std::path::PathBuf;

/// A command-scoped capability for the directory selected by the caller.
/// Keep its identity stable instead of reopening every ancestor for every file.
pub(crate) struct Root {
    #[cfg(unix)]
    path: PathBuf,
    #[cfg(unix)]
    directory: std::fs::File,
    #[cfg(target_os = "macos")]
    nofollow_any: bool,
    #[cfg(windows)]
    path: PathBuf,
}

impl Root {
    #[cfg(unix)]
    pub(crate) fn new(root: &Path) -> Option<Self> {
        use std::ffi::CString;
        use std::os::fd::{AsRawFd, FromRawFd};
        use std::os::unix::ffi::OsStrExt;

        if !root.is_absolute() {
            return None;
        }
        let name = CString::new(b"/".as_slice()).ok()?;
        let flags = libc::O_RDONLY | libc::O_CLOEXEC | libc::O_DIRECTORY | libc::O_NOFOLLOW;
        let fd = unsafe { libc::open(name.as_ptr(), flags) };
        if fd < 0 {
            return None;
        }
        let mut directory = unsafe { std::fs::File::from_raw_fd(fd) };
        for component in root.components() {
            let name = match component {
                std::path::Component::RootDir | std::path::Component::CurDir => continue,
                std::path::Component::Normal(name) => CString::new(name.as_bytes()).ok()?,
                _ => return None,
            };
            let fd = unsafe { libc::openat(directory.as_raw_fd(), name.as_ptr(), flags) };
            if fd < 0 {
                return None;
            }
            directory = unsafe { std::fs::File::from_raw_fd(fd) };
        }
        Some(Self {
            path: root.to_path_buf(),
            directory,
            #[cfg(target_os = "macos")]
            nofollow_any: macos_nofollow_any_supported(),
        })
    }

    #[cfg(windows)]
    pub(crate) fn new(root: &Path) -> Option<Self> {
        let path = std::fs::canonicalize(root).ok()?;
        path.is_dir().then_some(Self { path })
    }

    #[cfg(not(any(unix, windows)))]
    pub(crate) fn new(_root: &Path) -> Option<Self> {
        None
    }

    #[cfg(unix)]
    pub(crate) fn open(&self, target: &Path) -> Option<std::fs::File> {
        let relative = target.strip_prefix(&self.path).ok()?;
        if relative.as_os_str().is_empty() {
            return None;
        }
        #[cfg(target_os = "macos")]
        if self.nofollow_any {
            match self.open_macos_nofollow_any(relative) {
                Ok(file) => return file,
                Err(error)
                    if error
                        .raw_os_error()
                        .is_some_and(macos_nofollow_any_falls_back) => {}
                Err(_) => return None,
            }
        }
        self.open_component_walk(relative)
    }

    #[cfg(unix)]
    fn open_component_walk(&self, relative: &Path) -> Option<std::fs::File> {
        use std::ffi::CString;
        use std::os::fd::{AsRawFd, FromRawFd};
        use std::os::unix::ffi::OsStrExt;
        use std::os::unix::fs::MetadataExt;

        let mut components = relative.components().peekable();
        let mut current: Option<std::fs::File> = None;
        while let Some(component) = components.next() {
            let name = match component {
                std::path::Component::Normal(name) => CString::new(name.as_bytes()).ok()?,
                _ => return None,
            };
            let flags = libc::O_RDONLY
                | libc::O_CLOEXEC
                | libc::O_NOFOLLOW
                | if components.peek().is_none() {
                    libc::O_NONBLOCK
                } else {
                    libc::O_DIRECTORY
                };
            let parent = current.as_ref().unwrap_or(&self.directory);
            let fd = unsafe { libc::openat(parent.as_raw_fd(), name.as_ptr(), flags) };
            if fd < 0 {
                return None;
            }
            current = Some(unsafe { std::fs::File::from_raw_fd(fd) });
        }
        let file = current?;
        let metadata = file.metadata().ok()?;
        (metadata.is_file() && metadata.nlink() == 1).then_some(file)
    }

    #[cfg(target_os = "macos")]
    fn open_macos_nofollow_any(
        &self,
        relative: &Path,
    ) -> Result<Option<std::fs::File>, std::io::Error> {
        use std::ffi::CString;
        use std::os::fd::{AsRawFd, FromRawFd};
        use std::os::unix::ffi::OsStrExt;
        use std::os::unix::fs::MetadataExt;

        if macos_nofollow_any_must_walk(relative) {
            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
        }
        if !relative
            .components()
            .all(|component| matches!(component, std::path::Component::Normal(_)))
        {
            return Ok(None);
        }
        let name = match CString::new(relative.as_os_str().as_bytes()) {
            Ok(name) => name,
            Err(_) => return Ok(None),
        };
        // O_NOFOLLOW_ANY must not be combined with O_NOFOLLOW (EINVAL in XNU).
        let flags = libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW_ANY | libc::O_NONBLOCK;
        let fd = unsafe { libc::openat(self.directory.as_raw_fd(), name.as_ptr(), flags) };
        if fd < 0 {
            return Err(std::io::Error::last_os_error());
        }
        let file = unsafe { std::fs::File::from_raw_fd(fd) };
        let metadata = match file.metadata() {
            Ok(metadata) => metadata,
            Err(_) => return Ok(None),
        };
        Ok((metadata.is_file() && metadata.nlink() == 1).then_some(file))
    }

    #[cfg(windows)]
    pub(crate) fn open(&self, target: &Path) -> Option<std::fs::File> {
        use std::os::windows::fs::OpenOptionsExt;

        const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
        const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x0000_0010;
        // Canonicalize before opening to accept ordinary and verbatim Windows
        // path spellings consistently. The opened handle is checked again
        // below, so a parent junction swapped after this check still fails.
        let canonical = std::fs::canonicalize(target).ok()?;
        if !windows_path_is_beneath(&self.path, &canonical) {
            return None;
        }
        let mut options = std::fs::OpenOptions::new();
        options
            .read(true)
            .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
        let file = options.open(target).ok()?;
        let metadata = file.metadata().ok()?;
        let (attributes, links) = windows_handle_information(&file)?;
        if !metadata.is_file()
            || attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0
            || attributes & FILE_ATTRIBUTE_DIRECTORY != 0
            || links != 1
        {
            return None;
        }
        let final_path = windows_final_handle_path(&file)?;
        windows_path_is_beneath(&self.path, &final_path).then_some(file)
    }

    #[cfg(not(any(unix, windows)))]
    pub(crate) fn open(&self, _target: &Path) -> Option<std::fs::File> {
        None
    }
}

#[cfg(windows)]
#[repr(C)]
#[derive(Default)]
struct WindowsFileTime {
    low: u32,
    high: u32,
}

#[cfg(windows)]
#[repr(C)]
#[derive(Default)]
struct WindowsByHandleFileInformation {
    attributes: u32,
    creation: WindowsFileTime,
    access: WindowsFileTime,
    write: WindowsFileTime,
    volume_serial: u32,
    size_high: u32,
    size_low: u32,
    links: u32,
    index_high: u32,
    index_low: u32,
}

#[cfg(windows)]
#[link(name = "kernel32")]
#[allow(non_snake_case)]
unsafe extern "system" {
    fn GetFileInformationByHandle(
        handle: *mut std::ffi::c_void,
        information: *mut WindowsByHandleFileInformation,
    ) -> i32;
    fn GetFinalPathNameByHandleW(
        handle: *mut std::ffi::c_void,
        path: *mut u16,
        path_len: u32,
        flags: u32,
    ) -> u32;
}

#[cfg(windows)]
fn windows_handle_information(file: &std::fs::File) -> Option<(u32, u32)> {
    use std::os::windows::io::AsRawHandle;

    let mut information = WindowsByHandleFileInformation::default();
    // SAFETY: the handle and output structure remain live for the call.
    let ok = unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) };
    (ok != 0).then_some((information.attributes, information.links))
}

#[cfg(windows)]
fn windows_final_handle_path(file: &std::fs::File) -> Option<PathBuf> {
    use std::os::windows::ffi::OsStringExt;
    use std::os::windows::io::AsRawHandle;

    let mut buffer = vec![0u16; 512];
    loop {
        // SAFETY: `buffer` is writable for its declared UTF-16 capacity.
        let len = unsafe {
            GetFinalPathNameByHandleW(
                file.as_raw_handle(),
                buffer.as_mut_ptr(),
                buffer.len() as u32,
                0,
            )
        } as usize;
        if len == 0 || len > 32_768 {
            return None;
        }
        if len >= buffer.len() {
            buffer.resize(len + 1, 0);
            continue;
        }
        buffer.truncate(len);
        return Some(PathBuf::from(std::ffi::OsString::from_wide(&buffer)));
    }
}

#[cfg(windows)]
fn windows_path_is_beneath(root: &Path, target: &Path) -> bool {
    fn normalize(path: &Path) -> String {
        let text = path.to_string_lossy().replace('/', "\\");
        let text = if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
            format!(r"\\{rest}")
        } else if let Some(rest) = text.strip_prefix(r"\\?\") {
            rest.to_string()
        } else {
            text
        };
        text.trim_end_matches('\\').to_ascii_lowercase()
    }
    let root = normalize(root);
    let target = normalize(target);
    target == root
        || target
            .strip_prefix(&root)
            .is_some_and(|suffix| suffix.starts_with('\\'))
}

#[cfg(target_os = "macos")]
fn macos_nofollow_any_supported() -> bool {
    use std::ffi::CStr;
    use std::mem::MaybeUninit;

    let mut uts = MaybeUninit::<libc::utsname>::zeroed();
    if unsafe { libc::uname(uts.as_mut_ptr()) } != 0 {
        return false;
    }
    let uts = unsafe { uts.assume_init() };
    let release = unsafe { CStr::from_ptr(uts.release.as_ptr()) }.to_bytes();
    macos_nofollow_any_supported_release(release)
}

#[cfg(target_os = "macos")]
fn macos_nofollow_any_supported_release(release: &[u8]) -> bool {
    release
        .split(|byte| *byte == b'.')
        .next()
        .and_then(|major| std::str::from_utf8(major).ok())
        .and_then(|major| major.parse::<u32>().ok())
        .is_some_and(|major| major >= 20)
}

#[cfg(target_os = "macos")]
fn macos_nofollow_any_falls_back(error: i32) -> bool {
    matches!(error, libc::ENAMETOOLONG | libc::EINVAL | libc::ENOTSUP)
}

#[cfg(target_os = "macos")]
fn macos_nofollow_any_must_walk(relative: &Path) -> bool {
    use std::os::unix::ffi::OsStrExt;

    relative.components().any(|component| {
        matches!(component, std::path::Component::Normal(name)
            if name.as_bytes().eq_ignore_ascii_case(b"..namedfork"))
    })
}

pub(crate) fn open_beneath(root: &Path, target: &Path) -> Option<std::fs::File> {
    Root::new(root)?.open(target)
}

#[cfg(all(test, unix))]
mod secure_open_tests {
    use super::{open_beneath, Root};
    use std::path::Path;

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_nofollow_any_kernel_guard_rejects_every_symlink_component() {
        use std::os::fd::AsRawFd;

        assert!(super::macos_nofollow_any_supported_release(b"20.0.0"));
        assert!(!super::macos_nofollow_any_supported_release(b"19.6.0"));
        assert!(!super::macos_nofollow_any_supported_release(b"invalid"));

        let temporary = std::env::temp_dir().join(format!(
            "rdsh-nofollow-any-{}",
            crate::local_http::random_token().unwrap()
        ));
        let project = temporary.join("project");
        let outside = temporary.join("outside.txt");
        std::fs::create_dir(&temporary).unwrap();
        std::fs::create_dir(&project).unwrap();
        std::fs::write(project.join("file.txt"), "approved").unwrap();
        std::fs::write(&outside, "DUMMY_OUTSIDE_FILE").unwrap();
        std::os::unix::fs::symlink(&outside, project.join("link.txt")).unwrap();

        let root = std::fs::canonicalize(&project).unwrap();
        let reader = Root::new(&root).unwrap();
        assert!(reader.open(&root.join("file.txt")).is_some());
        assert!(reader.open(&root.join("link.txt")).is_none());
        assert!(reader.open(&root.join("../outside.txt")).is_none());

        if reader.nofollow_any {
            let name = std::ffi::CString::new("file.txt").unwrap();
            let flags = libc::O_RDONLY
                | libc::O_CLOEXEC
                | libc::O_NOFOLLOW
                | libc::O_NOFOLLOW_ANY
                | libc::O_NONBLOCK;
            let fd = unsafe { libc::openat(reader.directory.as_raw_fd(), name.as_ptr(), flags) };
            assert_eq!(fd, -1);
            assert_eq!(
                std::io::Error::last_os_error().raw_os_error(),
                Some(libc::EINVAL)
            );
        }
        std::fs::remove_dir_all(temporary).unwrap();
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_nofollow_any_falls_back_only_for_supported_open_errors() {
        assert!(super::macos_nofollow_any_falls_back(libc::ENAMETOOLONG));
        assert!(super::macos_nofollow_any_falls_back(libc::EINVAL));
        assert!(super::macos_nofollow_any_falls_back(libc::ENOTSUP));
        assert!(!super::macos_nofollow_any_falls_back(libc::ELOOP));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_nofollow_any_falls_back_for_a_path_longer_than_path_max() {
        use std::io::{Read, Write};
        use std::os::fd::{AsRawFd, FromRawFd};

        let temporary = std::env::temp_dir().join(format!(
            "rdsh-nofollow-any-long-{}",
            crate::local_http::random_token().unwrap()
        ));
        let project = temporary.join("project");
        std::fs::create_dir(&temporary).unwrap();
        std::fs::create_dir(&project).unwrap();
        let root = std::fs::canonicalize(&project).unwrap();
        let reader = Root::new(&root).unwrap();

        let component = "a".repeat(200);
        let mut parent = std::fs::File::open(&root).unwrap();
        let mut target = root.clone();
        for _ in 0..6 {
            let name = std::ffi::CString::new(component.as_bytes()).unwrap();
            assert_eq!(
                unsafe { libc::mkdirat(parent.as_raw_fd(), name.as_ptr(), 0o700) },
                0
            );
            let fd = unsafe {
                libc::openat(
                    parent.as_raw_fd(),
                    name.as_ptr(),
                    libc::O_RDONLY | libc::O_CLOEXEC | libc::O_DIRECTORY | libc::O_NOFOLLOW,
                )
            };
            assert!(fd >= 0);
            parent = unsafe { std::fs::File::from_raw_fd(fd) };
            target.push(&component);
        }
        let name = std::ffi::CString::new("file.txt").unwrap();
        let fd = unsafe {
            libc::openat(
                parent.as_raw_fd(),
                name.as_ptr(),
                libc::O_WRONLY | libc::O_CLOEXEC | libc::O_CREAT | libc::O_EXCL,
                0o600,
            )
        };
        assert!(fd >= 0);
        let mut file = unsafe { std::fs::File::from_raw_fd(fd) };
        file.write_all(b"approved").unwrap();
        drop(file);
        target.push("file.txt");

        if reader.nofollow_any {
            let relative = target.strip_prefix(&root).unwrap();
            let error = reader.open_macos_nofollow_any(relative).unwrap_err();
            assert_eq!(error.raw_os_error(), Some(libc::ENAMETOOLONG));
        }
        let mut text = String::new();
        reader
            .open(&target)
            .unwrap()
            .read_to_string(&mut text)
            .unwrap();
        assert_eq!(text, "approved");
        std::fs::remove_dir_all(temporary).unwrap();
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_nofollow_any_preserves_non_directory_namedfork_rejection() {
        use std::io::{Read, Write};
        use std::os::fd::AsRawFd;

        let temporary = std::env::temp_dir().join(format!(
            "rdsh-nofollow-any-namedfork-{}",
            crate::local_http::random_token().unwrap()
        ));
        let project = temporary.join("project");
        std::fs::create_dir(&temporary).unwrap();
        std::fs::create_dir(&project).unwrap();
        let root = std::fs::canonicalize(&project).unwrap();
        let plain = root.join("plain");
        let mut plain_file = std::fs::File::create(&plain).unwrap();
        plain_file.write_all(b"data").unwrap();
        assert_eq!(
            unsafe {
                libc::fsetxattr(
                    plain_file.as_raw_fd(),
                    c"com.apple.ResourceFork".as_ptr(),
                    c"R".as_ptr().cast(),
                    1,
                    0,
                    0,
                )
            },
            0
        );
        drop(plain_file);

        let reader = Root::new(&root).unwrap();
        let resource_fork = root.join("plain/..namedfork/rsrc");
        assert!(reader.open(&resource_fork).is_none());
        assert_eq!(
            reader
                .open_macos_nofollow_any(resource_fork.strip_prefix(&root).unwrap())
                .unwrap_err()
                .raw_os_error(),
            Some(libc::EINVAL)
        );
        assert!(reader.open(&root.join("plain/..NAMEDFORK/rsrc")).is_none());

        let real_fork_directory = root.join("real/..namedfork");
        std::fs::create_dir_all(&real_fork_directory).unwrap();
        let ordinary = real_fork_directory.join("file.txt");
        std::fs::write(&ordinary, "approved").unwrap();
        let mut text = String::new();
        reader
            .open(&ordinary)
            .unwrap()
            .read_to_string(&mut text)
            .unwrap();
        assert_eq!(text, "approved");
        std::fs::remove_dir_all(temporary).unwrap();
    }

    #[test]
    fn cached_root_keeps_approved_identity_when_path_is_replaced() {
        use std::io::Read;
        let temporary = std::env::temp_dir().join(format!(
            "rdsh-root-open-{}",
            crate::local_http::random_token().unwrap()
        ));
        let project = temporary.join("project");
        let outside = temporary.join("outside");
        std::fs::create_dir_all(&project).unwrap();
        std::fs::create_dir(&outside).unwrap();
        std::fs::write(project.join("file.txt"), "approved").unwrap();
        std::fs::write(outside.join("file.txt"), "DUMMY_OUTSIDE_FILE").unwrap();
        let path = std::fs::canonicalize(&project).unwrap();
        let root = Root::new(&path).unwrap();
        std::fs::rename(&project, temporary.join("approved-root")).unwrap();
        std::os::unix::fs::symlink(&outside, &project).unwrap();
        let mut text = String::new();
        root.open(&path.join("file.txt"))
            .unwrap()
            .read_to_string(&mut text)
            .unwrap();
        assert_eq!(text, "approved");
        assert!(Root::new(&path).is_none());
        assert!(root.open(&outside.join("file.txt")).is_none());
        assert!(root.open(&path.join("../outside/file.txt")).is_none());
        std::fs::remove_dir_all(temporary).unwrap();
    }

    #[test]
    fn rejects_parent_symlink_swaps_and_fifo_without_waiting() {
        use std::os::unix::ffi::OsStrExt;
        let temporary = std::env::temp_dir().join(format!(
            "rdsh-parent-open-{}",
            crate::local_http::random_token().unwrap()
        ));
        let project = temporary.join("project");
        let parent = project.join("parent");
        let outside = temporary.join("outside");
        std::fs::create_dir_all(&parent).unwrap();
        std::fs::create_dir(&outside).unwrap();
        std::fs::write(parent.join("file.txt"), "safe").unwrap();
        std::fs::write(outside.join("file.txt"), "DUMMY_OUTSIDE_FILE").unwrap();
        let root = std::fs::canonicalize(&project).unwrap();
        let reader = Root::new(&root).unwrap();
        let validated = std::fs::canonicalize(parent.join("file.txt")).unwrap();
        std::fs::rename(&parent, project.join("original-parent")).unwrap();
        std::os::unix::fs::symlink(&outside, &parent).unwrap();
        assert!(open_beneath(&root, &validated).is_none());
        assert!(reader.open(&validated).is_none());

        let fifo = root.join("pipe");
        let name = std::ffi::CString::new(fifo.as_os_str().as_bytes()).unwrap();
        assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0);
        assert!(open_beneath(&root, &fifo).is_none());
        assert!(reader.open(&fifo).is_none());
        assert!(open_beneath(&root, &root).is_none());
        std::fs::remove_dir_all(temporary).unwrap();
    }

    #[test]
    fn rejects_nested_parent_symlink_swap_after_a_successful_open() {
        use std::io::Read;

        let temporary = std::env::temp_dir().join(format!(
            "rdsh-nested-parent-open-{}",
            crate::local_http::random_token().unwrap()
        ));
        let project = temporary.join("project");
        let nested_parent = project.join("one/two");
        let nested_file = nested_parent.join("three/four/file.txt");
        let outside = temporary.join("outside");
        std::fs::create_dir_all(nested_file.parent().unwrap()).unwrap();
        std::fs::create_dir_all(outside.join("three/four")).unwrap();
        std::fs::write(&nested_file, "approved").unwrap();
        std::fs::write(outside.join("three/four/file.txt"), "DUMMY_OUTSIDE_FILE").unwrap();

        let root = std::fs::canonicalize(&project).unwrap();
        let reader = Root::new(&root).unwrap();
        let validated = std::fs::canonicalize(&nested_file).unwrap();
        let mut text = String::new();
        reader
            .open(&validated)
            .unwrap()
            .read_to_string(&mut text)
            .unwrap();
        assert_eq!(text, "approved");

        std::fs::rename(&nested_parent, project.join("one/original-two")).unwrap();
        std::os::unix::fs::symlink(&outside, &nested_parent).unwrap();

        assert!(reader.open(&validated).is_none());
        std::fs::remove_dir_all(temporary).unwrap();
    }

    #[test]
    fn rejects_symlink_swap_after_validation_and_hardlinked_outside_file() {
        let root = std::env::temp_dir().join(format!(
            "rdsh-file-open-{}",
            crate::local_http::random_token().unwrap()
        ));
        std::fs::create_dir_all(&root).unwrap();
        let project = root.join("project");
        std::fs::create_dir_all(&project).unwrap();
        let outside = root.join("outside-secret");
        std::fs::write(&outside, "DUMMY_CONTEXT_SECRET").unwrap();

        let slot = project.join("working.txt");
        std::fs::write(&slot, "safe initial file").unwrap();
        let root = std::fs::canonicalize(&project).unwrap();
        let reader = Root::new(&root).unwrap();
        let validated = std::fs::canonicalize(&slot).unwrap();
        std::fs::remove_file(&slot).unwrap();
        std::os::unix::fs::symlink(&outside, &slot).unwrap();
        assert!(open_beneath(&root, &validated).is_none());
        assert!(reader.open(&validated).is_none());

        std::fs::remove_file(&slot).unwrap();
        std::fs::hard_link(&outside, &slot).unwrap();
        let linked = std::fs::canonicalize(&slot).unwrap();
        assert!(open_beneath(Path::new(&root), &linked).is_none());
        assert!(reader.open(&linked).is_none());
        std::fs::remove_dir_all(root.parent().unwrap()).unwrap();
    }
}

/// Lenient pre-check for `--share-file` entries before they reach the tool
/// boundary: the JS snapshot remains the enforcer (dotfiles, key names,
/// sizes), so Rust only rejects what is definitely unusable — empty,
/// absolute, parent-escaping, or over-count selections — with a clear error
/// instead of a late sandbox failure.
pub(crate) fn validate_share_files(files: &[String]) -> Result<(), String> {
    if files.len() > 256 {
        return Err(format!("too many --share-file entries ({})", files.len()));
    }
    for f in files {
        if f.is_empty() || f.len() > 1024 {
            return Err(format!("invalid --share-file entry {f:?}"));
        }
        let path_bytes = f.as_bytes();
        let has_windows_drive_root = path_bytes.len() >= 3
            && path_bytes[0].is_ascii_alphabetic()
            && path_bytes[1] == b':'
            && matches!(path_bytes[2], b'/' | b'\\');
        if f.starts_with('/') || f.starts_with('\\') || has_windows_drive_root {
            return Err(format!("--share-file must be workspace-relative: {f:?}"));
        }
        if f.split(['/', '\\']).any(|part| part == "..") {
            return Err(format!("--share-file must not escape: {f:?}"));
        }
        if f.bytes().any(|b| b == 0) {
            return Err(format!("invalid --share-file entry {f:?}"));
        }
    }
    Ok(())
}

/// Create the directory (recursively) with 0700 so no other user can traverse
/// the state tree below it. Directories that already exist keep their mode:
/// only the ones this call creates are tightened, so a DSH-made 0700 is never
/// relaxed and a user's own choice is not silently changed.
pub(crate) fn ensure_private_dir(path: &Path) -> std::io::Result<()> {
    if path.is_dir() {
        return Ok(());
    }
    let mut builder = std::fs::DirBuilder::new();
    builder.recursive(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt;
        builder.mode(0o700);
    }
    builder.create(path)
}

/// True when the file exists and other users can read or traverse it. The
/// documented rule is "keep it at 0600, otherwise dsh refuses to read it";
/// refusing loudly here keeps a world-readable key from being used silently.
pub(crate) fn others_can_read(path: &Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt as _;
        let Ok(metadata) = std::fs::symlink_metadata(path) else {
            return false;
        };
        metadata.is_file() && metadata.mode() & 0o077 != 0
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        false
    }
}

#[cfg(test)]
mod private_state_tests {
    use super::{ensure_private_dir, others_can_read};

    #[test]
    fn a_created_state_directory_is_owner_only() {
        let root = std::env::temp_dir().join(format!("rdsh-privdir-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let target = root.join("a").join("b");
        ensure_private_dir(&target).unwrap();
        assert!(target.is_dir());
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt as _;
            let mode = std::fs::metadata(&target).unwrap().mode() & 0o777;
            assert_eq!(mode, 0o700, "created state dir must be 0700, got {mode:o}");
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn an_existing_directory_keeps_its_mode() {
        let root = std::env::temp_dir().join(format!("rdsh-privkeep-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o750)).unwrap();
        }
        ensure_private_dir(&root).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt as _;
            let mode = std::fs::metadata(&root).unwrap().mode() & 0o777;
            assert_eq!(mode, 0o750, "an existing directory must not be changed");
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn a_world_readable_file_is_flagged() {
        let path = std::env::temp_dir().join(format!("rdsh-creds-{}", std::process::id()));
        let _ = std::fs::remove_file(&path);
        std::fs::write(&path, b"x").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
            assert!(others_can_read(&path));
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
            assert!(!others_can_read(&path));
        }
        assert!(!others_can_read(&path.with_extension("missing")));
        let _ = std::fs::remove_file(&path);
    }
}
#[cfg(test)]
mod share_validation_tests {
    use super::validate_share_files;

    #[test]
    fn accepts_plain_relative_paths() {
        assert!(validate_share_files(&["AGENTS.md".into(), "docs/a b.txt".into()]).is_ok());
        assert!(validate_share_files(&[]).is_ok());
    }

    #[test]
    fn rejects_absolute_parent_and_overflow() {
        for bad in [
            "",
            "/etc/passwd",
            "C:\\Windows\\win.ini",
            "C:/Windows/win.ini",
            "a/../../b",
            "..\\x",
            "a\0b",
        ] {
            assert!(validate_share_files(&[bad.into()]).is_err(), "{bad:?}");
        }
        let many = vec!["a".to_string(); 257];
        assert!(validate_share_files(&many).is_err());
    }
}
#[cfg(all(test, windows))]
mod windows_secure_open_tests {
    use super::Root;
    use std::io::Read;

    struct Temp(std::path::PathBuf);
    impl Temp {
        fn new() -> Self {
            let path = std::env::temp_dir().join(format!(
                "rdsh-windows-open-{}-{}",
                std::process::id(),
                crate::local_http::random_token().unwrap()
            ));
            std::fs::create_dir_all(&path).unwrap();
            Self(path)
        }
    }
    impl Drop for Temp {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[test]
    fn opens_regular_file_under_root() {
        let temp = Temp::new();
        let root = temp.0.join("project");
        std::fs::create_dir_all(&root).unwrap();
        let path = root.join("source.rs");
        std::fs::write(&path, "approved").unwrap();
        let root = std::fs::canonicalize(root).unwrap();
        let reader = Root::new(&root).unwrap();
        let mut text = String::new();
        reader
            .open(&path)
            .unwrap()
            .read_to_string(&mut text)
            .unwrap();
        assert_eq!(text, "approved");
    }

    #[test]
    fn rejects_hard_links_by_open_handle_link_count() {
        let temp = Temp::new();
        let root = temp.0.join("project");
        std::fs::create_dir_all(&root).unwrap();
        let path = root.join("source.rs");
        std::fs::write(&path, "linked").unwrap();
        std::fs::hard_link(&path, temp.0.join("outside.rs")).unwrap();
        let root = std::fs::canonicalize(root).unwrap();
        let reader = Root::new(&root).unwrap();
        assert!(reader.open(&path).is_none());
    }

    #[test]
    fn rejects_parent_reparse_points_that_resolve_outside_root() {
        use std::os::windows::fs::symlink_dir;

        let temp = Temp::new();
        let root = temp.0.join("project");
        let outside = temp.0.join("outside");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::create_dir_all(&outside).unwrap();
        std::fs::write(outside.join("secret.rs"), "outside").unwrap();
        let junction = root.join("junction");
        if symlink_dir(&outside, &junction).is_err() {
            return;
        }
        let canonical_root = std::fs::canonicalize(root).unwrap();
        let reader = Root::new(&canonical_root).unwrap();
        assert!(reader.open(&junction.join("secret.rs")).is_none());
    }
}