adk-sandbox 2.3.0

Isolated code execution runtime for ADK 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
//! Linux bubblewrap sandbox enforcer.
//!
//! Uses `bwrap` with user namespaces to create isolated filesystem and
//! process environments without requiring root privileges.
//!
//! ## How It Works
//!
//! 1. Bubblewrap arguments are generated from the [`SandboxPolicy`]
//! 2. The original command is wrapped: `bwrap <args> -- <program> <args...>`
//! 3. The kernel enforces namespace-based isolation on the child process
//!
//! ## Key bwrap Arguments
//!
//! - `--die-with-parent` — kill child when parent exits
//! - `--unshare-pid` — isolate process ID namespace
//! - `--unshare-net` — isolate network namespace (no network access)
//! - `--ro-bind <src> <dest>` — read-only filesystem bind mount
//! - `--bind <src> <dest>` — read-write filesystem bind mount
//! - `--new-session` — new session, so the child cannot inject input into the caller's terminal
//! - `--seccomp <fd>` — seccomp program that denies process creation
//!
//! ## Process Spawning
//!
//! When `allow_process_spawn` is `false`, the wrapped program runs under a seccomp filter
//! that fails `fork`, `vfork`, and non-thread `clone` with `EPERM` and `clone3` with
//! `ENOSYS`. Threads and `execve` keep working. The filter is generated for x86-64 and
//! AArch64; on any other architecture [`SandboxEnforcer::configure_command`] returns
//! `EnforcerFailed` rather than running without it.
//!
//! The filter reaches bubblewrap as file descriptor [`SECCOMP_FD`], which
//! [`SandboxEnforcer::configure_command`] installs on the command. Running the output of
//! [`LinuxEnforcer::generate_args`] without that call makes bubblewrap exit with an error.

use std::ffi::{OsStr, OsString};

use super::seccomp;
use super::{AccessMode, AllowedPath, SandboxEnforcer, SandboxPolicy, WrappedCommand};
use crate::error::SandboxError;

/// File descriptor bubblewrap reads the process-creation seccomp program from.
///
/// High enough to stay clear of stdio and the descriptors the standard library uses while
/// spawning, and below every default `RLIMIT_NOFILE`.
pub const SECCOMP_FD: i32 = 64;

/// Linux bubblewrap sandbox enforcer.
///
/// Wraps child processes with `bwrap` arguments to enforce namespace-based
/// filesystem, network, and process isolation.
///
/// # Example
///
/// ```rust,ignore
/// use adk_sandbox::sandbox::linux::LinuxEnforcer;
/// use adk_sandbox::sandbox::{SandboxEnforcer, SandboxPolicyBuilder};
/// use std::ffi::OsString;
///
/// let enforcer = LinuxEnforcer::new();
/// enforcer.probe()?;
///
/// let policy = SandboxPolicyBuilder::new()
///     .allow_read("/usr/lib")
///     .allow_read_write("/tmp/work")
///     .build();
///
/// let wrapped = enforcer.wrap_command(
///     "python3".as_ref(),
///     &[OsString::from("-c"), OsString::from("print('hello')")],
///     &policy,
/// )?;
/// // wrapped.program == "bwrap"
/// // wrapped.args == ["--die-with-parent", "--unshare-pid", "--unshare-net",
/// //                   "--new-session", "--seccomp", "64",
/// //                   "--ro-bind", "/usr/lib", "/usr/lib",
/// //                   "--bind", "/tmp/work", "/tmp/work",
/// //                   "--", "python3", "-c", "print('hello')"]
/// // `configure_command` must then be applied to the command built from `wrapped`.
/// ```
pub struct LinuxEnforcer;

impl LinuxEnforcer {
    /// Creates a new Linux bubblewrap enforcer.
    pub fn new() -> Self {
        Self
    }

    /// Generates bubblewrap arguments from the policy.
    ///
    /// Always starts with `--die-with-parent` and `--unshare-pid`.
    /// The returned arguments do NOT include the `--` separator or the
    /// original program/args — those are appended by `wrap_command`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_sandbox::sandbox::linux::LinuxEnforcer;
    /// use adk_sandbox::sandbox::SandboxPolicyBuilder;
    ///
    /// let policy = SandboxPolicyBuilder::new()
    ///     .allow_read("/usr/lib")
    ///     .build();
    ///
    /// let args = LinuxEnforcer::generate_args(&policy);
    /// assert_eq!(args[0], "--die-with-parent");
    /// assert_eq!(args[1], "--unshare-pid");
    /// assert!(args.contains(&"--unshare-net".to_string()));
    /// ```
    pub fn generate_args(policy: &SandboxPolicy) -> Vec<String> {
        Self::generate_args_from_paths(
            &policy.allowed_paths,
            policy.allow_network,
            policy.allow_process_spawn,
        )
    }

    /// Internal: generates args from pre-canonicalized paths.
    fn generate_args_from_paths(
        paths: &[AllowedPath],
        allow_network: bool,
        allow_process_spawn: bool,
    ) -> Vec<String> {
        let mut args = Vec::with_capacity(16);

        // Always: terminate child when parent exits
        args.push("--die-with-parent".to_string());

        // Always: isolate PID namespace
        args.push("--unshare-pid".to_string());

        // Network isolation
        if !allow_network {
            args.push("--unshare-net".to_string());
        }

        // Process spawn restriction: the seccomp program is what denies fork and clone.
        if !allow_process_spawn {
            args.push("--new-session".to_string());
            args.push("--seccomp".to_string());
            args.push(SECCOMP_FD.to_string());
        }

        // Filesystem bind mounts
        for entry in paths {
            let path_str = entry.path.to_string_lossy().to_string();
            match entry.mode {
                AccessMode::ReadOnly => {
                    args.push("--ro-bind".to_string());
                    args.push(path_str.clone());
                    args.push(path_str);
                }
                AccessMode::ReadWrite => {
                    args.push("--bind".to_string());
                    args.push(path_str.clone());
                    args.push(path_str);
                }
            }
        }

        args
    }
}

impl Default for LinuxEnforcer {
    fn default() -> Self {
        Self::new()
    }
}

impl SandboxEnforcer for LinuxEnforcer {
    fn name(&self) -> &str {
        "bubblewrap"
    }

    fn probe(&self) -> Result<(), SandboxError> {
        // Check that bwrap binary exists
        let result = std::process::Command::new("bwrap")
            .arg("--version")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status();

        match result {
            Ok(status) if status.success() => {
                // Also check user namespaces are available
                // The root bind is not optional. bwrap gives the new namespace an empty
                // root, so without it `/bin/true` does not exist inside and execvp fails —
                // which this probe then reported as "user namespaces are not available",
                // pointing operators at a sysctl that was never the problem. The check
                // failed on every host, so the enforcer was never selectable on Linux.
                let ns_check = std::process::Command::new("bwrap")
                    .args(["--ro-bind", "/", "/", "--unshare-user", "--", "/bin/true"])
                    .stdout(std::process::Stdio::null())
                    .stderr(std::process::Stdio::null())
                    .status();

                match ns_check {
                    Ok(s) if s.success() => Ok(()),
                    _ => Err(SandboxError::EnforcerUnavailable {
                        enforcer: "bubblewrap".to_string(),
                        message: "user namespaces are not available. Check that \
                                  `kernel.unprivileged_userns_clone` sysctl is set to 1."
                            .to_string(),
                    }),
                }
            }
            Ok(_) => Err(SandboxError::EnforcerUnavailable {
                enforcer: "bubblewrap".to_string(),
                message: "bwrap binary found but returned an error. \
                          Verify installation is complete."
                    .to_string(),
            }),
            Err(e) => Err(SandboxError::EnforcerUnavailable {
                enforcer: "bubblewrap".to_string(),
                message: format!(
                    "bwrap binary not found: {e}. Install bubblewrap: \
                     `apt install bubblewrap` (Debian/Ubuntu) or \
                     `dnf install bubblewrap` (Fedora/RHEL)."
                ),
            }),
        }
    }

    fn wrap_command(
        &self,
        program: &OsStr,
        args: &[OsString],
        policy: &SandboxPolicy,
    ) -> Result<WrappedCommand, SandboxError> {
        // Warn if domain-level network rules are present — bubblewrap can't enforce them
        if !policy.allow_network && !policy.network_rules.is_empty() {
            tracing::warn!(
                rules_count = policy.network_rules.len(),
                "bubblewrap does not support per-domain network filtering; \
                 network_rules will be ignored and all network access will be blocked"
            );
        }

        // 1. Canonicalize all paths in the policy
        let canonicalized_paths = canonicalize_paths(&policy.allowed_paths)?;

        // 2. Generate bwrap args from canonicalized paths
        let bwrap_args = Self::generate_args_from_paths(
            &canonicalized_paths,
            policy.allow_network,
            policy.allow_process_spawn,
        );

        // 3. Build the wrapped command: bwrap <args> -- <program> <original_args...>
        let mut wrapped_args: Vec<OsString> = bwrap_args.into_iter().map(OsString::from).collect();
        wrapped_args.push(OsString::from("--"));
        wrapped_args.push(program.to_owned());
        wrapped_args.extend_from_slice(args);

        Ok(WrappedCommand { program: OsString::from("bwrap"), args: wrapped_args })
    }

    /// Installs the process-creation seccomp program as file descriptor [`SECCOMP_FD`].
    ///
    /// # Errors
    ///
    /// Returns `EnforcerFailed` when the policy denies process spawning on an architecture
    /// without a generated filter, or when the descriptor cannot be prepared.
    fn configure_command(
        &self,
        cmd: &mut tokio::process::Command,
        policy: &SandboxPolicy,
    ) -> Result<(), SandboxError> {
        use std::io::Write;
        use std::os::fd::{AsRawFd, OwnedFd};

        if policy.allow_process_spawn {
            return Ok(());
        }

        let abi = seccomp::Abi::native().ok_or_else(|| SandboxError::EnforcerFailed {
            enforcer: "bubblewrap".to_string(),
            message: format!(
                "no process-creation seccomp filter exists for {}; allow process spawning in \
                 the policy or run on x86_64 or aarch64",
                std::env::consts::ARCH
            ),
        })?;
        let program = seccomp::encode(&seccomp::deny_process_creation(abi));

        let failed = |error: std::io::Error| SandboxError::EnforcerFailed {
            enforcer: "bubblewrap".to_string(),
            message: format!("failed to prepare the seccomp program descriptor: {error}"),
        };
        // The program is a few hundred bytes, well inside a pipe buffer, so the write cannot
        // block, and closing the writer gives bubblewrap its end-of-file.
        let (reader, mut writer) = std::io::pipe().map_err(failed)?;
        writer.write_all(&program).map_err(failed)?;
        drop(writer);
        let program_fd = OwnedFd::from(reader);

        // SAFETY: the closure runs in the forked child before exec and calls only dup2(2) and
        // fcntl(2), which are async-signal-safe. `program_fd` is owned by the closure, so the
        // descriptor stays open until the command is dropped.
        unsafe {
            cmd.pre_exec(move || {
                let source = program_fd.as_raw_fd();
                let result = if source == SECCOMP_FD {
                    // dup2 onto itself leaves FD_CLOEXEC set, so clear the flag directly.
                    libc::fcntl(source, libc::F_SETFD, 0)
                } else {
                    libc::dup2(source, SECCOMP_FD)
                };
                if result == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) }
            });
        }
        Ok(())
    }
}

/// Canonicalizes all paths in the policy, logging warnings for changed paths.
fn canonicalize_paths(paths: &[AllowedPath]) -> Result<Vec<AllowedPath>, SandboxError> {
    let mut result = Vec::with_capacity(paths.len());

    for entry in paths {
        let canonical = std::fs::canonicalize(&entry.path).map_err(|e| {
            SandboxError::PolicyViolation(format!(
                "failed to canonicalize allowed path '{}': {e}",
                entry.path.display()
            ))
        })?;

        if canonical != entry.path {
            tracing::warn!(
                original = %entry.path.display(),
                resolved = %canonical.display(),
                "allowed path resolved to a different location (possible symlink)"
            );
        }

        result.push(AllowedPath { path: canonical, mode: entry.mode });
    }

    Ok(result)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_generate_args_deny_all() {
        let policy = SandboxPolicyBuilder::new().build();
        let args = LinuxEnforcer::generate_args(&policy);

        assert_eq!(args[0], "--die-with-parent");
        assert_eq!(args[1], "--unshare-pid");
        assert!(args.contains(&"--unshare-net".to_string()));
        assert!(args.contains(&"--new-session".to_string()));
        assert!(
            args.windows(2).any(|pair| pair[0] == "--seccomp" && pair[1] == SECCOMP_FD.to_string())
        );
        // No bind mounts
        assert!(!args.contains(&"--ro-bind".to_string()));
        assert!(!args.contains(&"--bind".to_string()));
    }

    #[test]
    fn test_generate_args_read_only_path() {
        let policy = SandboxPolicyBuilder::new().allow_read("/usr/lib").build();
        let args = LinuxEnforcer::generate_args(&policy);

        let ro_idx = args.iter().position(|a| a == "--ro-bind").unwrap();
        assert_eq!(args[ro_idx + 1], "/usr/lib");
        assert_eq!(args[ro_idx + 2], "/usr/lib");
        assert!(!args.contains(&"--bind".to_string()));
    }

    #[test]
    fn test_generate_args_read_write_path() {
        let policy = SandboxPolicyBuilder::new().allow_read_write("/tmp/work").build();
        let args = LinuxEnforcer::generate_args(&policy);

        let bind_idx = args.iter().position(|a| a == "--bind").unwrap();
        assert_eq!(args[bind_idx + 1], "/tmp/work");
        assert_eq!(args[bind_idx + 2], "/tmp/work");
        assert!(!args.contains(&"--ro-bind".to_string()));
    }

    #[test]
    fn test_generate_args_network_allowed() {
        let policy = SandboxPolicyBuilder::new().allow_network().build();
        let args = LinuxEnforcer::generate_args(&policy);

        assert!(!args.contains(&"--unshare-net".to_string()));
    }

    #[test]
    fn test_generate_args_network_denied() {
        let policy = SandboxPolicyBuilder::new().build();
        let args = LinuxEnforcer::generate_args(&policy);

        assert!(args.contains(&"--unshare-net".to_string()));
    }

    #[test]
    fn test_generate_args_process_spawn_allowed() {
        let policy = SandboxPolicyBuilder::new().allow_process_spawn().build();
        let args = LinuxEnforcer::generate_args(&policy);

        assert!(!args.contains(&"--new-session".to_string()));
        assert!(!args.contains(&"--seccomp".to_string()));
    }

    #[test]
    fn test_generate_args_process_spawn_denied() {
        let policy = SandboxPolicyBuilder::new().build();
        let args = LinuxEnforcer::generate_args(&policy);

        assert!(args.contains(&"--new-session".to_string()));
        let seccomp = args.iter().position(|arg| arg == "--seccomp").expect("--seccomp present");
        assert_eq!(args[seccomp + 1], SECCOMP_FD.to_string());
    }

    #[test]
    fn configure_command_is_a_no_op_when_spawning_is_allowed() {
        let policy = SandboxPolicyBuilder::new().allow_process_spawn().build();
        let mut cmd = tokio::process::Command::new("true");

        LinuxEnforcer::new().configure_command(&mut cmd, &policy).expect("nothing to configure");
    }

    #[test]
    fn configure_command_installs_the_filter_on_supported_architectures() {
        let policy = SandboxPolicyBuilder::new().build();
        let mut cmd = tokio::process::Command::new("true");

        let result = LinuxEnforcer::new().configure_command(&mut cmd, &policy);
        if seccomp::Abi::native().is_some() {
            result.expect("the filter is prepared on a supported architecture");
        } else {
            assert!(matches!(result, Err(SandboxError::EnforcerFailed { .. })), "{result:?}");
        }
    }

    #[test]
    fn test_generate_args_starts_with_die_with_parent() {
        let policy = SandboxPolicyBuilder::new()
            .allow_read("/tmp")
            .allow_network()
            .allow_process_spawn()
            .build();
        let args = LinuxEnforcer::generate_args(&policy);

        assert_eq!(args[0], "--die-with-parent");
    }

    #[test]
    fn test_generate_args_no_empty_strings() {
        let policy = SandboxPolicyBuilder::new()
            .allow_read("/usr/lib")
            .allow_read_write("/tmp")
            .allow_network()
            .build();
        let args = LinuxEnforcer::generate_args(&policy);

        for arg in &args {
            assert!(!arg.is_empty(), "found empty string in bwrap args");
        }
    }

    #[test]
    fn test_name() {
        let enforcer = LinuxEnforcer::new();
        assert_eq!(enforcer.name(), "bubblewrap");
    }

    #[test]
    fn test_wrap_command_nonexistent_path_fails() {
        let enforcer = LinuxEnforcer::new();
        let policy =
            SandboxPolicyBuilder::new().allow_read("/nonexistent/path/that/does/not/exist").build();

        let result = enforcer.wrap_command(OsStr::new("echo"), &[], &policy);

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, SandboxError::PolicyViolation(_)),
            "expected PolicyViolation, got: {err:?}"
        );
    }
}