clash 0.5.2

Command Line Agent Safety Harness — permission policies for coding agents
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
//! Sandbox enforcement backends.
//!
//! Each platform implements `exec_sandboxed` which applies kernel-enforced
//! restrictions and then execs the target command. The restrictions are
//! inherited by all child processes and cannot be removed.
//!
//! The `SandboxBackend` trait abstracts over platform-specific enforcement,
//! enabling a `MockSandbox` for testing without kernel features.

use std::path::Path;

use crate::policy::sandbox_types::{NetworkPolicy, SandboxPolicy};
use tracing::{Level, info, instrument};

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
pub mod proxy;

/// Result of checking platform sandbox support.
#[derive(Debug)]
pub enum SupportLevel {
    /// All policy features are supported.
    Full,
    /// Some features are missing (e.g., network filtering on older kernels).
    Partial { missing: Vec<String> },
    /// Sandbox not supported on this platform/kernel.
    Unsupported { reason: String },
}

/// Error during sandbox setup or execution.
#[derive(Debug, thiserror::Error)]
pub enum SandboxError {
    #[error("sandbox not supported: {0}")]
    Unsupported(String),
    #[error("failed to apply sandbox: {0}")]
    Apply(String),
    #[error("failed to exec command: {0}")]
    Exec(#[from] std::io::Error),
}

/// Trait abstracting over sandbox enforcement backends.
///
/// Platform implementations (Linux/Landlock, macOS/Seatbelt) use kernel
/// mechanisms and replace the process. The `MockSandbox` records the
/// policy and command for testing without kernel features.
pub trait SandboxBackend {
    /// Apply the sandbox policy and exec the command.
    ///
    /// For real backends, this replaces the process and never returns on success.
    /// For mock backends, this records the call and returns Ok(()).
    fn apply_and_exec(
        &self,
        policy: &SandboxPolicy,
        cwd: &Path,
        command: &[String],
        trace_path: Option<&Path>,
    ) -> Result<(), SandboxError>;

    /// Check whether this backend is supported.
    fn check_support(&self) -> SupportLevel;
}

/// A mock sandbox backend that records policy applications for testing.
///
/// Instead of applying kernel-level restrictions, it records what would
/// have been enforced, allowing unit tests to verify sandbox policy
/// generation without requiring root or kernel features.
#[cfg(test)]
pub struct MockSandbox {
    /// Recorded sandbox applications: (policy, cwd, command).
    pub applications: std::cell::RefCell<Vec<MockApplication>>,
    /// What support level to report.
    pub support: SupportLevel,
}

/// A recorded sandbox application.
#[cfg(test)]
#[derive(Debug, Clone)]
pub struct MockApplication {
    pub policy: SandboxPolicy,
    pub cwd: String,
    pub command: Vec<String>,
}

#[cfg(test)]
impl MockSandbox {
    pub fn new() -> Self {
        Self {
            applications: std::cell::RefCell::new(Vec::new()),
            support: SupportLevel::Full,
        }
    }

    pub fn with_support(mut self, support: SupportLevel) -> Self {
        self.support = support;
        self
    }

    pub fn applications(&self) -> Vec<MockApplication> {
        self.applications.borrow().clone()
    }
}

#[cfg(test)]
impl SandboxBackend for MockSandbox {
    fn apply_and_exec(
        &self,
        policy: &SandboxPolicy,
        cwd: &Path,
        command: &[String],
        _trace_path: Option<&Path>,
    ) -> Result<(), SandboxError> {
        self.applications.borrow_mut().push(MockApplication {
            policy: policy.clone(),
            cwd: cwd.to_string_lossy().into_owned(),
            command: command.to_vec(),
        });
        Ok(())
    }

    fn check_support(&self) -> SupportLevel {
        // Return Full since we can't move out of &self
        SupportLevel::Full
    }
}

/// Apply the sandbox policy and exec the command.
///
/// This function does not return on success — it replaces the current
/// process with the target command via `execvp`.
///
/// If `trace_path` is provided, sandbox violations are logged to that file.
/// On macOS this uses `sandbox-exec -t`; on Linux it is ignored (Landlock
/// has no built-in trace mechanism).
#[instrument(level = Level::TRACE, skip(policy))]
pub fn exec_sandboxed(
    policy: &SandboxPolicy,
    cwd: &Path,
    command: &[String],
    trace_path: Option<&Path>,
) -> Result<std::convert::Infallible, SandboxError> {
    if command.is_empty() {
        return Err(SandboxError::Apply("no command specified".into()));
    }

    let policy = &policy.expand_worktree_rules(cwd);

    #[cfg(target_os = "linux")]
    {
        // Landlock has no trace mechanism — ignore trace_path.
        let _ = trace_path;
        linux::exec_sandboxed(policy, cwd, command)
    }

    #[cfg(target_os = "macos")]
    {
        macos::exec_sandboxed(policy, cwd, command, trace_path)
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        let _ = trace_path;
        Err(SandboxError::Unsupported(
            "sandbox only supported on Linux and macOS".into(),
        ))
    }
}

/// Compile a sandbox policy into a platform-specific profile string.
///
/// On macOS, returns an SBPL profile suitable for `sandbox-exec -p`.
/// On Linux, returns a description string (Landlock is applied in-process, not via a profile).
/// On unsupported platforms, returns an error.
pub fn compile_sandbox_profile(policy: &SandboxPolicy, cwd: &Path) -> Result<String, SandboxError> {
    let policy = &policy.expand_worktree_rules(cwd);
    let cwd_str = cwd.to_string_lossy();

    #[cfg(target_os = "macos")]
    {
        Ok(macos::compile_to_sbpl(policy, &cwd_str))
    }

    #[cfg(target_os = "linux")]
    {
        let _ = (policy, &cwd_str);
        Err(SandboxError::Unsupported(
            "sandbox profile compilation not supported on Linux (Landlock is applied in-process)"
                .into(),
        ))
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        let _ = (policy, &cwd_str);
        Err(SandboxError::Unsupported(
            "sandbox only supported on Linux and macOS".into(),
        ))
    }
}

/// Spawn an interactive shell under the sandbox policy.
///
/// On macOS, uses `sandbox-exec -p <profile> -- /bin/bash -i`.
/// If the policy uses `AllowDomains`, a local HTTP proxy is started for
/// domain-level filtering and `HTTP_PROXY`/`HTTPS_PROXY` env vars are set.
/// Returns when the shell exits.
pub fn spawn_sandboxed_shell(
    policy: &SandboxPolicy,
    cwd: &Path,
) -> Result<std::process::ExitStatus, SandboxError> {
    let profile = compile_sandbox_profile(policy, cwd)?;

    // Start domain-filtering proxy if needed. The handle keeps it alive
    // until the shell exits; dropping it shuts down the proxy.
    let _proxy_handle = maybe_start_proxy(&policy.network)?;

    #[cfg(target_os = "macos")]
    {
        let mut cmd = std::process::Command::new("sandbox-exec");
        cmd.args(["-p", &profile, "--", "/bin/bash", "-i"])
            .current_dir(cwd)
            .stdin(std::process::Stdio::inherit())
            .stdout(std::process::Stdio::inherit())
            .stderr(std::process::Stdio::inherit());

        if let Some(ref handle) = _proxy_handle {
            set_proxy_env(&mut cmd, handle.addr);
        }

        let status = cmd.status().map_err(SandboxError::Exec)?;
        Ok(status)
    }

    #[cfg(not(target_os = "macos"))]
    {
        let _ = profile;
        Err(SandboxError::Unsupported(
            "interactive sandboxed shell only supported on macOS".into(),
        ))
    }
}

/// Start a domain-filtering proxy if the network policy is `AllowDomains`.
/// Returns `None` for `Deny` or `Allow` (no proxy needed).
fn maybe_start_proxy(network: &NetworkPolicy) -> Result<Option<proxy::ProxyHandle>, SandboxError> {
    match network {
        NetworkPolicy::AllowDomains(domains) => {
            let config = proxy::ProxyConfig {
                allowed_domains: domains.clone(),
            };
            let handle = proxy::start_proxy(config)
                .map_err(|e| SandboxError::Apply(format!("failed to start proxy: {}", e)))?;
            info!(addr = %handle.addr, domains = ?domains, "started domain-filtering proxy");
            Ok(Some(handle))
        }
        _ => Ok(None),
    }
}

/// Set `HTTP_PROXY` / `HTTPS_PROXY` env vars on a `Command` so the sandboxed
/// process routes traffic through the domain-filtering proxy.
#[cfg(target_os = "macos")]
fn set_proxy_env(cmd: &mut std::process::Command, addr: std::net::SocketAddr) {
    let proxy_url = format!("http://{}", addr);
    cmd.env("HTTP_PROXY", &proxy_url)
        .env("HTTPS_PROXY", &proxy_url)
        .env("http_proxy", &proxy_url)
        .env("https_proxy", &proxy_url);
}

/// Check whether sandboxing is supported on the current platform.
#[instrument(level = Level::TRACE)]
pub fn check_support() -> SupportLevel {
    #[cfg(target_os = "linux")]
    {
        linux::check_support()
    }

    #[cfg(target_os = "macos")]
    {
        macos::check_support()
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        SupportLevel::Unsupported {
            reason: "sandbox only supported on Linux and macOS".into(),
        }
    }
}

/// Exec a command (without sandbox), replacing the current process.
/// Used as the final step after sandbox setup.
#[instrument(level = Level::TRACE)]
pub(crate) fn do_exec(command: &[String]) -> Result<std::convert::Infallible, SandboxError> {
    use std::ffi::CString;

    let c_command = CString::new(command[0].as_str())
        .map_err(|e| SandboxError::Apply(format!("invalid command: {}", e)))?;
    let c_args: Vec<CString> = command
        .iter()
        .map(|arg| CString::new(arg.as_str()))
        .collect::<Result<_, _>>()
        .map_err(|e| SandboxError::Apply(format!("invalid argument: {}", e)))?;
    let c_args_ptrs: Vec<*const libc::c_char> = c_args
        .iter()
        .map(|arg| arg.as_ptr())
        .chain(std::iter::once(std::ptr::null()))
        .collect();

    unsafe {
        libc::execvp(c_command.as_ptr(), c_args_ptrs.as_ptr());
    }

    // execvp only returns on error
    Err(SandboxError::Exec(std::io::Error::last_os_error()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policy::sandbox_types::{Cap, NetworkPolicy, PathMatch, RuleEffect, SandboxRule};

    fn simple_policy() -> SandboxPolicy {
        SandboxPolicy {
            default: Cap::READ | Cap::EXECUTE,
            rules: vec![
                SandboxRule {
                    effect: RuleEffect::Allow,
                    caps: Cap::all(),
                    path: "/tmp".into(),
                    path_match: PathMatch::Subpath,
                    follow_worktrees: false,
                    doc: None,
                },
                SandboxRule {
                    effect: RuleEffect::Deny,
                    caps: Cap::READ,
                    path: "/etc/shadow".into(),
                    path_match: PathMatch::Literal,
                    follow_worktrees: false,
                    doc: None,
                },
            ],
            network: NetworkPolicy::Deny,
            doc: None,
        }
    }

    #[test]
    fn mock_sandbox_records_applications() {
        let mock = MockSandbox::new();
        let policy = simple_policy();
        let cwd = Path::new("/home/user");
        let command = vec!["ls".into(), "-la".into()];

        mock.apply_and_exec(&policy, cwd, &command, None).unwrap();

        let apps = mock.applications();
        assert_eq!(apps.len(), 1);
        assert_eq!(apps[0].cwd, "/home/user");
        assert_eq!(apps[0].command, vec!["ls", "-la"]);
        assert_eq!(apps[0].policy.network, NetworkPolicy::Deny);
        assert_eq!(apps[0].policy.rules.len(), 2);
    }

    #[test]
    fn mock_sandbox_records_multiple_applications() {
        let mock = MockSandbox::new();
        let policy = simple_policy();

        mock.apply_and_exec(&policy, Path::new("/a"), &["cmd1".into()], None)
            .unwrap();
        mock.apply_and_exec(&policy, Path::new("/b"), &["cmd2".into()], None)
            .unwrap();

        let apps = mock.applications();
        assert_eq!(apps.len(), 2);
        assert_eq!(apps[0].cwd, "/a");
        assert_eq!(apps[1].cwd, "/b");
    }

    #[test]
    fn mock_sandbox_reports_full_support() {
        let mock = MockSandbox::new();
        assert!(matches!(mock.check_support(), SupportLevel::Full));
    }

    #[test]
    fn effective_caps_default_only() {
        let policy = SandboxPolicy {
            default: Cap::READ | Cap::EXECUTE,
            rules: vec![],
            network: NetworkPolicy::Allow,
            doc: None,
        };
        let caps = policy.effective_caps("/any/path", "/cwd");
        assert_eq!(caps, Cap::READ | Cap::EXECUTE);
    }

    #[test]
    fn effective_caps_allow_rule() {
        let policy = SandboxPolicy {
            default: Cap::READ,
            rules: vec![SandboxRule {
                effect: RuleEffect::Allow,
                caps: Cap::WRITE,
                path: "/tmp".into(),
                path_match: PathMatch::Subpath,
                follow_worktrees: false,
                doc: None,
            }],
            network: NetworkPolicy::Allow,
            doc: None,
        };
        let caps = policy.effective_caps("/tmp/file.txt", "/cwd");
        assert_eq!(caps, Cap::READ | Cap::WRITE);
    }

    #[test]
    fn effective_caps_deny_overrides_allow() {
        let policy = SandboxPolicy {
            default: Cap::all(),
            rules: vec![SandboxRule {
                effect: RuleEffect::Deny,
                caps: Cap::WRITE | Cap::DELETE,
                path: "/etc".into(),
                path_match: PathMatch::Subpath,
                follow_worktrees: false,
                doc: None,
            }],
            network: NetworkPolicy::Allow,
            doc: None,
        };
        let caps = policy.effective_caps("/etc/passwd", "/cwd");
        // All caps minus WRITE and DELETE
        assert!(caps.contains(Cap::READ));
        assert!(caps.contains(Cap::EXECUTE));
        assert!(!caps.contains(Cap::WRITE));
        assert!(!caps.contains(Cap::DELETE));
    }

    #[test]
    fn effective_caps_deny_overrides_default_and_allow() {
        let policy = SandboxPolicy {
            default: Cap::READ,
            rules: vec![
                SandboxRule {
                    effect: RuleEffect::Allow,
                    caps: Cap::WRITE,
                    path: "/data".into(),
                    path_match: PathMatch::Subpath,
                    follow_worktrees: false,
                    doc: None,
                },
                SandboxRule {
                    effect: RuleEffect::Deny,
                    caps: Cap::WRITE,
                    path: "/data/readonly".into(),
                    path_match: PathMatch::Subpath,
                    follow_worktrees: false,
                    doc: None,
                },
            ],
            network: NetworkPolicy::Allow,
            doc: None,
        };
        // /data/file.txt: default READ + allow WRITE = READ | WRITE
        assert_eq!(
            policy.effective_caps("/data/file.txt", "/cwd"),
            Cap::READ | Cap::WRITE
        );
        // /data/readonly/file.txt: deny WRITE overrides allow WRITE
        assert_eq!(
            policy.effective_caps("/data/readonly/file.txt", "/cwd"),
            Cap::READ
        );
    }

    #[test]
    fn effective_caps_literal_match() {
        let policy = SandboxPolicy {
            default: Cap::READ,
            rules: vec![SandboxRule {
                effect: RuleEffect::Deny,
                caps: Cap::READ,
                path: "/secret.key".into(),
                path_match: PathMatch::Literal,
                follow_worktrees: false,
                doc: None,
            }],
            network: NetworkPolicy::Allow,
            doc: None,
        };
        // Exact match → denied
        assert_eq!(policy.effective_caps("/secret.key", "/cwd"), Cap::empty());
        // Non-match → default
        assert_eq!(policy.effective_caps("/secret.key.bak", "/cwd"), Cap::READ);
    }

    #[test]
    fn effective_caps_no_match_uses_default() {
        let policy = SandboxPolicy {
            default: Cap::READ | Cap::EXECUTE,
            rules: vec![SandboxRule {
                effect: RuleEffect::Allow,
                caps: Cap::all(),
                path: "/tmp".into(),
                path_match: PathMatch::Subpath,
                follow_worktrees: false,
                doc: None,
            }],
            network: NetworkPolicy::Allow,
            doc: None,
        };
        // Path outside /tmp → only default caps
        assert_eq!(
            policy.effective_caps("/home/user/file", "/cwd"),
            Cap::READ | Cap::EXECUTE
        );
    }
}