rx4 0.6.5

The agent harness engine — loop, tools, providers, sessions, permissions, computer-use
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
use super::userspace::SandboxError;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Which OS-level sandbox backend to use for enforcement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OsSandbox {
    /// macOS sandbox-exec (seatbelt) enforcement.
    MacosSeatbelt,
    /// Linux bwrap (Bubblewrap) enforcement.
    LinuxBubblewrap,
    /// Fallback: userspace validation only (current behavior).
    UserspaceOnly,
}

/// Declarative configuration for an [`OsSandboxRunner`].
#[derive(Debug, Clone)]
pub struct OsSandboxConfig {
    /// Which sandbox backend to use.
    pub mode: OsSandbox,
    /// Workspace root that will be mounted read-write.
    pub workspace: PathBuf,
    /// Whether to allow network access inside the sandbox.
    pub allow_network: bool,
    /// Whether to allow read-write access to `/tmp`.
    pub allow_tmp: bool,
    /// Extra paths to bind mount read-only.
    pub extra_ro_paths: Vec<PathBuf>,
    /// Environment variables to pass through into the sandbox.
    pub env_whitelist: Vec<String>,
}

impl OsSandboxConfig {
    /// Build a config for the given `mode` rooted at `workspace`.
    pub fn new(mode: OsSandbox, workspace: PathBuf) -> Self {
        Self {
            mode,
            workspace,
            allow_network: false,
            allow_tmp: true,
            extra_ro_paths: Vec::new(),
            env_whitelist: ["PATH", "HOME", "USER", "LANG", "TERM"]
                .into_iter()
                .map(String::from)
                .collect(),
        }
    }
}

/// Generates macOS seatbelt sandbox profile (`.sb`) files.
#[derive(Debug, Clone)]
pub struct SandboxProfileGenerator {
    config: OsSandboxConfig,
}

impl SandboxProfileGenerator {
    /// Create a generator for the given config.
    pub fn new(config: OsSandboxConfig) -> Self {
        Self { config }
    }

    /// Render the seatbelt profile text for `config`.
    pub fn generate_seatbelt_profile(config: &OsSandboxConfig) -> String {
        let workspace = config.workspace.display().to_string();
        let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
        let mut lines: Vec<String> = Vec::new();
        lines.push("(version 1)".to_string());
        lines.push("(deny default)".to_string());
        lines.push("(allow process-exec)".to_string());
        lines.push("(allow process-fork)".to_string());
        lines.push(format!("(allow file-read* (subpath \"{workspace}\"))"));
        lines.push("(allow file-read* (subpath \"/usr\"))".to_string());
        lines.push("(allow file-read* (subpath \"/bin\"))".to_string());
        lines.push("(allow file-read* (subpath \"/sbin\"))".to_string());
        lines.push("(allow file-read* (subpath \"/opt\"))".to_string());
        lines.push("(allow file-read* (subpath \"/Library\"))".to_string());
        lines.push("(allow file-read* (subpath \"/System\"))".to_string());
        lines.push("(allow file-read* (subpath \"/private/var/db/dyld\"))".to_string());
        lines.push("(allow file-read* (literal \"/dev/null\"))".to_string());
        lines.push("(allow file-read* (literal \"/dev/urandom\"))".to_string());
        lines.push("(allow file-write* (literal \"/dev/null\"))".to_string());
        lines.push(format!("(allow file-write* (subpath \"{workspace}\"))"));
        if config.allow_tmp {
            lines.push("(allow file-read* (subpath \"/tmp\"))".to_string());
            lines.push("(allow file-read* (subpath \"/private/tmp\"))".to_string());
            lines.push("(allow file-read* (subpath \"/var/tmp\"))".to_string());
            lines.push("(allow file-write* (subpath \"/tmp\"))".to_string());
            lines.push("(allow file-write* (subpath \"/private/tmp\"))".to_string());
            lines.push("(allow file-write* (subpath \"/var/tmp\"))".to_string());
        }
        if config.allow_network {
            lines.push("(allow network*)".to_string());
        } else {
            lines.push("(deny network*)".to_string());
        }
        lines.push(format!(
            "(allow file-read* (literal \"{home}/.gitconfig\"))"
        ));
        lines.push(format!(
            "(allow file-read* (literal \"{home}/.gitignore_global\"))"
        ));
        lines.push(format!(
            "(allow file-read* (literal \"{home}/.config/git/config\"))"
        ));
        lines.push(format!(
            "(allow file-read* (literal \"{home}/.config/git/ignore\"))"
        ));
        for extra in &config.extra_ro_paths {
            lines.push(format!(
                "(allow file-read* (subpath \"{}\"))",
                extra.display()
            ));
        }
        lines.push(format!("(deny file-read* (subpath \"{home}/.ssh\"))"));
        lines.push(format!("(deny file-read* (subpath \"{home}/.aws\"))"));
        lines.push(format!(
            "(deny file-read* (subpath \"{home}/.config/gcloud\"))"
        ));
        lines.push(format!("(deny file-read* (subpath \"{home}/.netrc\"))"));
        lines.push(format!("(deny file-read* (subpath \"{home}/.gnupg\"))"));
        lines.join("\n") + "\n"
    }

    /// Write the profile to `dir/rx4-sandbox-{uuid}.sb` and return the path.
    pub fn write_profile(&self, dir: &Path) -> Result<PathBuf, SandboxError> {
        let contents = Self::generate_seatbelt_profile(&self.config);
        let id = uuid::Uuid::new_v4();
        let path = dir.join(format!("rx4-sandbox-{id}.sb"));
        std::fs::write(&path, contents).map_err(|e| SandboxError::PathDenied(e.to_string()))?;
        Ok(path)
    }
}

/// Executes commands within an OS-level sandbox.
#[derive(Debug, Clone)]
pub struct OsSandboxRunner {
    pub(crate) config: OsSandboxConfig,
    /// Path to the written seatbelt profile (macOS only).
    pub(crate) profile_path: Option<Arc<PathBuf>>,
}

impl Drop for OsSandboxRunner {
    fn drop(&mut self) {
        if let Some(path) = self.profile_path.take() {
            if Arc::strong_count(&path) == 1 {
                let _ = std::fs::remove_file(path.as_path());
            }
        }
    }
}

impl OsSandboxRunner {
    /// Create a runner for the given config. On macOS this writes the
    /// seatbelt profile to `/tmp` so that [`Self::wrap_command`] can refer
    /// to it.
    pub fn new(config: OsSandboxConfig) -> Result<Self, SandboxError> {
        let profile_path = match config.mode {
            OsSandbox::MacosSeatbelt => {
                #[cfg(not(target_os = "macos"))]
                return Err(SandboxError::PathDenied(
                    "macOS seatbelt (sandbox-exec) not available; refuse fail-open".into(),
                ));

                #[cfg(target_os = "macos")]
                {
                    if !has_seatbelt() {
                        return Err(SandboxError::PathDenied(
                            "macOS seatbelt (sandbox-exec) not available; refuse fail-open".into(),
                        ));
                    }
                    let gen = SandboxProfileGenerator::new(config.clone());
                    let dir = if config.allow_tmp {
                        PathBuf::from("/tmp")
                    } else {
                        std::env::temp_dir()
                    };
                    Some(gen.write_profile(&dir)?)
                }
            }
            OsSandbox::LinuxBubblewrap => {
                if !has_bubblewrap() {
                    return Err(SandboxError::PathDenied(
                        "Linux bwrap not available; refuse fail-open".into(),
                    ));
                }
                None
            }
            OsSandbox::UserspaceOnly => None,
        };
        Ok(Self {
            config,
            profile_path: profile_path.map(Arc::new),
        })
    }

    /// Detect which sandbox backend is available on the current system.
    pub fn is_available() -> OsSandbox {
        detect_sandbox()
    }

    /// Return the active sandbox mode.
    pub fn mode(&self) -> OsSandbox {
        self.config.mode
    }

    pub fn config(&self) -> &OsSandboxConfig {
        &self.config
    }

    /// Return the full command vector with the sandbox wrapper prepended.
    pub fn wrap_command(&self, cmd: &str, args: &[&str]) -> Vec<String> {
        match self.config.mode {
            OsSandbox::MacosSeatbelt => {
                let profile = self
                    .profile_path
                    .as_ref()
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|| "/tmp/rx4-sandbox.sb".to_string());
                let mut v: Vec<String> = vec![
                    "sandbox-exec".to_string(),
                    "-f".to_string(),
                    profile,
                    "--".to_string(),
                    cmd.to_string(),
                ];
                v.extend(args.iter().map(|a| a.to_string()));
                v
            }
            OsSandbox::LinuxBubblewrap => {
                let workspace = self.config.workspace.display().to_string();
                // Private-by-default: mount only essential system paths + workspace.
                // Do NOT bind host root — that would expose all of /home, /root, etc.
                let mut v: Vec<String> = vec![
                    "bwrap".to_string(),
                    // Essential runtime directories read-only.
                    "--ro-bind".to_string(),
                    "/usr".to_string(),
                    "/usr".to_string(),
                    "--ro-bind".to_string(),
                    "/lib".to_string(),
                    "/lib".to_string(),
                    "--ro-bind".to_string(),
                    "/lib64".to_string(),
                    "/lib64".to_string(),
                    "--ro-bind".to_string(),
                    "/bin".to_string(),
                    "/bin".to_string(),
                    "--ro-bind".to_string(),
                    "/sbin".to_string(),
                    "/sbin".to_string(),
                    "--ro-bind".to_string(),
                    "/etc".to_string(),
                    "/etc".to_string(),
                    // Device and process filesystems.
                    "--dev".to_string(),
                    "/dev".to_string(),
                    "--proc".to_string(),
                    "/proc".to_string(),
                    // Temp storage.
                    "--tmpfs".to_string(),
                    "/tmp".to_string(),
                    // Workspace mounted read-write.
                    "--bind".to_string(),
                    workspace.clone(),
                    workspace,
                ];
                for extra in &self.config.extra_ro_paths {
                    let p = extra.display().to_string();
                    v.push("--ro-bind".to_string());
                    v.push(p.clone());
                    v.push(p);
                }
                v.push("--unshare-all".to_string());
                if self.config.allow_network {
                    v.push("--share-net".to_string());
                }
                v.push("--clearenv".to_string());
                for name in &self.config.env_whitelist {
                    if let Ok(value) = std::env::var(name) {
                        v.push("--setenv".to_string());
                        v.push(name.clone());
                        v.push(value);
                    }
                }
                v.push("--".to_string());
                v.push(cmd.to_string());
                v.extend(args.iter().map(|a| a.to_string()));
                v
            }
            OsSandbox::UserspaceOnly => {
                let mut v: Vec<String> = vec![cmd.to_string()];
                v.extend(args.iter().map(|a| a.to_string()));
                v
            }
        }
    }

    /// Build a [`std::process::Command`] with the sandbox wrapper applied.
    pub fn command(&self, cmd: &str, args: &[&str]) -> Result<std::process::Command, SandboxError> {
        let wrapped = self.wrap_command(cmd, args);
        if wrapped.is_empty() {
            return Err(SandboxError::CommandDenied(
                "empty sandbox command".to_string(),
            ));
        }
        let mut command = std::process::Command::new(&wrapped[0]);
        for arg in &wrapped[1..] {
            command.arg(arg);
        }
        Ok(command)
    }
}

/// Returns true if `bwrap` (Bubblewrap) is available in `PATH`.
pub fn has_bubblewrap() -> bool {
    find_in_path("bwrap", std::env::var("PATH").unwrap_or_default())
}

/// Returns true if `sandbox-exec` (seatbelt) is available. Always true on
/// macOS.
#[cfg(target_os = "macos")]
pub fn has_seatbelt() -> bool {
    true
}

/// Detect the best available sandbox backend for the current platform.
pub fn detect_sandbox() -> OsSandbox {
    #[cfg(target_os = "macos")]
    {
        if has_seatbelt() {
            return OsSandbox::MacosSeatbelt;
        }
    }
    #[cfg(target_os = "linux")]
    {
        if has_bubblewrap() {
            return OsSandbox::LinuxBubblewrap;
        }
    }
    let _ = has_bubblewrap();
    OsSandbox::UserspaceOnly
}

#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
}

#[cfg(not(unix))]
fn is_executable(path: &Path) -> bool {
    path.is_file()
}

fn find_in_path<P: AsRef<std::ffi::OsStr>>(name: &str, path: P) -> bool {
    for dir in std::env::split_paths(path.as_ref()) {
        if is_executable(&dir.join(name)) {
            return true;
        }
    }
    false
}

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

    #[test]
    fn test_detect_sandbox_returns_valid_mode() {
        let mode = detect_sandbox();
        assert!(matches!(
            mode,
            OsSandbox::MacosSeatbelt | OsSandbox::LinuxBubblewrap | OsSandbox::UserspaceOnly
        ));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_detect_sandbox_macos() {
        if has_seatbelt() {
            assert_eq!(detect_sandbox(), OsSandbox::MacosSeatbelt);
        } else {
            assert_eq!(detect_sandbox(), OsSandbox::UserspaceOnly);
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_detect_sandbox_linux() {
        if has_bubblewrap() {
            assert_eq!(detect_sandbox(), OsSandbox::LinuxBubblewrap);
        } else {
            assert_eq!(detect_sandbox(), OsSandbox::UserspaceOnly);
        }
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    #[test]
    fn test_detect_sandbox_other_platforms() {
        assert_eq!(detect_sandbox(), OsSandbox::UserspaceOnly);
    }

    #[test]
    fn test_has_bubblewrap() {
        has_bubblewrap();
    }

    #[test]
    fn test_find_in_path_found() {
        let temp_dir = tempfile::tempdir().unwrap();
        let bwrap_path = temp_dir.path().join("bwrap");
        std::fs::write(&bwrap_path, "").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&bwrap_path, std::fs::Permissions::from_mode(0o755)).unwrap();
        }

        let path = temp_dir.path().to_string_lossy().into_owned();
        assert!(find_in_path("bwrap", &path));
    }

    #[test]
    fn test_find_in_path_not_found() {
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().to_string_lossy().into_owned();
        assert!(!find_in_path("bwrap", &path));
    }

    #[test]
    fn test_find_in_path_is_dir() {
        let temp_dir = tempfile::tempdir().unwrap();
        let bwrap_path = temp_dir.path().join("bwrap");
        std::fs::create_dir(&bwrap_path).unwrap();

        let path = temp_dir.path().to_string_lossy().into_owned();
        assert!(!find_in_path("bwrap", &path));
    }

    #[test]
    fn test_find_in_path_empty_path() {
        assert!(!find_in_path("bwrap", ""));
    }

    #[test]
    fn test_find_in_path_multiple_paths() {
        let temp_dir1 = tempfile::tempdir().unwrap();
        let temp_dir2 = tempfile::tempdir().unwrap();
        let temp_dir3 = tempfile::tempdir().unwrap();

        // Put bwrap in the second directory
        let bwrap_path = temp_dir2.path().join("bwrap");
        std::fs::write(&bwrap_path, "").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&bwrap_path, std::fs::Permissions::from_mode(0o755)).unwrap();
        }

        let paths = vec![
            temp_dir1.path().to_path_buf(),
            temp_dir2.path().to_path_buf(),
            temp_dir3.path().to_path_buf(),
        ];

        let new_path = std::env::join_paths(paths).unwrap();
        assert!(find_in_path("bwrap", &new_path));
    }

    #[test]
    #[cfg(unix)]
    fn test_find_in_path_not_executable() {
        let temp_dir = tempfile::tempdir().unwrap();
        let bwrap_path = temp_dir.path().join("bwrap");
        std::fs::write(&bwrap_path, "").unwrap();
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&bwrap_path, std::fs::Permissions::from_mode(0o644)).unwrap();
        }

        let path = temp_dir.path().to_string_lossy().into_owned();
        assert!(!find_in_path("bwrap", &path));
    }
}