Skip to main content

vtcode_computer_use/browser/
container.rs

1//! Approved-container lifecycle for the isolated Chromium runner.
2//!
3//! The caller approves the image and the static build. The launcher enforces
4//! pinning, directory shape, and mount-spec safety, starts the container with
5//! a fixed hardening flag set over `argv` (never a shell), and tears down the
6//! exact container it started. The flag set never degrades: any failure
7//! refuses the target instead of launching weaker isolation.
8
9use std::{ffi::OsString, path::Path, time::Duration};
10
11use anyhow::{Context, Result, bail, ensure};
12use tokio::process::{Child, ChildStdin, ChildStdout, Command};
13
14const DOCKER_TIMEOUT: Duration = Duration::from_secs(30);
15const AVAILABILITY_TIMEOUT: Duration = Duration::from_secs(10);
16const IDENTIFY_TIMEOUT: Duration = Duration::from_secs(15);
17const IDENTIFY_INTERVAL: Duration = Duration::from_millis(200);
18const CONTAINER_NAME_PREFIX: &str = "vtcode-cua-";
19const CONTAINER_ID_LEN: usize = 64;
20const DIAGNOSTIC_MAX_BYTES: usize = 512;
21
22/// A validated image and build pair for one approved container.
23pub struct ContainerSpec {
24    image: String,
25    build_dir: String,
26}
27
28impl ContainerSpec {
29    /// Approve an image and build directory for container launch.
30    ///
31    /// The image must carry an explicit tag or digest other than `latest`.
32    /// The build directory must exist, resolve to a real directory, and be
33    /// representable in a `--mount` spec.
34    ///
35    /// # Errors
36    ///
37    /// Returns an error for an unpinned image, a missing or non-directory
38    /// build path, or a path that cannot appear in a mount spec.
39    pub async fn approved(image: &str, build_dir: &Path) -> Result<Self> {
40        ensure!(!image.is_empty() && image.len() <= 512, "invalid browser container image");
41        ensure!(image.chars().all(|c| !c.is_control() && !c.is_whitespace()), "invalid browser container image");
42        ensure!(has_image_pin(image) && !image.ends_with(":latest"), "browser container image must be pinned");
43        let canonical = vtcode_commons::fs::canonicalize_with_context_async(build_dir, "browser build").await?;
44        ensure!(canonical.is_dir(), "browser build is not a directory");
45        let Some(dir) = canonical.to_str() else {
46            bail!("browser build path is not representable");
47        };
48        ensure!(mount_spec_safe(dir), "browser build path cannot appear in a mount spec");
49        Ok(Self { image: image.to_owned(), build_dir: dir.to_owned() })
50    }
51}
52
53/// Handle to the exact container started for an approved spec. Dropping the
54/// handle kills the attached client; use [`ContainerHandle::terminate`] to
55/// deterministically remove the exact container.
56pub struct ContainerHandle {
57    name: String,
58    id: String,
59    #[allow(dead_code, reason = "Owned for its kill-on-drop backstop; never read directly.")]
60    child: Child,
61}
62
63/// What `terminate` found: the container it removed, or one already gone.
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum TerminateOutcome {
66    /// The exact container was removed by this call.
67    Removed,
68    /// The container was already gone; teardown stays idempotent.
69    AlreadyGone,
70}
71
72impl ContainerHandle {
73    /// Start the approved container and return its pipes for the driver.
74    ///
75    /// The tuple order matches [`crate::browser::BrowserDriver::connect`]:
76    /// the handle, the reply stream, then the command stream.
77    ///
78    /// # Errors
79    ///
80    /// Returns an error if `docker` is unavailable, the container cannot be
81    /// started, or its identity cannot be established.
82    pub async fn launch(spec: &ContainerSpec) -> Result<(Self, ChildStdout, ChildStdin)> {
83        let name = format!("{CONTAINER_NAME_PREFIX}{}", uuid::Uuid::new_v4().as_simple());
84        let mut child = Command::new("docker")
85            .args(docker_run_argv(spec, &name))
86            .stdin(std::process::Stdio::piped())
87            .stdout(std::process::Stdio::piped())
88            .stderr(std::process::Stdio::piped())
89            .kill_on_drop(true)
90            .spawn()
91            .context("could not start the approved browser container")?;
92        let replies = child.stdout.take().context("browser container did not pipe its replies")?;
93        let commands = child.stdin.take().context("browser container did not pipe its commands")?;
94        let id = inspect_container_id(&name, &mut child).await?;
95        Ok((Self { name, id, child }, replies, commands))
96    }
97
98    /// The unique container name assigned at launch.
99    #[must_use]
100    pub fn name(&self) -> &str {
101        &self.name
102    }
103
104    /// The exact container identity established at launch.
105    #[must_use]
106    pub fn id(&self) -> &str {
107        &self.id
108    }
109
110    /// Remove the exact container, succeeding when it is already gone.
111    /// Call this on Stop, failure, and teardown paths; dropping the handle
112    /// only stops the attached client. The caller reports the outcome with
113    /// the trigger that caused it, so teardown stays auditable.
114    ///
115    /// `Removed` means this call ensured removal; `AlreadyGone` means the
116    /// container was observably absent before attempting it.
117    ///
118    /// # Errors
119    ///
120    /// Returns an error if `docker` is unavailable, a step times out, or
121    /// the container is still present afterwards.
122    pub async fn terminate(&self) -> Result<TerminateOutcome> {
123        // `rm --force` succeeds silently for a missing container on current
124        // daemons, so presence is established with `inspect` first. Only a
125        // clean miss short-circuits: unknown presence and probe errors both
126        // proceed, since `rm` below surfaces the truth and a probe failure
127        // must never block the real removal.
128        if matches!(self.present().await, Ok(Presence::Missing)) {
129            return Ok(TerminateOutcome::AlreadyGone);
130        }
131        let output = run_docker(&[
132            OsString::from("rm"),
133            OsString::from("--force"),
134            OsString::from(&self.id),
135        ])
136        .await?;
137        if !output.status.success() {
138            let diagnostic = diagnostic_text(&output.stderr);
139            if is_missing_message(&diagnostic) {
140                return Ok(TerminateOutcome::AlreadyGone);
141            }
142            bail!("could not remove browser container {}: {diagnostic}", self.id);
143        }
144        // Verify removal; retry an unreadable answer so one daemon blip
145        // cannot turn a successful teardown into a false alarm.
146        for _ in 0..3 {
147            match self.present().await? {
148                Presence::Missing => return Ok(TerminateOutcome::Removed),
149                Presence::Exists => {
150                    bail!("browser container {} is still present", self.id);
151                }
152                Presence::Unknown => tokio::time::sleep(IDENTIFY_INTERVAL).await,
153            }
154        }
155        bail!("could not verify removal of browser container {}", self.id);
156    }
157
158    /// Presence of the exact container: exists, cleanly missing, or
159    /// unreadable.
160    async fn present(&self) -> Result<Presence> {
161        let output = run_docker(&[OsString::from("inspect"), OsString::from(&self.id)]).await?;
162        if output.status.success() {
163            return Ok(Presence::Exists);
164        }
165        if is_missing_message(&diagnostic_text(&output.stderr)) {
166            return Ok(Presence::Missing);
167        }
168        Ok(Presence::Unknown)
169    }
170}
171
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173enum Presence {
174    Exists,
175    Missing,
176    Unknown,
177}
178
179/// Whether the reference carries a tag or digest. A registry port colon
180/// (`registry:5000/foo`) is not a tag: only a colon after the last slash
181/// counts. Mirrors the config fail-fast in
182/// `vtcode_config::computer_use`.
183fn has_image_pin(image: &str) -> bool {
184    if image.contains('@') {
185        return true;
186    }
187    match image.rsplit_once('/') {
188        Some((_, last)) => last.contains(':'),
189        None => image.contains(':'),
190    }
191}
192
193/// Whether docker reports the target as absent across command wordings
194/// (`rm` says container, `inspect` says object).
195fn is_missing_message(diagnostic: &str) -> bool {
196    let lower = diagnostic.to_ascii_lowercase();
197    lower.contains("no such container") || lower.contains("no such object")
198}
199
200/// Whether a Docker daemon answers. Callers use this to skip container-backed
201/// checks (and to refuse the browser target) without failing the run.
202pub async fn docker_available() -> bool {
203    let Ok(mut child) = Command::new("docker")
204        .arg("info")
205        .stdin(std::process::Stdio::null())
206        .stdout(std::process::Stdio::null())
207        .stderr(std::process::Stdio::null())
208        .kill_on_drop(true)
209        .spawn()
210    else {
211        return false;
212    };
213    tokio::time::timeout(AVAILABILITY_TIMEOUT, child.wait())
214        .await
215        .is_ok_and(|status| status.is_ok_and(|status| status.success()))
216}
217
218/// Whether a directory can appear unquoted in a `--mount` spec: no separator,
219/// quoting, or control characters. Fail-closed on anything ambiguous.
220fn mount_spec_safe(dir: &str) -> bool {
221    !dir.is_empty() && !dir.chars().any(|c| c.is_control() || matches!(c, ',' | '"' | '\\'))
222}
223
224fn docker_run_argv(spec: &ContainerSpec, name: &str) -> Vec<OsString> {
225    [
226        "run",
227        "--rm",
228        "--interactive",
229        "--init",
230        "--pull=never",
231        "--network=none",
232        "--read-only",
233        "--cap-drop=ALL",
234        "--user=65534",
235        "--security-opt=no-new-privileges",
236        "--pids-limit=256",
237        "--memory=1g",
238        "--tmpfs=/tmp:rw,nosuid,nodev,noexec,size=512m",
239        "--env=HOME=/tmp",
240    ]
241    .into_iter()
242    .map(OsString::from)
243    .chain([
244        OsString::from(format!("--name={name}")),
245        OsString::from(format!("--mount=type=bind,src={},dst=/build,readonly", spec.build_dir)),
246        OsString::from(&spec.image),
247    ])
248    .collect()
249}
250
251async fn inspect_container_id(name: &str, child: &mut Child) -> Result<String> {
252    let start = tokio::time::Instant::now();
253    loop {
254        if let Some(status) = child.try_wait().context("could not poll the browser container")? {
255            bail!(
256                "browser container exited before its identity could be established: {status}: {}",
257                drain_stderr(child).await
258            );
259        }
260        let output = run_docker(&[
261            OsString::from("inspect"),
262            OsString::from("--format={{.Id}}"),
263            OsString::from(name),
264        ])
265        .await?;
266        if output.status.success() {
267            if let Ok(id) = parse_container_id(&String::from_utf8_lossy(&output.stdout)) {
268                return Ok(id);
269            }
270        }
271        ensure!(start.elapsed() < IDENTIFY_TIMEOUT, "could not identify the browser container");
272        tokio::time::sleep(IDENTIFY_INTERVAL).await;
273    }
274}
275
276async fn drain_stderr(child: &mut Child) -> String {
277    use tokio::io::AsyncReadExt;
278    let mut stderr = String::new();
279    if let Some(mut pipe) = child.stderr.take() {
280        // Best effort: partial stderr is still useful diagnostics.
281        let _drained = tokio::time::timeout(Duration::from_secs(2), pipe.read_to_string(&mut stderr)).await;
282    }
283    diagnostic_text(stderr.as_bytes())
284}
285
286fn parse_container_id(raw: &str) -> Result<String> {
287    let id = raw.trim().to_owned();
288    ensure!(
289        id.len() == CONTAINER_ID_LEN && id.chars().all(|c| c.is_ascii_hexdigit()),
290        "could not identify the browser container"
291    );
292    Ok(id)
293}
294
295async fn run_docker(args: &[OsString]) -> Result<std::process::Output> {
296    let child = Command::new("docker")
297        .args(args)
298        .stdin(std::process::Stdio::null())
299        .stdout(std::process::Stdio::piped())
300        .stderr(std::process::Stdio::piped())
301        .kill_on_drop(true)
302        .spawn()
303        .context("could not run docker")?;
304    // Dropping the timed-out future drops the child, and `kill_on_drop`
305    // stops the docker client it was waiting on.
306    match tokio::time::timeout(DOCKER_TIMEOUT, child.wait_with_output()).await {
307        Ok(output) => output.context("could not read docker output"),
308        Err(_) => bail!("docker command timed out"),
309    }
310}
311
312fn diagnostic_text(output: &[u8]) -> String {
313    let text = String::from_utf8_lossy(output);
314    let end = text.floor_char_boundary(DIAGNOSTIC_MAX_BYTES.min(text.len()));
315    text.get(..end).unwrap_or_default().to_owned()
316}
317
318#[cfg(test)]
319mod tests;