codewhale-tui 0.9.9

Terminal UI for open-source and open-weight coding models
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
//! Bubblewrap (bwrap) passthrough for Linux sandbox (#2184).
//!
//! Bubblewrap is a setuid-less container runtime used by Flatpak and other
//! projects. It creates a new mount namespace with configurable bind mounts,
//! providing filesystem isolation without requiring root privileges.
//!
//! # How it works
//!
//! When `/usr/bin/bwrap` is executable AND the top-level config key
//! `prefer_bwrap` is set to `true`, exec_shell commands are routed through
//! bwrap. The bwrap invocation looks like:
//!
//! ```text
//! bwrap \
//!   --unshare-all \
//!   --ro-bind / / \
//!   --dev /dev \
//!   --proc /proc \
//!   --tmpfs /tmp \
//!   --bind <writable-root> <writable-root> \
//!   --chdir <cwd> \
//!   -- <program> <args>
//! ```
//!
//! This creates a read-only view of the entire filesystem with write access
//! limited to the policy-derived writable roots. Policies that allow network
//! access add `--share-net` after `--unshare-all`. A private `/dev` and
//! `/proc` plus a tmpfs `/tmp` keep standard toolchain expectations working
//! (#5410); user-configured extra roots and device nodes append after them.
//!
//! # Important
//!
//! We do NOT vendor bwrap. The user must install it themselves:
//!
//! - Ubuntu/Debian: `apt install bubblewrap`
//! - Fedora: `dnf install bubblewrap`
//! - Arch: `pacman -S bubblewrap`
//!
//! If bwrap is not executable, Codewhale reports no Linux OS sandbox and runs
//! the command without an OS wrapper. It never labels that fallback as
//! sandboxed.

#[cfg(target_os = "linux")]
use super::policy::WritableRoot;
#[cfg(target_os = "linux")]
use std::collections::BTreeSet;
#[cfg(target_os = "linux")]
use std::path::{Path, PathBuf};

/// Crate-visible wrapper over [`existing_directory`] so the sandbox module's
/// `BwrapMountExtensions::resolve` applies the same canonicalize + is_dir
/// rule to user-configured read-only roots (#5410).
#[cfg(target_os = "linux")]
pub(crate) fn existing_directory_shim(path: &Path) -> Option<PathBuf> {
    existing_directory(path)
}

/// Canonical path to the bubblewrap binary.
#[cfg(target_os = "linux")]
pub const BWRAP_PATH: &str = "/usr/bin/bwrap";

/// Check if bubblewrap is installed and executable.
#[cfg(target_os = "linux")]
pub fn is_available() -> bool {
    is_executable(std::path::Path::new(BWRAP_PATH))
}

#[cfg(target_os = "linux")]
fn is_executable(path: &std::path::Path) -> bool {
    use std::os::unix::fs::PermissionsExt;

    std::fs::metadata(path)
        .is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
}

#[cfg(not(target_os = "linux"))]
pub fn is_available() -> bool {
    false
}

/// Build a bwrap command that wraps the given program and arguments.
///
/// The returned command vector is suitable for use as `ExecEnv.command` —
/// it replaces the normal program+args with a bwrap invocation that sets
/// up a read-only root filesystem with write access only to the specified
/// policy roots.
///
/// # Arguments
///
/// - `cwd` — working directory and sandbox chdir target
/// - `program` — the program to run inside the container
/// - `args` — arguments to pass to the program
/// - `writable_roots` — policy-derived directories to remount read-write
/// - `network_access` — whether to retain the caller's network namespace
/// - `extensions` — user-configured extra read-only roots and writable
///   device nodes (#5410); skipped when they do not exist on the host
///
/// # Returns
///
/// A `Vec<String>` representing the full bwrap invocation.
#[cfg(target_os = "linux")]
pub fn build_bwrap_command(
    cwd: &std::path::Path,
    program: &str,
    args: &[String],
    writable_roots: &[WritableRoot],
    network_access: bool,
    extensions: &crate::sandbox::BwrapMountExtensions,
) -> Vec<String> {
    let (writable_mounts, read_only_mounts) = safe_mounts(writable_roots);
    let (extra_read_only, device_mounts) = extensions.resolve();
    let mut cmd: Vec<String> =
        Vec::with_capacity(10 + args.len() + 3 * (writable_mounts.len() + read_only_mounts.len()));

    cmd.push(BWRAP_PATH.to_string());

    // Isolate every supported namespace by default. `--share-net` selectively
    // retains only the network namespace when the resolved policy allows it.
    cmd.push("--unshare-all".to_string());
    if network_access {
        cmd.push("--share-net".to_string());
    }

    // Read-only bind-mount the entire root filesystem.
    cmd.push("--ro-bind".to_string());
    cmd.push("/".to_string());
    cmd.push("/".to_string());

    // Standard container essentials (#5410): a private `/dev` (so device
    // nodes exist fresh and writable — `>/dev/null` under the read-only
    // root bind is EROFS without this), `/proc`, and a writable isolated
    // `/tmp` for toolchain scratch space.
    cmd.push("--dev".to_string());
    cmd.push("/dev".to_string());
    cmd.push("--proc".to_string());
    cmd.push("/proc".to_string());
    cmd.push("--tmpfs".to_string());
    cmd.push("/tmp".to_string());

    // User-configured writable device nodes (#5410), e.g. a host `/dev/null`
    // when the caller needs the host's, not the fresh private one.
    for device in device_mounts {
        let device = device.to_string_lossy().into_owned();
        cmd.push("--dev-bind".to_string());
        cmd.push(device.clone());
        cmd.push(device);
    }

    for root in writable_mounts {
        let root = root.to_string_lossy().into_owned();
        cmd.push("--bind".to_string());
        cmd.push(root.clone());
        cmd.push(root);
    }

    // Re-apply protected descendants after all writable parents so a broad
    // writable root cannot make .codewhale/.deepseek exceptions writable.
    for root in read_only_mounts {
        let root = root.to_string_lossy().into_owned();
        cmd.push("--ro-bind".to_string());
        cmd.push(root.clone());
        cmd.push(root);
    }

    // User-configured extra read-only roots (#5410) apply last so they can
    // narrow (re-mount read-only over) any earlier writable bind if the
    // user explicitly lists a path the policy made writable.
    for root in extra_read_only {
        let root = root.to_string_lossy().into_owned();
        cmd.push("--ro-bind".to_string());
        cmd.push(root.clone());
        cmd.push(root);
    }

    // Change to the working directory inside the container.
    let cwd_str = cwd.to_string_lossy().to_string();
    cmd.push("--chdir".to_string());
    cmd.push(cwd_str);

    // Separator between bwrap args and the command to run.
    cmd.push("--".to_string());

    // The actual program and its arguments.
    cmd.push(program.to_string());
    cmd.extend(args.iter().cloned());

    cmd
}

#[cfg(target_os = "linux")]
fn safe_mounts(writable_roots: &[WritableRoot]) -> (Vec<PathBuf>, Vec<PathBuf>) {
    let mut writable = BTreeSet::new();
    let mut read_only = BTreeSet::new();

    for root in writable_roots {
        let Some(canonical_root) = safe_existing_directory(&root.root) else {
            continue;
        };
        writable.insert(canonical_root.clone());

        for exception in &root.read_only_subpaths {
            let Some(canonical_exception) = existing_directory(exception) else {
                continue;
            };
            if canonical_exception.starts_with(&canonical_root) {
                read_only.insert(canonical_exception);
            }
        }
    }

    (
        writable.into_iter().collect(),
        read_only.into_iter().collect(),
    )
}

#[cfg(target_os = "linux")]
fn safe_existing_directory(path: &Path) -> Option<PathBuf> {
    let canonical = existing_directory(path)?;
    (canonical != Path::new("/")).then_some(canonical)
}

#[cfg(target_os = "linux")]
fn existing_directory(path: &Path) -> Option<PathBuf> {
    let canonical = path.canonicalize().ok()?;
    canonical.is_dir().then_some(canonical)
}

/// Detect a failure attributable to the bubblewrap boundary.
#[cfg(target_os = "linux")]
pub fn detect_denial(exit_code: i32, stderr: &str) -> bool {
    exit_code != 0
        && (stderr
            .lines()
            .any(|line| line.trim_start().starts_with("bwrap:"))
            || stderr.contains("Read-only file system"))
}

#[cfg(not(target_os = "linux"))]
pub fn detect_denial(_exit_code: i32, _stderr: &str) -> bool {
    false
}

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

    #[test]
    fn test_is_available_does_not_panic() {
        let _ = is_available();
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_build_bwrap_command_structure() {
        let dir = tempfile::tempdir().expect("tempdir");
        let cwd = dir.path();
        let cmd = build_bwrap_command(
            cwd,
            "sh",
            &["-c".to_string(), "echo hi".to_string()],
            &[WritableRoot::new(cwd.to_path_buf())],
            false,
            &crate::sandbox::BwrapMountExtensions::default(),
        );

        // Should start with bwrap
        assert_eq!(cmd[0], "/usr/bin/bwrap");

        // Should have ro-bind for root
        assert!(cmd.contains(&"--ro-bind".to_string()));

        // Standard container essentials (#5410): private /dev, /proc, tmpfs /tmp.
        assert!(cmd.contains(&"--dev".to_string()));
        assert!(cmd.contains(&"--proc".to_string()));
        assert!(cmd.contains(&"--tmpfs".to_string()));

        // Should have --chdir
        assert!(cmd.contains(&"--chdir".to_string()));

        // Network stays isolated unless the policy explicitly allows it.
        assert!(cmd.contains(&"--unshare-all".to_string()));
        assert!(!cmd.contains(&"--share-net".to_string()));

        // Should end with the command
        assert_eq!(cmd[cmd.len() - 1], "echo hi");
        assert_eq!(cmd[cmd.len() - 2], "-c");
        assert_eq!(cmd[cmd.len() - 3], "sh");
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn read_only_command_does_not_remount_the_working_directory_writable() {
        let dir = tempfile::tempdir().expect("tempdir");
        let cwd = dir.path();
        let cmd = build_bwrap_command(
            cwd,
            "true",
            &[],
            &[],
            false,
            &crate::sandbox::BwrapMountExtensions::default(),
        );

        assert!(!cmd.iter().any(|arg| arg == "--bind"));
        assert!(!cmd.iter().any(|arg| arg == "--share-net"));
        assert!(
            cmd.windows(2)
                .any(|args| args[0] == "--chdir" && args[1] == cwd.to_string_lossy())
        );
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn workspace_write_mounts_every_safe_root_and_protects_read_only_descendants() {
        let dir = tempfile::tempdir().expect("tempdir");
        let workspace = dir.path().join("workspace");
        let extra = dir.path().join("extra");
        let protected = workspace.join(".codewhale");
        std::fs::create_dir_all(&protected).expect("protected directory");
        std::fs::create_dir_all(&extra).expect("extra directory");

        let roots = vec![
            WritableRoot::with_exceptions(workspace.clone(), vec![protected.clone()]),
            WritableRoot::new(extra.clone()),
            WritableRoot::new(dir.path().join("missing")),
            WritableRoot::new(PathBuf::from("/")),
        ];
        let cmd = build_bwrap_command(
            &workspace,
            "true",
            &[],
            &roots,
            true,
            &crate::sandbox::BwrapMountExtensions::default(),
        );

        for root in [&workspace, &extra] {
            let canonical = root.canonicalize().expect("canonical root");
            assert!(has_mount(&cmd, "--bind", &canonical));
        }
        assert!(has_mount(
            &cmd,
            "--ro-bind",
            &protected.canonicalize().expect("canonical protected path")
        ));
        assert!(!has_mount(&cmd, "--bind", Path::new("/")));
        assert!(!cmd.iter().any(|arg| arg.ends_with("/missing")));

        let unshare = cmd
            .iter()
            .position(|arg| arg == "--unshare-all")
            .expect("unshare all");
        let share = cmd
            .iter()
            .position(|arg| arg == "--share-net")
            .expect("share net");
        assert!(share > unshare);
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn extensions_add_ro_roots_and_device_nodes_and_skip_invalid_entries() {
        let dir = tempfile::tempdir().expect("tempdir");
        let cwd = dir.path();
        let extra_ro = dir.path().join("vendor-libs");
        std::fs::create_dir_all(&extra_ro).expect("extra ro dir");

        let extensions = crate::sandbox::BwrapMountExtensions {
            read_only_roots: vec![
                extra_ro.clone(),
                dir.path().join("missing-ro"), // silently skipped
            ],
            device_roots: vec![
                // A real char device on every Linux host: /dev/null.
                PathBuf::from("/dev/null"),
                // Not a device: skipped even though it exists.
                extra_ro.clone(),
                // Missing: skipped.
                PathBuf::from("/dev/does-not-exist"),
            ],
        };
        let cmd = build_bwrap_command(cwd, "true", &[], &[], false, &extensions);

        assert!(has_mount(
            &cmd,
            "--ro-bind",
            &extra_ro.canonicalize().expect("canonical extra"),
        ));
        assert!(has_mount(
            &cmd,
            "--dev-bind",
            &PathBuf::from("/dev/null")
                .canonicalize()
                .expect("canonical null")
        ));
        // The non-device directory must never appear as a dev-bind — the key
        // is not a writable-root escape hatch.
        assert!(!cmd.iter().any(|arg| arg.ends_with("/missing-ro")));
        let dev_binds_of_extra = cmd
            .windows(3)
            .any(|args| args[0] == "--dev-bind" && args[1].as_str() == extra_ro.to_string_lossy());
        assert!(!dev_binds_of_extra, "directories must not be dev-bound");
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn extension_ro_roots_apply_after_writable_binds_so_they_can_narrow() {
        let dir = tempfile::tempdir().expect("tempdir");
        let workspace = dir.path().join("workspace");
        let narrowed = workspace.join("vendor-libs");
        std::fs::create_dir_all(&narrowed).expect("dirs");

        let roots = vec![WritableRoot::new(workspace.clone())];
        let extensions = crate::sandbox::BwrapMountExtensions {
            read_only_roots: vec![narrowed.clone()],
            device_roots: vec![],
        };
        let cmd = build_bwrap_command(&workspace, "true", &[], &roots, false, &extensions);

        let writable_pos = cmd
            .windows(3)
            .position(|args| {
                args[0] == "--bind"
                    && args[1].as_str() == workspace.canonicalize().unwrap().to_string_lossy()
            })
            .expect("workspace writable bind");
        let narrow_pos = cmd
            .windows(3)
            .position(|args| {
                args[0] == "--ro-bind"
                    && args[1].as_str() == narrowed.canonicalize().unwrap().to_string_lossy()
            })
            .expect("narrowed ro bind");
        assert!(
            narrow_pos > writable_pos,
            "extra ro roots must apply after writable binds so they can narrow them"
        );
    }

    #[cfg(target_os = "linux")]
    fn has_mount(command: &[String], flag: &str, path: &Path) -> bool {
        let path = path.to_string_lossy();
        command.windows(3).any(|args| {
            args[0] == flag
                && args[1].as_str() == path.as_ref()
                && args[2].as_str() == path.as_ref()
        })
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn executable_probe_requires_a_regular_executable_file() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("bwrap");
        std::fs::write(&path, b"fixture").expect("write fixture");
        assert!(!is_executable(&path));

        let mut permissions = std::fs::metadata(&path).expect("metadata").permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(&path, permissions).expect("set executable bit");
        assert!(is_executable(&path));
        assert!(!is_executable(dir.path()));
    }

    #[test]
    fn denial_detection_requires_a_failed_sandbox_signal() {
        assert!(!detect_denial(0, "bwrap: ignored on success"));
        #[cfg(target_os = "linux")]
        {
            assert!(detect_denial(1, "bwrap: Creating new namespace failed"));
            assert!(detect_denial(1, "Read-only file system"));
            assert!(!detect_denial(1, "child output mentions bwrap: casually"));
            assert!(!detect_denial(1, "Permission denied"));
            assert!(!detect_denial(1, "Operation not permitted"));
            assert!(!detect_denial(1, "ordinary command failure"));
        }
    }
}