Skip to main content

adk_sandbox/sandbox/
mod.rs

1//! OS-level sandbox enforcement types and traits.
2//!
3//! This module defines the platform-agnostic [`SandboxPolicy`] data model,
4//! the [`SandboxEnforcer`] trait for platform-specific enforcement, and the
5//! [`get_enforcer`] registry function that selects the appropriate enforcer
6//! for the current platform.
7
8#[cfg(all(feature = "sandbox-macos", target_os = "macos"))]
9pub mod macos;
10
11#[cfg(all(feature = "sandbox-linux", target_os = "linux"))]
12pub mod linux;
13
14// The restricted-token enforcer's platform-neutral surface (the policy-to-grant mapping and
15// the honest probe) compiles wherever the feature is on, so it is unit-tested on every host;
16// the Win32 launch is gated to Windows inside the module (spec 3.2 §10 W5).
17#[cfg(any(test, feature = "sandbox-windows"))]
18pub mod windows;
19
20#[cfg(any(test, all(feature = "sandbox-linux", target_os = "linux")))]
21mod seccomp;
22
23pub(crate) mod command;
24
25#[cfg(any(
26    test,
27    all(feature = "sandbox-macos", target_os = "macos"),
28    all(feature = "sandbox-linux", target_os = "linux")
29))]
30mod layering;
31
32pub use command::sandboxed_command;
33
34use std::collections::HashMap;
35use std::ffi::{OsStr, OsString};
36use std::path::PathBuf;
37
38use serde::{Deserialize, Serialize};
39
40use crate::error::SandboxError;
41
42/// Filesystem access mode for an allowed path.
43///
44/// # Example
45///
46/// ```rust
47/// use adk_sandbox::sandbox::AccessMode;
48///
49/// let mode = AccessMode::ReadOnly;
50/// assert_ne!(mode, AccessMode::ReadWrite);
51/// ```
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "camelCase")]
54pub enum AccessMode {
55    /// Read-only access.
56    ReadOnly,
57    /// Read and write access.
58    ReadWrite,
59}
60
61/// A filesystem path entry with an access mode.
62///
63/// # Example
64///
65/// ```rust
66/// use std::path::PathBuf;
67/// use adk_sandbox::sandbox::{AllowedPath, AccessMode};
68///
69/// let entry = AllowedPath {
70///     path: PathBuf::from("/tmp"),
71///     mode: AccessMode::ReadOnly,
72/// };
73/// assert_eq!(entry.mode, AccessMode::ReadOnly);
74/// ```
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76#[serde(rename_all = "camelCase")]
77pub struct AllowedPath {
78    /// The filesystem path (directory or file).
79    pub path: PathBuf,
80    /// The access mode: read-only or read-write.
81    pub mode: AccessMode,
82}
83
84/// The loopback port of an egress proxy, the one destination a
85/// [`NetworkAccess::Proxied`] process may reach.
86///
87/// The process reaches it at `127.0.0.1:<port>` and finds it through the standard proxy
88/// variables [`NetworkAccess::proxy_env`] names.
89///
90/// # Example
91///
92/// ```rust
93/// use adk_sandbox::sandbox::ProxyEndpoint;
94///
95/// let endpoint = ProxyEndpoint { port: 47811 };
96/// assert_eq!(endpoint.url(), "http://127.0.0.1:47811");
97/// ```
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub struct ProxyEndpoint {
101    /// The loopback port.
102    pub port: u16,
103}
104
105impl ProxyEndpoint {
106    /// The proxy URL a process configures, `http://127.0.0.1:<port>`.
107    pub fn url(&self) -> String {
108        format!("http://127.0.0.1:{}", self.port)
109    }
110}
111
112/// What a sandboxed process may reach on the network.
113///
114/// | Mode | The process reaches |
115/// |------|---------------------|
116/// | `Denied` (the default) | Nothing |
117/// | `Proxied` | Only the egress proxy at [`ProxyEndpoint`], which decides every destination |
118/// | `Open` | Everything the host reaches |
119///
120/// An enforcer that cannot enforce the mode refuses the policy with
121/// [`SandboxError::Unenforceable`] instead of running it with more network access; see
122/// [`SandboxEnforcer::network_support`].
123///
124/// # Example
125///
126/// ```rust
127/// use adk_sandbox::sandbox::{NetworkAccess, ProxyEndpoint};
128///
129/// let proxied = NetworkAccess::Proxied { endpoint: ProxyEndpoint { port: 47811 } };
130/// assert!(proxied.restricts());
131/// assert!(proxied.proxy_env().contains(&("HTTPS_PROXY", "http://127.0.0.1:47811".to_string())));
132/// assert!(NetworkAccess::Denied.proxy_env().is_empty());
133/// ```
134#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
135#[serde(rename_all = "camelCase", tag = "mode")]
136pub enum NetworkAccess {
137    /// No network access.
138    #[default]
139    Denied,
140    /// Network access only through the egress proxy at `endpoint`.
141    Proxied {
142        /// Where the proxy listens.
143        endpoint: ProxyEndpoint,
144    },
145    /// Unrestricted network access.
146    Open,
147}
148
149impl NetworkAccess {
150    /// Whether the mode restricts the network (`Denied` or `Proxied`).
151    pub fn restricts(&self) -> bool {
152        !matches!(self, Self::Open)
153    }
154
155    /// The variables a `Proxied` process runs with, upper and lower case: `HTTP_PROXY`,
156    /// `HTTPS_PROXY` and `ALL_PROXY` name the endpoint, and `NO_PROXY` is empty so no
157    /// destination bypasses it. Empty for the other modes.
158    pub fn proxy_env(&self) -> Vec<(&'static str, String)> {
159        match self {
160            Self::Proxied { endpoint } => {
161                let url = endpoint.url();
162                let mut env: Vec<(&'static str, String)> = [
163                    "HTTP_PROXY",
164                    "HTTPS_PROXY",
165                    "ALL_PROXY",
166                    "http_proxy",
167                    "https_proxy",
168                    "all_proxy",
169                ]
170                .into_iter()
171                .map(|name| (name, url.clone()))
172                .collect();
173                env.push(("NO_PROXY", String::new()));
174                env.push(("no_proxy", String::new()));
175                env
176            }
177            Self::Denied | Self::Open => Vec::new(),
178        }
179    }
180}
181
182impl std::fmt::Display for NetworkAccess {
183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        match self {
185            Self::Denied => f.write_str("denied"),
186            Self::Proxied { endpoint } => write!(f, "proxied through 127.0.0.1:{}", endpoint.port),
187            Self::Open => f.write_str("open"),
188        }
189    }
190}
191
192/// Which restrictive [`NetworkAccess`] modes an enforcer enforces; `Open` needs no enforcement.
193///
194/// # Example
195///
196/// ```rust
197/// use adk_sandbox::sandbox::{NetworkAccess, NetworkSupport};
198///
199/// let support = NetworkSupport { denied: true, proxied: false };
200/// assert!(support.enforces(&NetworkAccess::Denied));
201/// assert!(support.enforces(&NetworkAccess::Open));
202/// assert!(NetworkSupport::NONE.check("custom", &NetworkAccess::Denied).is_err());
203/// ```
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
205#[serde(rename_all = "camelCase")]
206pub struct NetworkSupport {
207    /// Whether `Denied` is enforced.
208    pub denied: bool,
209    /// Whether `Proxied` is enforced.
210    pub proxied: bool,
211}
212
213impl NetworkSupport {
214    /// No network restriction is enforced.
215    pub const NONE: Self = Self { denied: false, proxied: false };
216
217    /// Whether `network` is enforced.
218    pub fn enforces(&self, network: &NetworkAccess) -> bool {
219        match network {
220            NetworkAccess::Denied => self.denied,
221            NetworkAccess::Proxied { .. } => self.proxied,
222            NetworkAccess::Open => true,
223        }
224    }
225
226    /// `Ok` when `network` is enforced.
227    ///
228    /// # Errors
229    ///
230    /// Returns [`SandboxError::Unenforceable`] naming `enforcer` when `network` is not enforced.
231    pub fn check(&self, enforcer: &str, network: &NetworkAccess) -> Result<(), SandboxError> {
232        if self.enforces(network) {
233            return Ok(());
234        }
235        Err(SandboxError::Unenforceable {
236            enforcer: enforcer.to_string(),
237            requirement: format!("network access {network}"),
238        })
239    }
240}
241
242/// Where the egress proxy of a [`NetworkAccess::Proxied`] call must listen for the sandboxed
243/// process to reach it ([`SandboxEnforcer::proxy_listener`]).
244///
245/// # Example
246///
247/// ```rust
248/// use adk_sandbox::sandbox::ProxyListener;
249///
250/// assert_ne!(ProxyListener::HostLoopback, ProxyListener::SandboxLoopback);
251/// ```
252#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(rename_all = "camelCase")]
254pub enum ProxyListener {
255    /// The host's loopback interface, which the sandbox shares (Seatbelt).
256    HostLoopback,
257    /// The loopback interface of the sandbox's own network namespace, where the enforcer
258    /// places a listener the proxy serves (bubblewrap).
259    SandboxLoopback,
260}
261
262/// A declarative sandbox policy describing allowed operations.
263///
264/// Constructed via [`SandboxPolicyBuilder`]. Defaults to deny-all when
265/// no permissions are granted.
266///
267/// # Network Access
268///
269/// [`network`](Self::network) is one of three modes, and an enforcer runs a policy only when
270/// it enforces the mode; otherwise it returns [`SandboxError::Unenforceable`]:
271///
272/// | Enforcer | `Denied` | `Proxied` | `Open` |
273/// |----------|----------|-----------|--------|
274/// | Seatbelt (macOS) | `(deny network*)`, Unix-domain sockets included | Only `localhost:<port>` of the proxy | Allowed |
275/// | bubblewrap (Linux) | `--unshare-net`: no IP traffic and no abstract Unix sockets; a grant of `/tmp`, `/var/tmp` or `/dev/shm` itself, or of a socket-holding path under `/run`, is refused, and a grant above them, such as `/`, covers them with an empty `tmpfs` | Only the proxy, which listens inside the empty namespace (feature `egress-proxy`); refused without it | Allowed |
276/// | Restricted token (Windows) | Refused, unless the caller acknowledges that the network stays open (`WindowsEnforcer::acknowledge_open_network`) | Refused the same way | Allowed |
277///
278/// Policies serialized before 3.0 load: `allowNetwork: true` becomes `Open`, `false` becomes
279/// `Denied`, and `networkRules` is dropped, as no enforcer ever applied it.
280///
281/// # Example
282///
283/// ```rust
284/// use adk_sandbox::sandbox::{NetworkAccess, SandboxPolicy, SandboxPolicyBuilder};
285///
286/// let policy = SandboxPolicyBuilder::new().allow_read("/usr/lib").env("PATH", "/usr/bin").build();
287/// assert_eq!(policy.network, NetworkAccess::Denied);
288///
289/// let legacy: SandboxPolicy = serde_json::from_str(
290///     r#"{"allowedPaths":[],"allowNetwork":true,"allowProcessSpawn":false,"env":{}}"#,
291/// )
292/// .unwrap();
293/// assert_eq!(legacy.network, NetworkAccess::Open);
294/// ```
295#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
296#[serde(rename_all = "camelCase", from = "SandboxPolicyWire")]
297pub struct SandboxPolicy {
298    /// Filesystem paths the process may access. Each path must exist; enforcers resolve
299    /// them and fail with `PolicyViolation` otherwise.
300    ///
301    /// When entries nest, the most specific one decides, whatever their order (spec 3.1
302    /// §10 S3). A `ReadOnly` entry inside a `ReadWrite` entry — `.git` inside a workspace —
303    /// refuses every write, creation, removal, rename, and link beneath it on Seatbelt and
304    /// bubblewrap alike, and the writable directories above it cannot be renamed or removed.
305    /// For the same path, `ReadWrite` wins.
306    pub allowed_paths: Vec<AllowedPath>,
307    /// What the process may reach on the network; see [Network Access](Self#network-access).
308    pub network: NetworkAccess,
309    /// Whether the process may create child processes.
310    ///
311    /// When `false`, replacing the process image with `execve` remains allowed
312    /// but creating a new process is refused:
313    ///
314    /// | Enforcer | Mechanism |
315    /// |----------|-----------|
316    /// | Seatbelt (macOS) | `process-fork` is not granted |
317    /// | bubblewrap (Linux) | seccomp filter failing `fork`, `vfork`, and non-thread `clone` (x86-64 and AArch64) |
318    /// | Restricted token (Windows) | Not restricted |
319    ///
320    /// A shell running more than one external command forks, so `sh -c` scripts
321    /// usually need this enabled.
322    pub allow_process_spawn: bool,
323    /// Environment variables passed to the sandboxed process.
324    pub env: HashMap<String, String>,
325}
326
327/// The serialized form of [`SandboxPolicy`], which also reads the fields it had before 3.0.
328#[derive(Deserialize)]
329#[serde(rename_all = "camelCase")]
330struct SandboxPolicyWire {
331    #[serde(default)]
332    allowed_paths: Vec<AllowedPath>,
333    #[serde(default)]
334    network: Option<NetworkAccess>,
335    /// Before 3.0: `true` for all network access.
336    #[serde(default)]
337    allow_network: Option<bool>,
338    /// Before 3.0: domain rules no enforcer applied; read and dropped.
339    #[serde(default, rename = "networkRules")]
340    _network_rules: serde::de::IgnoredAny,
341    #[serde(default)]
342    allow_process_spawn: bool,
343    #[serde(default)]
344    env: HashMap<String, String>,
345}
346
347impl From<SandboxPolicyWire> for SandboxPolicy {
348    fn from(wire: SandboxPolicyWire) -> Self {
349        let legacy = wire
350            .allow_network
351            .map(|open| if open { NetworkAccess::Open } else { NetworkAccess::Denied });
352        Self {
353            allowed_paths: wire.allowed_paths,
354            network: wire.network.or(legacy).unwrap_or_default(),
355            allow_process_spawn: wire.allow_process_spawn,
356            env: wire.env,
357        }
358    }
359}
360
361/// The result of wrapping a command with sandbox enforcement.
362///
363/// Contains the new program to execute and the full argument list
364/// (sandbox wrapper args + original program + original args).
365#[derive(Debug, Clone)]
366pub struct WrappedCommand {
367    /// The program to execute (e.g., "sandbox-exec", "bwrap", or the original program for Windows).
368    pub program: OsString,
369    /// The full argument list including wrapper args, separator, and original args.
370    pub args: Vec<OsString>,
371}
372
373/// Builder for constructing [`SandboxPolicy`] values incrementally.
374///
375/// Defaults to deny-all: no allowed paths, no network, no process spawning,
376/// and no environment variables.
377///
378/// # Example
379///
380/// ```rust
381/// use adk_sandbox::sandbox::SandboxPolicyBuilder;
382///
383/// let policy = SandboxPolicyBuilder::new()
384///     .allow_read("/usr/lib")
385///     .allow_read_write("/tmp/work")
386///     .allow_network()
387///     .allow_process_spawn()
388///     .env("HOME", "/home/user")
389///     .build();
390///
391/// assert_eq!(policy.allowed_paths.len(), 2);
392/// assert_eq!(policy.network, adk_sandbox::sandbox::NetworkAccess::Open);
393/// assert!(policy.allow_process_spawn);
394/// assert_eq!(policy.env.get("HOME").unwrap(), "/home/user");
395/// ```
396pub struct SandboxPolicyBuilder {
397    policy: SandboxPolicy,
398}
399
400impl SandboxPolicyBuilder {
401    /// Creates a new builder with deny-all defaults.
402    pub fn new() -> Self {
403        Self {
404            policy: SandboxPolicy {
405                allowed_paths: Vec::new(),
406                network: NetworkAccess::Denied,
407                allow_process_spawn: false,
408                env: HashMap::new(),
409            },
410        }
411    }
412
413    /// Adds a read-only allowed path.
414    pub fn allow_read(mut self, path: impl Into<PathBuf>) -> Self {
415        self.policy
416            .allowed_paths
417            .push(AllowedPath { path: path.into(), mode: AccessMode::ReadOnly });
418        self
419    }
420
421    /// Adds a read-write allowed path.
422    pub fn allow_read_write(mut self, path: impl Into<PathBuf>) -> Self {
423        self.policy
424            .allowed_paths
425            .push(AllowedPath { path: path.into(), mode: AccessMode::ReadWrite });
426        self
427    }
428
429    /// Sets what the process may reach on the network.
430    pub fn network(mut self, network: NetworkAccess) -> Self {
431        self.policy.network = network;
432        self
433    }
434
435    /// Enables full network access: [`NetworkAccess::Open`].
436    pub fn allow_network(self) -> Self {
437        self.network(NetworkAccess::Open)
438    }
439
440    /// Lets the process reach only the egress proxy at `endpoint`: [`NetworkAccess::Proxied`].
441    ///
442    /// # Example
443    ///
444    /// ```rust
445    /// use adk_sandbox::sandbox::{NetworkAccess, ProxyEndpoint, SandboxPolicyBuilder};
446    ///
447    /// let endpoint = ProxyEndpoint { port: 47811 };
448    /// let policy = SandboxPolicyBuilder::new().proxied(endpoint).build();
449    /// assert_eq!(policy.network, NetworkAccess::Proxied { endpoint });
450    /// ```
451    pub fn proxied(self, endpoint: ProxyEndpoint) -> Self {
452        self.network(NetworkAccess::Proxied { endpoint })
453    }
454
455    /// Enables child process spawning.
456    pub fn allow_process_spawn(mut self) -> Self {
457        self.policy.allow_process_spawn = true;
458        self
459    }
460
461    /// Adds an environment variable key-value pair.
462    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
463        self.policy.env.insert(key.into(), value.into());
464        self
465    }
466
467    /// Consumes the builder and returns the constructed [`SandboxPolicy`].
468    pub fn build(self) -> SandboxPolicy {
469        self.policy
470    }
471}
472
473impl Default for SandboxPolicyBuilder {
474    fn default() -> Self {
475        Self::new()
476    }
477}
478
479/// Platform-specific sandbox enforcement.
480///
481/// Implementations translate a [`SandboxPolicy`] into OS-native restrictions.
482/// The trait uses a `wrap_command` approach rather than mutating a `Command`
483/// directly, because `tokio::process::Command` does not allow replacing the
484/// program after construction.
485///
486/// # Building a Command
487///
488/// [`sandboxed_command`] calls `wrap_command()` to obtain the wrapper program
489/// and args, constructs a new `Command` with those values, and then calls
490/// `configure_command()` on it. `ProcessBackend` builds its sandboxed commands
491/// the same way. This avoids the limitation that tokio's Command doesn't expose
492/// `get_program()`/`get_args()` setters after creation.
493///
494/// # Windows Exception
495///
496/// On Windows, `WindowsEnforcer` confines a command with a restricted token, which
497/// is set when the process is created and so cannot be attached to a
498/// `tokio::process::Command`. Its `wrap_command` returns the original program and
499/// args unchanged, and its `probe` and `configure_command` fail, naming
500/// `WindowsEnforcer::run_confined` as the path that confines (spec 3.2 §10 W5).
501pub trait SandboxEnforcer: Send + Sync {
502    /// Returns the enforcer name (e.g., "seatbelt", "bubblewrap", "restricted-token").
503    fn name(&self) -> &str;
504
505    /// Checks whether the enforcer is functional on the current system.
506    fn probe(&self) -> Result<(), SandboxError>;
507
508    /// The restrictive [`NetworkAccess`] modes this enforcer enforces.
509    ///
510    /// [`wrap_command`](Self::wrap_command) refuses a policy whose mode is not among them with
511    /// [`SandboxError::Unenforceable`]; it never runs a command with more network access than
512    /// the policy asks for.
513    fn network_support(&self) -> NetworkSupport;
514
515    /// Where the egress proxy of a `Proxied` call listens; the default is the host's loopback.
516    /// A wrapper forwards its inner enforcer's.
517    fn proxy_listener(&self) -> ProxyListener {
518        ProxyListener::HostLoopback
519    }
520
521    /// Wraps the original command with sandbox enforcement.
522    ///
523    /// Given the original program and its arguments, returns a [`WrappedCommand`]
524    /// containing the sandbox wrapper program and the full argument list.
525    ///
526    /// This method:
527    /// 1. Returns `SandboxError::Unenforceable` if the policy's network mode is not enforced
528    /// 2. Resolves every path in the policy to the location it grants: a symbolic link
529    ///    resolved is logged at `debug`, and at `warn` only when the link sits between a
530    ///    read-write entry and a read-only entry inside it, where a command can replace it
531    /// 3. Returns `SandboxError::PolicyViolation` if any path cannot be resolved
532    /// 4. Generates the platform-specific wrapper (Seatbelt profile, bwrap args, etc.)
533    /// 5. Returns the wrapped program and args
534    fn wrap_command(
535        &self,
536        program: &OsStr,
537        args: &[OsString],
538        policy: &SandboxPolicy,
539    ) -> Result<WrappedCommand, SandboxError>;
540
541    /// Configures the Command with platform-specific process attributes.
542    ///
543    /// Must be called on the Command constructed from `wrap_command()` output,
544    /// after its program and arguments are final. The default implementation is
545    /// a no-op. Linux uses it to install the process-creation seccomp program
546    /// that the wrapped arguments reference; the Windows enforcer fails here, since a
547    /// restricted token cannot be set on a `tokio::process::Command`.
548    fn configure_command(
549        &self,
550        _cmd: &mut tokio::process::Command,
551        _policy: &SandboxPolicy,
552    ) -> Result<(), SandboxError> {
553        Ok(())
554    }
555}
556
557/// Resolves each allowed path to the location the enforcers grant, since Seatbelt matches
558/// and bubblewrap mounts resolved paths: `/tmp` is granted as `/private/tmp` on macOS.
559///
560/// A path that resolves elsewhere — `/tmp`, a Homebrew `opt` link, the Cryptexes on `PATH`
561/// on macOS — is logged at `debug`: the grant covers the location it resolves to. The one
562/// resolution logged at `warn` is a read-only entry reached through a symbolic link inside
563/// a read-write entry, because a sandboxed command can replace that link: the grant still
564/// protects the target, but no longer what the entry's path names.
565///
566/// # Errors
567///
568/// Returns `SandboxError::PolicyViolation` when a path cannot be resolved.
569#[cfg(any(
570    test,
571    feature = "sandbox-windows",
572    all(feature = "sandbox-macos", target_os = "macos"),
573    all(feature = "sandbox-linux", target_os = "linux")
574))]
575pub(crate) fn canonicalize_paths(paths: &[AllowedPath]) -> Result<Vec<AllowedPath>, SandboxError> {
576    let resolved = paths
577        .iter()
578        .map(|entry| {
579            let path = std::fs::canonicalize(&entry.path).map_err(|e| {
580                SandboxError::PolicyViolation(format!(
581                    "failed to canonicalize allowed path '{}': {e}",
582                    entry.path.display()
583                ))
584            })?;
585            Ok(AllowedPath { path, mode: entry.mode })
586        })
587        .collect::<Result<Vec<_>, SandboxError>>()?;
588
589    for (entry, canonical) in paths.iter().zip(&resolved) {
590        if canonical.path == entry.path {
591            continue;
592        }
593        let replaceable = entry.mode == AccessMode::ReadOnly
594            && paths.iter().zip(&resolved).any(|(outer, outer_canonical)| {
595                outer.mode == AccessMode::ReadWrite
596                    && outer.path != entry.path
597                    && entry
598                        .path
599                        .strip_prefix(&outer.path)
600                        .is_ok_and(|rest| outer_canonical.path.join(rest) != canonical.path)
601            });
602        if replaceable {
603            tracing::warn!(
604                original = %entry.path.display(),
605                resolved = %canonical.path.display(),
606                "a read-only path inside a writable one is reached through a symbolic link a \
607                 sandboxed command can replace, so only the link's target stays read-only; \
608                 replace the link with what it points to"
609            );
610        } else {
611            tracing::debug!(
612                original = %entry.path.display(),
613                resolved = %canonical.path.display(),
614                "allowed path granted at its resolved location"
615            );
616        }
617    }
618
619    Ok(resolved)
620}
621
622/// Returns the platform-appropriate sandbox enforcer.
623///
624/// Selects the enforcer based on enabled feature flags, then calls `probe()`
625/// to verify it is functional. Returns an error if no enforcer is available
626/// or if the probe fails.
627///
628/// # Errors
629///
630/// Returns `SandboxError::EnforcerUnavailable` if no sandbox feature flag is
631/// enabled for the current platform, or if the selected enforcer's `probe()`
632/// check fails.
633///
634/// # Example
635///
636/// ```rust,ignore
637/// use adk_sandbox::sandbox::get_enforcer;
638///
639/// let enforcer = get_enforcer()?;
640/// println!("Using enforcer: {}", enforcer.name());
641/// ```
642pub fn get_enforcer() -> Result<Box<dyn SandboxEnforcer>, SandboxError> {
643    #[cfg(all(feature = "sandbox-macos", target_os = "macos"))]
644    {
645        let enforcer = macos::MacOsEnforcer::new();
646        enforcer.probe()?;
647        return Ok(Box::new(enforcer));
648    }
649
650    #[cfg(all(feature = "sandbox-linux", target_os = "linux"))]
651    {
652        let enforcer = linux::LinuxEnforcer::new();
653        enforcer.probe()?;
654        return Ok(Box::new(enforcer));
655    }
656
657    #[cfg(all(feature = "sandbox-windows", target_os = "windows"))]
658    {
659        let enforcer = windows::WindowsEnforcer::new();
660        enforcer.probe()?;
661        return Ok(Box::new(enforcer));
662    }
663
664    #[allow(unreachable_code)]
665    Err(SandboxError::EnforcerUnavailable {
666        enforcer: "none".to_string(),
667        message: "no sandbox feature flag is enabled for this platform".to_string(),
668    })
669}
670
671#[cfg(all(test, unix))]
672mod tests {
673    use std::os::unix::fs::symlink;
674    use std::path::Path;
675    use std::sync::{Arc, Mutex};
676
677    use tracing::field::{Field, Visit};
678    use tracing::span::{Attributes, Id, Record};
679    use tracing::{Event, Level, Metadata, Subscriber};
680
681    use super::*;
682
683    /// The level and `original` field of every event logged.
684    #[derive(Clone, Default)]
685    struct Logged(Arc<Mutex<Vec<(Level, String)>>>);
686
687    struct Original<'a>(&'a mut String);
688
689    impl Visit for Original<'_> {
690        fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
691            if field.name() == "original" {
692                *self.0 = format!("{value:?}");
693            }
694        }
695    }
696
697    impl Subscriber for Logged {
698        fn enabled(&self, _: &Metadata<'_>) -> bool {
699            true
700        }
701
702        fn new_span(&self, _: &Attributes<'_>) -> Id {
703            Id::from_u64(1)
704        }
705
706        fn record(&self, _: &Id, _: &Record<'_>) {}
707
708        fn record_follows_from(&self, _: &Id, _: &Id) {}
709
710        fn event(&self, event: &Event<'_>) {
711            let mut original = String::new();
712            event.record(&mut Original(&mut original));
713            self.0.lock().expect("the log").push((*event.metadata().level(), original));
714        }
715
716        fn enter(&self, _: &Id) {}
717
718        fn exit(&self, _: &Id) {}
719    }
720
721    /// Resolves `paths`, returning the resolved paths and what was logged.
722    fn resolve(paths: &[(&Path, AccessMode)]) -> (Vec<PathBuf>, Vec<(Level, String)>) {
723        let entries: Vec<AllowedPath> = paths
724            .iter()
725            .map(|(path, mode)| AllowedPath { path: path.to_path_buf(), mode: *mode })
726            .collect();
727        let logged = Logged::default();
728        let resolved =
729            tracing::subscriber::with_default(logged.clone(), || canonicalize_paths(&entries))
730                .expect("every path resolves");
731        let events = std::mem::take(&mut *logged.0.lock().expect("the log"));
732        (resolved.into_iter().map(|entry| entry.path).collect(), events)
733    }
734
735    #[test]
736    fn a_linked_toolchain_directory_is_granted_at_its_target_and_logged_at_debug() {
737        // Homebrew's `opt/<formula>` link into `Cellar`, as a `PATH` entry reaches it.
738        let root = tempfile::tempdir().expect("tempdir");
739        let root = std::fs::canonicalize(root.path()).expect("canonical");
740        let cellar = root.join("Cellar/python/3.12/libexec/bin");
741        std::fs::create_dir_all(&cellar).expect("cellar");
742        std::fs::create_dir(root.join("opt")).expect("opt");
743        symlink("../Cellar/python/3.12", root.join("opt/python")).expect("link");
744        let linked = root.join("opt/python/libexec/bin");
745
746        let (resolved, logged) = resolve(&[(&linked, AccessMode::ReadOnly)]);
747
748        assert_eq!(resolved, vec![cellar]);
749        assert_eq!(logged, vec![(Level::DEBUG, linked.display().to_string())]);
750    }
751
752    #[test]
753    fn a_link_above_the_workspace_is_routine() {
754        // `/tmp` on macOS: the link sits above both entries, so it is not the workspace's.
755        let root = tempfile::tempdir().expect("tempdir");
756        let root = std::fs::canonicalize(root.path()).expect("canonical");
757        std::fs::create_dir_all(root.join("real/ws/.git")).expect("workspace");
758        symlink("real", root.join("tmp")).expect("link");
759        let workspace = root.join("tmp/ws");
760        let git = workspace.join(".git");
761
762        let (resolved, logged) =
763            resolve(&[(&workspace, AccessMode::ReadWrite), (&git, AccessMode::ReadOnly)]);
764
765        assert_eq!(resolved, vec![root.join("real/ws"), root.join("real/ws/.git")]);
766        assert!(logged.iter().all(|(level, _)| *level == Level::DEBUG), "{logged:?}");
767    }
768
769    #[test]
770    fn a_read_only_entry_behind_a_replaceable_link_warns() {
771        // `.git` inside the writable workspace is a link: a command can swap the link for a
772        // writable directory, so only the link's target stays read-only.
773        let root = tempfile::tempdir().expect("tempdir");
774        let root = std::fs::canonicalize(root.path()).expect("canonical");
775        let workspace = root.join("ws");
776        std::fs::create_dir_all(root.join("elsewhere/git")).expect("target");
777        std::fs::create_dir(&workspace).expect("workspace");
778        symlink(root.join("elsewhere/git"), workspace.join(".git")).expect("link");
779        let git = workspace.join(".git");
780
781        let (resolved, logged) =
782            resolve(&[(&workspace, AccessMode::ReadWrite), (&git, AccessMode::ReadOnly)]);
783
784        assert_eq!(resolved, vec![workspace, root.join("elsewhere/git")]);
785        assert_eq!(logged, vec![(Level::WARN, git.display().to_string())]);
786    }
787
788    #[test]
789    fn a_writable_entry_behind_a_link_is_routine() {
790        // A writable entry reached through a link inside a read-only one cannot be replaced:
791        // the link sits in read-only space.
792        let root = tempfile::tempdir().expect("tempdir");
793        let root = std::fs::canonicalize(root.path()).expect("canonical");
794        let workspace = root.join("ws");
795        std::fs::create_dir_all(root.join("elsewhere/out")).expect("target");
796        std::fs::create_dir(&workspace).expect("workspace");
797        symlink(root.join("elsewhere/out"), workspace.join("out")).expect("link");
798        let out = workspace.join("out");
799
800        let (_, logged) =
801            resolve(&[(&workspace, AccessMode::ReadOnly), (&out, AccessMode::ReadWrite)]);
802
803        assert_eq!(logged, vec![(Level::DEBUG, out.display().to_string())]);
804    }
805}