astrid-workspace 0.5.0

Operational workspace boundaries for Astrid secure agent runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
use std::ffi::OsString;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Validate a path for safe interpolation into sandbox profiles (SBPL/bwrap).
///
/// Rejects relative paths, non-UTF-8, double-quote, backslash, and null byte -
/// all of which can break or bypass sandbox profile syntax.
fn validate_sandbox_str<'a>(path: &'a Path, label: &str) -> io::Result<&'a str> {
    if !path.is_absolute() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "sandbox {label} must be an absolute path, got: {}",
                path.display()
            ),
        ));
    }
    let s = path.to_str().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("sandbox {label} is not valid UTF-8: {}", path.display()),
        )
    })?;
    if s.contains(['"', '\\', '\0']) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "sandbox {label} contains forbidden characters (double-quote, backslash, or null): {}",
                path.display()
            ),
        ));
    }
    Ok(s)
}

/// Validates that a path is safe for interpolation into an SBPL profile string.
///
/// Rejects:
/// - Non-UTF-8 paths (silent lossy coercion would misalign the SBPL rule with the real path)
/// - Double-quote (`"`) - SBPL string delimiter; allows sandbox escape
/// - Backslash (`\`) - SBPL escape character; silently reinterprets the path
/// - Null byte (`\0`) - defense in depth
///
/// # Errors
///
/// Returns an error if the path is not valid UTF-8 or contains forbidden characters.
#[cfg(test)]
fn validate_sandbox_path(path: &Path) -> io::Result<()> {
    let s = path.to_str().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("sandbox path is not valid UTF-8: {}", path.display()),
        )
    })?;
    if s.contains(['"', '\\', '\0']) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "sandbox path contains forbidden characters (double-quote, backslash, or null): {}",
                path.display()
            ),
        ));
    }
    Ok(())
}

/// Returns the Darwin kernel major version (e.g. 25 for macOS 15 Sequoia).
/// Used to detect macOS 15+ where `sandbox-exec` is deprecated.
#[cfg(target_os = "macos")]
fn darwin_major_version() -> u32 {
    std::process::Command::new("uname")
        .arg("-r")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .and_then(|s| s.split('.').next()?.parse().ok())
        .unwrap_or(0)
}

/// Wraps a standard OS command in a native kernel sandbox (bwrap or Seatbelt).
///
/// Ensures that agent-executed native tools are restricted from accessing
/// anything outside the provided worktree sandbox.
pub struct SandboxCommand;

impl SandboxCommand {
    /// Wraps the provided command in the host OS sandbox, restricting its access to
    /// the provided `worktree_path`.
    ///
    /// - On Linux, this dynamically prepends `bwrap` with strict mount rules.
    /// - On macOS, this dynamically generates a Seatbelt profile and prepends `sandbox-exec -p`.
    /// - On other platforms (Windows), this currently passes through the command unmodified (with a warning).
    ///
    /// # Errors
    ///
    /// Returns an error if the worktree path is not absolute, not valid UTF-8,
    /// or contains characters unsafe for SBPL interpolation (double-quote,
    /// backslash, or null byte).
    ///
    /// # Panics
    ///
    /// Panics on macOS if `validate_sandbox_str` passes but the path is not
    /// valid UTF-8. This is unreachable because the validation rejects
    /// non-UTF-8 paths.
    #[allow(clippy::needless_pass_by_value)] // Consumed on macOS early return, borrowed on Linux bwrap
    pub fn wrap(inner_cmd: Command, worktree_path: &Path) -> io::Result<Command> {
        // Validate on all platforms for defense in depth and API consistency.
        // On macOS the validated string is needed for SBPL interpolation.
        // On Linux bwrap passes paths as argv entries (no injection risk),
        // but we still reject unsafe paths at the API boundary.
        let _ = validate_sandbox_str(worktree_path, "worktree path")?;

        #[cfg(target_os = "linux")]
        {
            // Bubblewrap implementation - paths are passed as separate argv entries (no injection).
            // The process can only read the root OS, but can only write to the worktree and /tmp.
            let mut bwrap = Command::new("bwrap");
            bwrap
                .arg("--ro-bind").arg("/").arg("/") // Read-only access to host OS (for binaries like /usr/bin/node)
                .arg("--dev").arg("/dev")           // Standard dev mounts
                .arg("--proc").arg("/proc")         // Standard proc mounts
                .arg("--bind").arg(worktree_path).arg(worktree_path) // Write access to the worktree
                .arg("--tmpfs").arg("/tmp")         // Disposable tmpfs
                .arg("--unshare-all")               // Drop namespaces (network, pid, etc.)
                .arg("--share-net")                 // Re-enable network so npm/cargo can fetch
                .arg("--die-with-parent"); // Prevent orphan processes

            // Extract the original command and args, and append them to bwrap
            bwrap.arg(inner_cmd.get_program());
            for arg in inner_cmd.get_args() {
                bwrap.arg(arg);
            }

            // Inherit the env and current_dir from the original command
            for (k, v) in inner_cmd.get_envs() {
                if let Some(v) = v {
                    bwrap.env(k, v);
                } else {
                    bwrap.env_remove(k);
                }
            }
            if let Some(dir) = inner_cmd.get_current_dir() {
                bwrap.current_dir(dir);
            }

            Ok(bwrap)
        }

        #[cfg(target_os = "macos")]
        {
            // sandbox-exec (Seatbelt) is deprecated on macOS 15+ (Darwin >= 24).
            if darwin_major_version() >= 24 {
                tracing::warn!(
                    "macOS 15+ detected: sandbox-exec is deprecated. Running host process unsandboxed."
                );
                return Ok(inner_cmd);
            }

            // Safe: validate_sandbox_str above confirmed valid UTF-8.
            let worktree_str = worktree_path
                .to_str()
                .expect("unreachable: validated UTF-8 above");

            // macOS Seatbelt implementation
            // Deny all writes except to the worktree and /tmp.
            // Restrict reads to system directories, the worktree, and tmp to protect user dotfiles.
            let profile = format!(
                r#"(version 1)
(deny default)
(allow process-exec*)
(allow process-fork)
(allow network*)
(allow sysctl-read)
(allow ipc-posix-shm)
(allow file-read*
    (subpath "/usr")
    (subpath "/bin")
    (subpath "/sbin")
    (subpath "/System")
    (subpath "/Library")
    (subpath "/opt")
    (subpath "/dev")
    (subpath "{worktree_str}")
    (subpath "/private/tmp")
    (subpath "/var/folders")
)
(allow file-write*
    (subpath "{worktree_str}")
    (subpath "/private/tmp")
    (subpath "/var/folders")
    (literal "/dev/null")
)"#
            );

            // Pass profile inline via -p to avoid temp-file leaks and TOCTOU races.
            let mut sb_cmd = Command::new("sandbox-exec");
            sb_cmd.arg("-p").arg(&profile);

            // Extract original
            sb_cmd.arg(inner_cmd.get_program());
            for arg in inner_cmd.get_args() {
                sb_cmd.arg(arg);
            }

            // Inherit env and dir
            for (k, v) in inner_cmd.get_envs() {
                if let Some(v) = v {
                    sb_cmd.env(k, v);
                } else {
                    sb_cmd.env_remove(k);
                }
            }
            if let Some(dir) = inner_cmd.get_current_dir() {
                sb_cmd.current_dir(dir);
            }

            Ok(sb_cmd)
        }

        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
        {
            tracing::warn!(
                "Host-level sandboxing is not supported on this OS. Processes will run unsandboxed."
            );
            Ok(inner_cmd)
        }
    }
}

/// The sandbox wrapper program and its argument prefix.
///
/// The caller appends the original program and its arguments after these args.
#[derive(Debug, Clone)]
pub struct SandboxPrefix {
    /// The sandbox wrapper program (e.g., `bwrap` or `sandbox-exec`).
    pub program: OsString,
    /// Arguments to the sandbox wrapper, NOT including the inner command.
    pub args: Vec<OsString>,
}

/// Data-oriented sandbox configuration that produces a wrapper program + args
/// prefix rather than wrapping a `std::process::Command` directly.
///
/// This is useful when the consumer needs a different `Command` type (e.g.,
/// `tokio::process::Command`) but still wants OS-level sandbox wrapping.
///
/// # Example
///
/// ```rust,ignore
/// let config = ProcessSandboxConfig::new("/home/user/project")
///     .with_network(true)
///     .with_hidden("/home/user/.astrid");
///
/// if let Some(prefix) = config.sandbox_prefix()? {
///     let mut cmd = tokio::process::Command::new(&prefix.program);
///     cmd.args(&prefix.args);
///     cmd.arg("npx").args(["@anthropics/mcp-server-filesystem", "/tmp"]);
/// }
/// ```
#[derive(Debug, Clone)]
pub struct ProcessSandboxConfig {
    /// Root directory the sandboxed process can write to.
    writable_root: PathBuf,
    /// Additional read-only paths beyond the OS defaults.
    extra_read_paths: Vec<PathBuf>,
    /// Additional writable paths beyond `writable_root`.
    extra_write_paths: Vec<PathBuf>,
    /// Whether to allow network access.
    allow_network: bool,
    /// Paths to overlay with empty tmpfs (Linux) or exclude (macOS), blocking access.
    hidden_paths: Vec<PathBuf>,
}

impl ProcessSandboxConfig {
    /// Create a new sandbox config with the given writable root.
    #[must_use]
    pub fn new(writable_root: impl Into<PathBuf>) -> Self {
        Self {
            writable_root: writable_root.into(),
            extra_read_paths: Vec::new(),
            extra_write_paths: Vec::new(),
            allow_network: true,
            hidden_paths: Vec::new(),
        }
    }

    /// Set whether network access is allowed.
    #[must_use]
    pub fn with_network(mut self, allow: bool) -> Self {
        self.allow_network = allow;
        self
    }

    /// Add an additional read-only path.
    #[must_use]
    pub fn with_extra_read(mut self, path: impl Into<PathBuf>) -> Self {
        self.extra_read_paths.push(path.into());
        self
    }

    /// Add an additional writable path.
    #[must_use]
    pub fn with_extra_write(mut self, path: impl Into<PathBuf>) -> Self {
        self.extra_write_paths.push(path.into());
        self
    }

    /// Add a path to hide from the sandboxed process.
    ///
    /// On Linux, this overlays an empty tmpfs. On macOS, the path is
    /// excluded from the Seatbelt read allowlist.
    #[must_use]
    pub fn with_hidden(mut self, path: impl Into<PathBuf>) -> Self {
        self.hidden_paths.push(path.into());
        self
    }

    /// Build the sandbox wrapper prefix for this configuration.
    ///
    /// Returns `Some(prefix)` on supported platforms (Linux, macOS), `None` on
    /// unsupported platforms (e.g., Windows).
    ///
    /// # Errors
    ///
    /// Returns an error if any configured path is not valid UTF-8, not absolute,
    /// or contains characters that would break sandbox profile syntax
    /// (double-quote, backslash, or null byte).
    pub fn sandbox_prefix(&self) -> io::Result<Option<SandboxPrefix>> {
        // Validate all configured paths up front, regardless of platform.
        // This ensures the doc contract ("returns Err for non-UTF-8 or
        // forbidden chars") holds on every OS, not just macOS where SBPL
        // interpolation makes it exploitable.
        self.validate_all_paths()?;

        #[cfg(target_os = "linux")]
        {
            Ok(Some(self.build_bwrap_prefix()))
        }

        #[cfg(target_os = "macos")]
        {
            self.build_seatbelt_prefix().map(Some)
        }

        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
        {
            tracing::warn!(
                "Host-level sandboxing is not supported on this OS. \
                 MCP server will run unsandboxed."
            );
            Ok(None)
        }
    }

    /// Validate all configured paths for safe use in sandbox profiles.
    fn validate_all_paths(&self) -> io::Result<()> {
        validate_sandbox_str(&self.writable_root, "writable root")?;
        for p in &self.extra_read_paths {
            validate_sandbox_str(p, "extra read path")?;
        }
        for p in &self.extra_write_paths {
            validate_sandbox_str(p, "extra write path")?;
        }
        for p in &self.hidden_paths {
            validate_sandbox_str(p, "hidden path")?;
        }
        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn build_bwrap_prefix(&self) -> SandboxPrefix {
        let mut args: Vec<OsString> = Vec::new();

        // Read-only access to host OS (for binaries like /usr/bin/node)
        args.extend(["--ro-bind", "/", "/"].map(OsString::from));
        // Standard dev + proc mounts
        args.extend(["--dev", "/dev"].map(OsString::from));
        args.extend(["--proc", "/proc"].map(OsString::from));

        // Write access to the writable root
        args.extend([
            OsString::from("--bind"),
            self.writable_root.as_os_str().into(),
            self.writable_root.as_os_str().into(),
        ]);

        // Additional writable paths
        for path in &self.extra_write_paths {
            args.extend([
                OsString::from("--bind"),
                path.as_os_str().into(),
                path.as_os_str().into(),
            ]);
        }

        // extra_read_paths are not emitted on Linux because `--ro-bind / /`
        // already grants read access to all host paths. Hidden paths override
        // via tmpfs below. On macOS, extra_read_paths are added to the
        // Seatbelt allow-list because the default policy is deny-all.

        // Disposable tmpfs for /tmp
        args.extend(["--tmpfs", "/tmp"].map(OsString::from));

        // Hidden paths: overlay with empty tmpfs
        for path in &self.hidden_paths {
            args.extend([OsString::from("--tmpfs"), path.as_os_str().into()]);
        }

        // Drop all namespaces
        args.push(OsString::from("--unshare-all"));

        // Conditionally re-enable network
        if self.allow_network {
            args.push(OsString::from("--share-net"));
        }

        // Prevent orphan processes
        args.push(OsString::from("--die-with-parent"));

        // Separator before the inner command
        args.push(OsString::from("--"));

        SandboxPrefix {
            program: OsString::from("bwrap"),
            args,
        }
    }

    #[cfg(target_os = "macos")]
    fn build_seatbelt_prefix(&self) -> io::Result<SandboxPrefix> {
        let writable_root_str = validate_sandbox_str(&self.writable_root, "writable root")?;

        // Build the network rule conditionally
        let network_rule = if self.allow_network {
            "(allow network*)"
        } else {
            ""
        };

        // Build extra read path rules
        let extra_read_rules: String = self
            .extra_read_paths
            .iter()
            .map(|p| {
                validate_sandbox_str(p, "extra read path").map(|s| format!("    (subpath \"{s}\")"))
            })
            .collect::<io::Result<Vec<_>>>()?
            .join("\n");

        // Build extra write path rules
        let extra_write_rules: String = self
            .extra_write_paths
            .iter()
            .map(|p| {
                validate_sandbox_str(p, "extra write path")
                    .map(|s| format!("    (subpath \"{s}\")"))
            })
            .collect::<io::Result<Vec<_>>>()?
            .join("\n");

        // Build deny rules for hidden paths (e.g. ~/.astrid/).
        // Skip any hidden path that is an ancestor of or equal to the
        // writable_root — the capsule must be able to access its own
        // directory, and Seatbelt deny rules block even lstat() on parent
        // paths which prevents Node.js from resolving real paths.
        let hidden_deny_rules: String = self
            .hidden_paths
            .iter()
            .filter(|p| !self.writable_root.starts_with(p.as_path()))
            .map(|p| {
                validate_sandbox_str(p, "hidden path").map(|s| {
                    format!(
                        "(deny file-read* (subpath \"{s}\"))\n\
                         (deny file-write* (subpath \"{s}\"))"
                    )
                })
            })
            .collect::<io::Result<Vec<_>>>()?
            .join("\n");

        let profile = format!(
            r#"(version 1)
(deny default)
(allow process-exec*)
(allow process-fork)
{network_rule}
(allow sysctl-read)
(allow ipc-posix-shm)
(allow mach*)
(allow file-read*
    (subpath "/usr")
    (subpath "/bin")
    (subpath "/sbin")
    (subpath "/System")
    (subpath "/Library")
    (subpath "/opt")
    (subpath "/dev")
    (subpath "{writable_root_str}")
    (subpath "/private/tmp")
    (subpath "/var/folders")
    (literal "/")
{extra_read_rules}
)
(allow file-write*
    (subpath "{writable_root_str}")
    (subpath "/private/tmp")
    (subpath "/var/folders")
    (literal "/dev/null")
{extra_write_rules}
)
{hidden_deny_rules}"#
        );

        // Pass profile inline via -p to avoid temp file leak.
        let args = vec![OsString::from("-p"), OsString::from(&profile)];

        Ok(SandboxPrefix {
            program: OsString::from("sandbox-exec"),
            args,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    // --- validate_sandbox_path tests ---

    #[test]
    fn validate_sandbox_path_accepts_normal_path() {
        let path = PathBuf::from("/Users/agent/workspace/project");
        assert!(validate_sandbox_path(&path).is_ok());
    }

    #[test]
    fn validate_sandbox_path_accepts_path_with_spaces() {
        let path = PathBuf::from("/Users/agent/my project/src");
        assert!(validate_sandbox_path(&path).is_ok());
    }

    #[test]
    fn validate_sandbox_path_rejects_double_quote() {
        let path = PathBuf::from("/Users/agent/work\"inject");
        let err = validate_sandbox_path(&path).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
        assert!(
            err.to_string().contains("forbidden characters"),
            "unexpected error message: {err}"
        );
    }

    #[test]
    fn validate_sandbox_path_rejects_sbpl_injection_payload() {
        // Simulates an actual SBPL escape attempt.
        let path = PathBuf::from(r#"/tmp/evil") (allow file-write* (subpath "/"))"#);
        let err = validate_sandbox_path(&path).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
        assert!(
            err.to_string().contains("forbidden characters"),
            "unexpected error message: {err}"
        );
    }

    #[test]
    fn validate_sandbox_path_rejects_backslash() {
        // Backslash is an SBPL escape character - would silently reinterpret the path.
        let path = PathBuf::from("/tmp/work\\nspace");
        let err = validate_sandbox_path(&path).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
        assert!(
            err.to_string().contains("forbidden characters"),
            "unexpected error message: {err}"
        );
    }

    #[test]
    fn validate_sandbox_path_rejects_null_byte() {
        // Null byte (0x00) is valid UTF-8, so to_str() succeeds.
        // The s.contains('\0') guard then catches it.
        let path = PathBuf::from("/tmp/work\0space");
        let err = validate_sandbox_path(&path).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
        assert!(
            err.to_string().contains("forbidden characters"),
            "unexpected error message: {err}"
        );
    }

    // --- SandboxCommand::wrap() tests ---

    #[test]
    fn test_wrap_rejects_non_utf8_path() {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt;

        let bad_bytes: &[u8] = b"/tmp/\xff\xfe/workspace";
        let bad_path = Path::new(OsStr::from_bytes(bad_bytes));
        let cmd = Command::new("echo");
        let result = SandboxCommand::wrap(cmd, bad_path);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("not valid UTF-8"),
            "error should mention UTF-8: {err_msg}"
        );
    }

    #[test]
    fn test_wrap_rejects_double_quote_path() {
        let bad_path = Path::new("/tmp/evil\"injection/workspace");
        let cmd = Command::new("echo");
        let result = SandboxCommand::wrap(cmd, bad_path);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("forbidden characters"),
            "error should mention forbidden chars: {err_msg}"
        );
    }

    #[test]
    fn test_wrap_rejects_null_byte_path() {
        let bad_path = Path::new("/tmp/evil\0null/workspace");
        let cmd = Command::new("echo");
        let result = SandboxCommand::wrap(cmd, bad_path);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("forbidden characters"),
            "error should mention forbidden chars: {err_msg}"
        );
    }

    #[test]
    fn test_wrap_rejects_backslash_path() {
        let bad_path = Path::new("/tmp/work\\nspace");
        let cmd = Command::new("echo");
        let result = SandboxCommand::wrap(cmd, bad_path);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("forbidden characters"),
            "error should mention forbidden chars: {err_msg}"
        );
    }

    #[test]
    fn test_wrap_rejects_relative_path() {
        let bad_path = Path::new("relative/workspace");
        let cmd = Command::new("echo");
        let result = SandboxCommand::wrap(cmd, bad_path);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("absolute path"),
            "error should mention absolute path: {err_msg}"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn wrap_uses_inline_profile() {
        let cmd = Command::new("echo");
        let path = PathBuf::from("/tmp/safe-workspace");
        let wrapped = SandboxCommand::wrap(cmd, &path).unwrap();

        if super::darwin_major_version() >= 24 {
            // Passthrough: the program is "echo" directly, not "sandbox-exec".
            assert_eq!(
                wrapped.get_program(),
                "echo",
                "on macOS 15+, command should pass through unwrapped"
            );
        } else {
            let args: Vec<_> = wrapped.get_args().collect();
            // First arg should be "-p" (inline profile), not "-f" (file).
            assert_eq!(args[0], "-p", "expected -p for inline profile delivery");
            // Second arg is the profile content, which should contain the worktree path.
            let profile = args[1].to_string_lossy();
            assert!(
                profile.contains("/tmp/safe-workspace"),
                "profile should contain the worktree path"
            );
        }
    }

    // --- ProcessSandboxConfig builder tests ---

    #[test]
    fn test_sandbox_config_builder() {
        let config = ProcessSandboxConfig::new("/project")
            .with_network(false)
            .with_extra_read("/data")
            .with_extra_write("/output")
            .with_hidden("/home/user/.astrid");

        assert_eq!(config.writable_root, PathBuf::from("/project"));
        assert!(!config.allow_network);
        assert_eq!(config.extra_read_paths, vec![PathBuf::from("/data")]);
        assert_eq!(config.extra_write_paths, vec![PathBuf::from("/output")]);
        assert_eq!(
            config.hidden_paths,
            vec![PathBuf::from("/home/user/.astrid")]
        );
    }

    #[test]
    fn test_sandbox_config_defaults() {
        let config = ProcessSandboxConfig::new("/project");
        assert!(config.allow_network);
        assert!(config.extra_read_paths.is_empty());
        assert!(config.extra_write_paths.is_empty());
        assert!(config.hidden_paths.is_empty());
    }

    // --- Platform-specific prefix tests ---

    #[cfg(target_os = "linux")]
    #[test]
    fn test_bwrap_prefix_basic() {
        let config = ProcessSandboxConfig::new("/project");
        let prefix = config.build_bwrap_prefix();

        assert_eq!(prefix.program, OsString::from("bwrap"));

        let args_str: Vec<String> = prefix
            .args
            .iter()
            .map(|a| a.to_string_lossy().to_string())
            .collect();

        // Verify core structure
        assert!(args_str.contains(&"--ro-bind".to_string()));
        assert!(args_str.contains(&"--dev".to_string()));
        assert!(args_str.contains(&"--proc".to_string()));
        assert!(args_str.contains(&"--unshare-all".to_string()));
        assert!(args_str.contains(&"--share-net".to_string()));
        assert!(args_str.contains(&"--die-with-parent".to_string()));
        assert!(args_str.contains(&"--".to_string()));

        // Writable root bind
        let bind_idx = args_str
            .iter()
            .position(|a| a == "--bind")
            .expect("should have --bind");
        assert_eq!(args_str[bind_idx + 1], "/project");
        assert_eq!(args_str[bind_idx + 2], "/project");
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_bwrap_prefix_no_network() {
        let config = ProcessSandboxConfig::new("/project").with_network(false);
        let prefix = config.build_bwrap_prefix();

        let args_str: Vec<String> = prefix
            .args
            .iter()
            .map(|a| a.to_string_lossy().to_string())
            .collect();

        assert!(args_str.contains(&"--unshare-all".to_string()));
        assert!(!args_str.contains(&"--share-net".to_string()));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_bwrap_prefix_hidden_paths() {
        let config = ProcessSandboxConfig::new("/project").with_hidden("/home/user/.astrid");
        let prefix = config.build_bwrap_prefix();

        let args_str: Vec<String> = prefix
            .args
            .iter()
            .map(|a| a.to_string_lossy().to_string())
            .collect();

        // Find the tmpfs for hidden path (not the /tmp one)
        let tmpfs_positions: Vec<usize> = args_str
            .iter()
            .enumerate()
            .filter(|(_, a)| *a == "--tmpfs")
            .map(|(i, _)| i)
            .collect();

        assert!(
            tmpfs_positions.len() >= 2,
            "should have at least 2 tmpfs mounts"
        );
        let hidden_tmpfs_found = tmpfs_positions
            .iter()
            .any(|&i| args_str.get(i + 1) == Some(&"/home/user/.astrid".to_string()));
        assert!(hidden_tmpfs_found, "should have tmpfs for hidden path");
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_bwrap_prefix_extra_paths() {
        let config = ProcessSandboxConfig::new("/project")
            .with_extra_read("/data")
            .with_extra_write("/output");
        let prefix = config.build_bwrap_prefix();

        let args_str: Vec<String> = prefix
            .args
            .iter()
            .map(|a| a.to_string_lossy().to_string())
            .collect();

        // Extra writable path should have --bind
        let bind_positions: Vec<usize> = args_str
            .iter()
            .enumerate()
            .filter(|(_, a)| *a == "--bind")
            .map(|(i, _)| i)
            .collect();
        let has_output_bind = bind_positions
            .iter()
            .any(|&i| args_str.get(i + 1) == Some(&"/output".to_string()));
        assert!(has_output_bind, "should have --bind for extra write path");

        // extra_read_paths are NOT emitted as --ro-bind on Linux because
        // `--ro-bind / /` already covers all host paths. Verify they are
        // NOT redundantly added.
        let ro_positions: Vec<usize> = args_str
            .iter()
            .enumerate()
            .filter(|(_, a)| *a == "--ro-bind")
            .map(|(i, _)| i)
            .collect();
        let has_data_explicit = ro_positions
            .iter()
            .any(|&i| args_str.get(i + 1) == Some(&"/data".to_string()));
        assert!(
            !has_data_explicit,
            "extra_read_paths should NOT produce --ro-bind on Linux (covered by --ro-bind / /)"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_seatbelt_prefix_basic() {
        let config = ProcessSandboxConfig::new("/project");
        let prefix = config.build_seatbelt_prefix().unwrap();

        assert_eq!(prefix.program, OsString::from("sandbox-exec"));
        assert_eq!(prefix.args[0], OsString::from("-p"));

        // Profile is passed inline as the second arg
        let profile = prefix.args[1].to_string_lossy().to_string();

        assert!(profile.contains("(deny default)"));
        assert!(profile.contains("(allow network*)"));
        assert!(profile.contains(r#"(subpath "/project")"#));
        assert!(profile.contains("(allow process-exec*)"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_seatbelt_prefix_no_network() {
        let config = ProcessSandboxConfig::new("/project").with_network(false);
        let prefix = config.build_seatbelt_prefix().unwrap();

        let profile = prefix.args[1].to_string_lossy().to_string();
        assert!(!profile.contains("(allow network*)"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_seatbelt_prefix_extra_paths() {
        let config = ProcessSandboxConfig::new("/project")
            .with_extra_read("/data")
            .with_extra_write("/output");
        let prefix = config.build_seatbelt_prefix().unwrap();

        let profile = prefix.args[1].to_string_lossy().to_string();
        assert!(profile.contains(r#"(subpath "/data")"#));
        assert!(profile.contains(r#"(subpath "/output")"#));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_seatbelt_prefix_hidden_paths() {
        let config = ProcessSandboxConfig::new("/project").with_hidden("/Users/testuser/.astrid");
        let prefix = config.build_seatbelt_prefix().unwrap();

        let profile = prefix.args[1].to_string_lossy().to_string();
        assert!(
            profile.contains(r#"(deny file-read* (subpath "/Users/testuser/.astrid"))"#),
            "should deny file-read for hidden path"
        );
        assert!(
            profile.contains(r#"(deny file-write* (subpath "/Users/testuser/.astrid"))"#),
            "should deny file-write for hidden path"
        );
    }

    // --- Cross-platform sandbox_prefix() rejection tests ---
    // These are NOT gated by platform - sandbox_prefix() validates on all
    // platforms for API contract consistency.

    #[test]
    fn test_sandbox_prefix_rejects_relative_writable_root() {
        let config = ProcessSandboxConfig::new("relative/project");
        assert!(config.sandbox_prefix().is_err());
    }

    #[test]
    fn test_sandbox_prefix_rejects_non_utf8_writable_root() {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt;

        let bad_bytes: &[u8] = b"/tmp/\xff\xfe/workspace";
        let bad_path = PathBuf::from(OsStr::from_bytes(bad_bytes));
        let config = ProcessSandboxConfig::new(bad_path);
        let result = config.sandbox_prefix();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not valid UTF-8"));
    }

    #[test]
    fn test_sandbox_prefix_rejects_non_utf8_extra_paths() {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt;

        let bad_bytes: &[u8] = b"/data/\xff\xfe";
        let bad_path = PathBuf::from(OsStr::from_bytes(bad_bytes));

        // Non-UTF-8 in extra read path
        let config = ProcessSandboxConfig::new("/project").with_extra_read(bad_path.clone());
        assert!(config.sandbox_prefix().is_err());

        // Non-UTF-8 in extra write path
        let config = ProcessSandboxConfig::new("/project").with_extra_write(bad_path.clone());
        assert!(config.sandbox_prefix().is_err());

        // Non-UTF-8 in hidden path
        let config = ProcessSandboxConfig::new("/project").with_hidden(bad_path);
        assert!(config.sandbox_prefix().is_err());
    }

    #[test]
    fn test_sandbox_prefix_rejects_double_quote_in_paths() {
        // Double-quote in writable root
        let config = ProcessSandboxConfig::new("/project/evil\"dir");
        assert!(config.sandbox_prefix().is_err());

        // Double-quote in extra read path
        let config = ProcessSandboxConfig::new("/project").with_extra_read("/data/evil\"path");
        assert!(config.sandbox_prefix().is_err());

        // Double-quote in extra write path
        let config = ProcessSandboxConfig::new("/project").with_extra_write("/output/evil\"path");
        assert!(config.sandbox_prefix().is_err());

        // Double-quote in hidden path
        let config = ProcessSandboxConfig::new("/project").with_hidden("/hidden/evil\"path");
        assert!(config.sandbox_prefix().is_err());
    }

    #[test]
    fn test_sandbox_prefix_rejects_backslash_in_paths() {
        // Backslash in writable root
        let config = ProcessSandboxConfig::new("/project/evil\\dir");
        assert!(config.sandbox_prefix().is_err());

        // Backslash in extra read path
        let config = ProcessSandboxConfig::new("/project").with_extra_read("/data/evil\\path");
        assert!(config.sandbox_prefix().is_err());

        // Backslash in extra write path
        let config = ProcessSandboxConfig::new("/project").with_extra_write("/output/evil\\path");
        assert!(config.sandbox_prefix().is_err());

        // Backslash in hidden path
        let config = ProcessSandboxConfig::new("/project").with_hidden("/hidden/evil\\path");
        assert!(config.sandbox_prefix().is_err());
    }

    #[test]
    fn test_sandbox_prefix_rejects_null_byte_in_paths() {
        let config = ProcessSandboxConfig::new("/project/evil\0dir");
        assert!(config.sandbox_prefix().is_err());

        let config = ProcessSandboxConfig::new("/project").with_extra_read("/data/evil\0path");
        assert!(config.sandbox_prefix().is_err());

        let config = ProcessSandboxConfig::new("/project").with_extra_write("/output/evil\0path");
        assert!(config.sandbox_prefix().is_err());

        let config = ProcessSandboxConfig::new("/project").with_hidden("/hidden/evil\0path");
        assert!(config.sandbox_prefix().is_err());
    }
}