From f78f8fd4bc03eac89e14e26779b888c634839244 Mon Sep 17 00:00:00 2001 From: Sunil Kumar Vadlamani <25136458+sunilteja93@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:55:44 -0800 Subject: [PATCH 1/4] test(sandbox): preserve nested userns denial baseline Signed-off-by: Sunil Kumar Vadlamani <25136458+sunilteja93@users.noreply.github.com> --- e2e/rust/tests/chromium_boundary_baseline.rs | 45 ++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 e2e/rust/tests/chromium_boundary_baseline.rs diff --git a/e2e/rust/tests/chromium_boundary_baseline.rs b/e2e/rust/tests/chromium_boundary_baseline.rs new file mode 100644 index 0000000000..e867241a38 --- /dev/null +++ b/e2e/rust/tests/chromium_boundary_baseline.rs @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#![cfg(feature = "e2e-podman")] + +use openshell_e2e::harness::sandbox::SandboxGuard; + +const USERNS_PROBE: &str = r#" +import ctypes +import errno +import sys + +libc = ctypes.CDLL(None, use_errno=True) +libc.unshare.argtypes = [ctypes.c_int] +libc.unshare.restype = ctypes.c_int + +CLONE_NEWUSER = 0x10000000 + +result = libc.unshare(CLONE_NEWUSER) +error = ctypes.get_errno() + +if result == -1 and error == errno.EPERM: + print("WORKLOAD_USERNS_DENIED") +else: + print(f"UNEXPECTED_USERNS_RESULT result={result} errno={error}") + sys.exit(1) +"#; + +#[tokio::test] +async fn existing_workload_rejects_nested_user_namespaces() { + let mut sandbox = SandboxGuard::create(&[]) + .await + .expect("create baseline OpenShell sandbox"); + + let result = sandbox.exec(&["python3", "-c", USERNS_PROBE]).await; + + sandbox.cleanup().await; + + let output = result.expect("namespace denial must be observable"); + + assert!( + output.contains("WORKLOAD_USERNS_DENIED"), + "existing workload isolation must remain enforced: {output}" + ); +} From 527c67c583c9d7b8537909afee33d104219f7e12 Mon Sep 17 00:00:00 2001 From: Sunil Kumar Vadlamani <25136458+sunilteja93@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:14:40 -0800 Subject: [PATCH 2/4] test(sandbox): verify Chromium isolation boundary invariants Signed-off-by: Sunil Kumar Vadlamani <25136458+sunilteja93@users.noreply.github.com> --- e2e/chromium/README.md | 102 +++++++++++++++++++ e2e/rust/tests/chromium_boundary_baseline.rs | 52 +++++++--- 2 files changed, 142 insertions(+), 12 deletions(-) create mode 100644 e2e/chromium/README.md diff --git a/e2e/chromium/README.md b/e2e/chromium/README.md new file mode 100644 index 0000000000..33dd3cf841 --- /dev/null +++ b/e2e/chromium/README.md @@ -0,0 +1,102 @@ +# Chromium isolation for OpenShell — #4098 + +> **Design and verification work in progress.** This directory does not yet +> provide supported Chromium execution, and the existing browser probe is +> currently expected to fail. Do not use `--no-sandbox` to make it pass. + +## Goal and non-negotiable invariants + +Enable Chromium/Playwright with Chromium's **own user-namespace and seccomp +sandbox** while preserving the existing *agent workload* restrictions: + +- Ordinary agent processes continue to lack effective and bounding + capabilities, with `no_new_privs=1` and OpenShell seccomp enforcement. +- The workload cannot create nested user namespaces or invoke `chroot`. +- The browser cannot access supervisor credentials, gateway secrets, + agent workspace files by default, or another sandbox's control/data. +- The browser has no direct Internet-facing interface, no host network, + no privileged container, and no broad host mounts. +- Browser egress is mediated by OpenShell's supervisor **before** any + destination connection; the browser cannot override DNS or proxy routes. +- Control is authenticated and bound to sandbox identity and runtime + generation, not exposed as an unauthenticated CDP TCP listener. +- If any required enforcement cannot be established or inspected, + provisioning fails closed. No `--no-sandbox` fallback. + +The ordinary workload baseline is executable as +`e2e/rust/tests/chromium_boundary_baseline.rs` in the Podman E2E lane. + +## Current evidence (not an implementation) + +At OpenShell base `8ff5b6087`, the baseline Podman E2E suite passed 77 +conformance tests, and the ordinary-workload nested-userns denial test passed. +In a **separate standalone Podman control**, Chromium failed with +`sys_chroot("/proc/self/fdinfo/") == 0`; direct `chroot /` also returned `EPERM` +under `--cap-drop=all --security-opt=no-new-privileges`. A nested user +namespace could be created in that standalone container, but could not make +`chroot` succeed. This is consistent with an inherited OCI seccomp decision, +not definitive proof of the specific denying layer. + +In an earlier *diagnostic-only* OpenShell worktree, user namespace creation +could be made to succeed through opt-in changes, yet mount namespace creation +continued to fail with `EPERM` and Chromium reported `No usable sandbox!`. +Those opt-in changes are **not** part of the proposed production solution. + +## Candidate architecture (not yet approved) + +```text + ordinary agent workload + existing seccomp/Landlock, network=none + | + authenticated, sandbox-scoped browser control + | + isolated browser execution boundary + no agent mounts, no supervisor secrets, no direct egress + | + authenticated, policy-mediated egress adapter + | + trusted OpenShell supervisor -> approved destination +``` + +Do not treat a local Chrome proxy flag as the egress security boundary. +A browser can initiate non-proxy sockets, DNS and loopback requests. The +**outer** browser network fence must prevent all unauthorized routes, +including when the browser or renderer is compromised. The egress adapter +must retain policy attribution, DNS validation, TLS/L7 rules, policy reload +semantics and audit events; inability to enforce these means fail closed. + +The browser boundary also needs independent security review: Chromium requires +operations that the existing agent workload forbids. Enabling them in a new +boundary is not equivalent to proving that the boundary is secure. A Podman +sidecar may require an explicitly validated runtime profile; a microVM +implementation may instead require a separate guest. Neither is implemented +or approved by this document. + +## Required implementation gates + +1. **Product scope:** Maintainer acceptance that a separately managed browser + execution boundary satisfies #4098's *in-guest* Chromium requirement. +2. **Identity and lifecycle:** Only gateway/driver-authorized sandbox sessions + can create and access the browser. Close control connections and terminate + the browser on stop/delete, restart or generation mismatch, and supervisor + failure. Reconnection and cleanup must be idempotent. +3. **Filesystem and process isolation:** No supervisor secrets or implicit + workspace mounts; non-root default, capability budget justified per + boundary; all mount points and runtime identity verified after creation. +4. **Network and control:** No host/bridge route from the browser; authenticated + non-public CDP bridge; every external connection governed by the same + destination and L7 rules as the agent, including after a policy reload. +5. **Native Chromium sandbox:** Verify `chrome://sandbox` in addition to + renderer namespace, seccomp, `NoNewPrivs` and capability state. Verify + that Chromium does not automatically fall back to `--no-sandbox`. +6. **Adversarial tests:** Unauthorized CDP access, raw TCP/UDP/DNS egress, + metadata/loopback access, secret and agent-file reads, policy reload, + symlink/mount attacks, driver crash, and cross-sandbox access must fail. +7. **Runtime support:** Podman and microVM coverage per the issue, with an + explicit unsupported-runtime error when any mandatory isolation feature + cannot be provided. + +A PR is **not complete** merely because it starts Chromium or because the +agent-workload regression test passes. Native Chromium sandbox operation, +policy-governed networking, and a real adversarial E2E pass are the merge +criteria. diff --git a/e2e/rust/tests/chromium_boundary_baseline.rs b/e2e/rust/tests/chromium_boundary_baseline.rs index e867241a38..3ae215fae1 100644 --- a/e2e/rust/tests/chromium_boundary_baseline.rs +++ b/e2e/rust/tests/chromium_boundary_baseline.rs @@ -3,9 +3,13 @@ #![cfg(feature = "e2e-podman")] +//! Security invariants for the *ordinary agent workload* while Chromium +//! compatibility is developed in a separate execution boundary. This is not a +//! Chromium functionality test; it must stay green when browser support ships. + use openshell_e2e::harness::sandbox::SandboxGuard; -const USERNS_PROBE: &str = r#" +const WORKLOAD_BOUNDARY_PROBE: &str = r#" import ctypes import errno import sys @@ -13,33 +17,57 @@ import sys libc = ctypes.CDLL(None, use_errno=True) libc.unshare.argtypes = [ctypes.c_int] libc.unshare.restype = ctypes.c_int +libc.chroot.argtypes = [ctypes.c_char_p] +libc.chroot.restype = ctypes.c_int -CLONE_NEWUSER = 0x10000000 +with open('/proc/self/status', encoding='utf-8') as status_file: + fields = dict(line.split(':', 1) for line in status_file if ':' in line) + +def field(name): + return fields.get(name, '').strip().split()[0] if fields.get(name, '').strip() else '' + +def require(name, predicate): + if not predicate: + print(f'WORKLOAD_INVARIANT_FAILED {name}', flush=True) + sys.exit(1) + print(f'WORKLOAD_INVARIANT_OK {name}', flush=True) + +require('no_new_privs', field('NoNewPrivs') == '1') +require('no_effective_caps', int(field('CapEff') or '0', 16) == 0) +require('no_bounding_caps', int(field('CapBnd') or '0', 16) == 0) +require('seccomp_filter', field('Seccomp') == '2') +CLONE_NEWUSER = 0x10000000 +ctypes.set_errno(0) result = libc.unshare(CLONE_NEWUSER) error = ctypes.get_errno() +require('nested_userns_denied', result == -1 and error == errno.EPERM) + +# chroot('/') deliberately avoids special paths and cannot be confused with +# a failure to resolve a target executable after a successful chroot. +ctypes.set_errno(0) +result = libc.chroot(b'/') +error = ctypes.get_errno() +require('chroot_denied', result == -1 and error == errno.EPERM) -if result == -1 and error == errno.EPERM: - print("WORKLOAD_USERNS_DENIED") -else: - print(f"UNEXPECTED_USERNS_RESULT result={result} errno={error}") - sys.exit(1) +print('WORKLOAD_BOUNDARY_INTACT', flush=True) "#; #[tokio::test] -async fn existing_workload_rejects_nested_user_namespaces() { +async fn existing_workload_preserves_browser_boundary_invariants() { let mut sandbox = SandboxGuard::create(&[]) .await .expect("create baseline OpenShell sandbox"); - let result = sandbox.exec(&["python3", "-c", USERNS_PROBE]).await; + let result = sandbox + .exec(&["python3", "-c", WORKLOAD_BOUNDARY_PROBE]) + .await; sandbox.cleanup().await; - let output = result.expect("namespace denial must be observable"); - + let output = result.expect("security invariants must be observable"); assert!( - output.contains("WORKLOAD_USERNS_DENIED"), + output.contains("WORKLOAD_BOUNDARY_INTACT"), "existing workload isolation must remain enforced: {output}" ); } From 77860a391462014160011167cccbab31b205f4a8 Mon Sep 17 00:00:00 2001 From: Sunil Kumar Vadlamani <25136458+sunilteja93@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:23:37 -0800 Subject: [PATCH 3/4] test(browser): verify native Chromium sandbox in restricted Podman Signed-off-by: Sunil Kumar Vadlamani <25136458+sunilteja93@users.noreply.github.com> --- e2e/chromium/Dockerfile | 18 ++++ e2e/chromium/verify-sandbox.sh | 60 ++++++++++++ e2e/rust/tests/chromium_podman_native.rs | 118 +++++++++++++++++++++++ 3 files changed, 196 insertions(+) create mode 100644 e2e/chromium/Dockerfile create mode 100755 e2e/chromium/verify-sandbox.sh create mode 100644 e2e/rust/tests/chromium_podman_native.rs diff --git a/e2e/chromium/Dockerfile b/e2e/chromium/Dockerfile new file mode 100644 index 0000000000..0b6f509bc6 --- /dev/null +++ b/e2e/chromium/Dockerfile @@ -0,0 +1,18 @@ +FROM debian:bookworm-slim + +RUN apt-get update && \ + DEBIAN_FRONTEND=noninteractive apt-get install -y \ + --no-install-recommends \ + chromium ca-certificates util-linux fonts-liberation \ + && rm -rf /var/lib/apt/lists/* \ + && groupadd -g 1000 sandbox \ + && useradd -u 1000 -g 1000 -m -s /bin/sh sandbox \ + && mkdir -p /sandbox \ + && chown sandbox:sandbox /sandbox + +COPY --chmod=0555 verify-sandbox.sh /usr/local/bin/verify-sandbox + +USER sandbox:sandbox +WORKDIR /sandbox +ENV HOME=/sandbox +CMD ["sleep", "infinity"] diff --git a/e2e/chromium/verify-sandbox.sh b/e2e/chromium/verify-sandbox.sh new file mode 100755 index 0000000000..7eda458fb6 --- /dev/null +++ b/e2e/chromium/verify-sandbox.sh @@ -0,0 +1,60 @@ +#!/bin/sh +set -eu + +baseline_ns=$(readlink /proc/self/ns/user) +baseline_filters=$(awk '/^Seccomp_filters:/ {print $2}' /proc/self/status) + +chromium \ + --headless \ + --disable-gpu \ + --disable-dev-shm-usage \ + --no-first-run \ + --user-data-dir=/tmp/chromium-e2e-profile \ + about:blank >/tmp/chromium-e2e.log 2>&1 & + +browser_pid=$! +trap 'kill "$browser_pid" 2>/dev/null || true' EXIT + +sleep 5 + +verified=0 + +for proc in /proc/[0-9]*; do + executable=$(readlink "$proc/exe" 2>/dev/null || true) + + case "$executable" in + */chromium|*/chrome) ;; + *) continue ;; + esac + + args=$(tr '\000' ' ' < "$proc/cmdline" 2>/dev/null || true) + + case "$args" in + *--type=renderer*) ;; + *) continue ;; + esac + + namespace=$(readlink "$proc/ns/user" 2>/dev/null || true) + nnp=$(awk '/^NoNewPrivs:/ {print $2}' "$proc/status" 2>/dev/null || true) + seccomp=$(awk '/^Seccomp:/ {print $2}' "$proc/status" 2>/dev/null || true) + filters=$(awk '/^Seccomp_filters:/ {print $2}' "$proc/status" 2>/dev/null || true) + capabilities=$(awk '/^CapEff:/ {print $2}' "$proc/status" 2>/dev/null || true) + + if [ "$namespace" != "$baseline_ns" ] && + [ -n "$namespace" ] && + [ "$nnp" = 1 ] && + [ "$seccomp" = 2 ] && + [ "$capabilities" = 0000000000000000 ] && + [ -n "$filters" ] && + [ "$filters" -gt "$baseline_filters" ]; then + verified=$((verified + 1)) + fi +done + +if [ "$verified" -lt 1 ]; then + echo "CHROMIUM_SANDBOX_VERIFICATION_FAILED" + tail -n 30 /tmp/chromium-e2e.log + exit 1 +fi + +echo "CHROMIUM_SANDBOX_VERIFIED renderers=$verified" diff --git a/e2e/rust/tests/chromium_podman_native.rs b/e2e/rust/tests/chromium_podman_native.rs new file mode 100644 index 0000000000..111adac4e2 --- /dev/null +++ b/e2e/rust/tests/chromium_podman_native.rs @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#![cfg(feature = "e2e-podman")] + +//! Standalone Podman control for Chromium's native Linux renderer sandbox. +//! +//! This is deliberately NOT an OpenShell browser-integration test. It proves +//! the browser fixture can start with an isolated netns, no_new_privs, runtime +//! seccomp, and a narrowly scoped OCI capability request. The ordinary agent +//! workload must continue to have *no* capabilities (see +//! `chromium_boundary_baseline.rs`). + +use openshell_e2e::harness::container::{ContainerEngine, ImageGuard}; +use std::path::PathBuf; +use std::process::Output; + +const SYS_CHROOT_CAPABILITY_BIT: u64 = 1 << 18; + +fn browser_run(engine: &ContainerEngine, image: &str, command: &[&str]) -> Output { + let mut cmd = engine.command(); + cmd.args([ + "run", + "--rm", + "--network=none", + "--cap-drop=all", + "--cap-add=SYS_CHROOT", + "--security-opt=no-new-privileges", + image, + ]); + cmd.args(command); + cmd.output().expect("execute constrained Podman browser probe") +} + +fn combined_output(output: &Output) -> String { + format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ) +} + +fn status_value<'a>(status: &'a str, key: &str) -> &'a str { + status + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + (name == key).then_some(value.trim()) + }) + .unwrap_or_else(|| panic!("missing {key} in /proc/self/status")) +} + +#[test] +fn chromium_native_renderer_sandbox_starts_in_constrained_podman() { + let context = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../chromium"); + let image = ImageGuard::build("chromium-native", &context.join("Dockerfile"), &context) + .expect("build isolated Chromium fixture"); + let engine = ContainerEngine::from_env().expect("resolve Podman engine"); + assert_eq!(engine.name(), "podman", "only Podman is covered by this control"); + + // Verify the *outer* browser process before running Chromium. A successful + // renderer check must not mask broader-than-intended OCI capabilities. + let status = browser_run(&engine, image.tag(), &["cat", "/proc/self/status"]); + assert!( + status.status.success(), + "read outer browser-process status: {}", + combined_output(&status) + ); + let status = String::from_utf8_lossy(&status.stdout); + assert_eq!(status_value(&status, "NoNewPrivs"), "1"); + assert_eq!(status_value(&status, "Seccomp"), "2"); + for key in ["CapInh", "CapPrm", "CapEff", "CapBnd", "CapAmb"] { + let mask = u64::from_str_radix(status_value(&status, key), 16) + .unwrap_or_else(|_| panic!("non-hex {key} in /proc/self/status")); + assert_eq!( + mask & !SYS_CHROOT_CAPABILITY_BIT, + 0, + "{key} contains capabilities beyond CAP_SYS_CHROOT: {mask:#x}" + ); + if key == "CapBnd" { + assert_ne!( + mask & SYS_CHROOT_CAPABILITY_BIT, + 0, + "Podman did not install the expected CAP_SYS_CHROOT bounding bit" + ); + } + } + + // The browser-side control has no default IPv4 route. This is a control + // for the standalone fixture only, not proof of production egress policy. + let routes = browser_run(&engine, image.tag(), &["cat", "/proc/net/route"]); + assert!( + routes.status.success(), + "inspect browser network routes: {}", + combined_output(&routes) + ); + let routes = String::from_utf8_lossy(&routes.stdout); + for row in routes.lines().skip(1) { + let columns = row.split_whitespace().collect::>(); + if columns.len() >= 2 { + assert_ne!( + columns[1], "00000000", + "unexpected default IPv4 route in --network=none browser: {row}" + ); + } + } + + // The script must run Chromium without --no-sandbox and inspect live + // renderer namespaces, seccomp, no_new_privs, and effective capabilities. + // chrome://sandbox and end-to-end policy isolation are separate gates. + let probe = browser_run(&engine, image.tag(), &["/usr/local/bin/verify-sandbox"]); + let output = combined_output(&probe); + assert!(probe.status.success(), "native Chromium probe failed:\n{output}"); + assert!( + output.contains("CHROMIUM_SANDBOX_VERIFIED"), + "renderer sandbox verification marker absent:\n{output}" + ); +} From a1fbbe79994f874e639265eb49782c1116aed359 Mon Sep 17 00:00:00 2001 From: Sunil Kumar Vadlamani <25136458+sunilteja93@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:32:23 -0800 Subject: [PATCH 4/4] feat(podman): define isolated Chromium browser container spec Signed-off-by: Sunil Kumar Vadlamani <25136458+sunilteja93@users.noreply.github.com> --- .../openshell-driver-podman/src/container.rs | 194 ++++++++++++++++++ 1 file changed, 194 insertions(+) diff --git a/crates/openshell-driver-podman/src/container.rs b/crates/openshell-driver-podman/src/container.rs index 06f31c740d..7157ff8ce7 100644 --- a/crates/openshell-driver-podman/src/container.rs +++ b/crates/openshell-driver-podman/src/container.rs @@ -1606,6 +1606,104 @@ impl IsolationSpecs { } } +/// Build the OCI browser execution spec without inheriting workload or +/// supervisor credentials, mounts, devices, environment, or network access. +/// +/// `browser_image` must be resolved from an operator-controlled image and +/// pinned to an immutable Podman image ID before calling this function. +/// `entrypoint` must be selected by the trusted driver, never by the agent. +/// This builder does not authorize access to the browser. The caller must +/// provide an authenticated control channel and full lifecycle management +/// before a browser container can be started. +pub fn build_browser_container_spec( + sandbox: &DriverSandbox, + config: &PodmanComputeConfig, + browser_image: &ResolvedPodmanImage, + entrypoint: &str, + command: &[String], +) -> Result { + let digest = browser_image.id.strip_prefix("sha256:").ok_or_else(|| { + ComputeDriverError::Precondition("browser image must be pinned to a sha256 image ID".into()) + })?; + if digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(ComputeDriverError::Precondition( + "browser image has an invalid sha256 image ID".into(), + )); + } + if !entrypoint.starts_with('/') + || entrypoint + .split('/') + .skip(1) + .any(|part| part.is_empty() || part == "." || part == "..") + || entrypoint.bytes().any(|byte| byte == 0) + { + return Err(ComputeDriverError::InvalidArgument( + "browser entrypoint must be an absolute, normalized path".into(), + )); + } + if config + .userns + .as_deref() + .is_some_and(|mode| mode.split(':').next() == Some("host")) + { + return Err(ComputeDriverError::Precondition( + "browser execution rejects host user namespaces".into(), + )); + } + + // Reuse the driver-owned OCI fields and resource limits, but no runtime + // fields that could be influenced by an agent template may cross roles. + let mut browser = build_base_spec(sandbox, config, None, None, browser_image, None, None)?; + browser.name = format!("openshell-browser-{}", sandbox.id); + crate::client::validate_name(&browser.name) + .map_err(|error| ComputeDriverError::InvalidArgument(error.to_string()))?; + browser.labels = BTreeMap::from([ + (LABEL_MANAGED.into(), "true".into()), + (LABEL_SANDBOX_ID.into(), sandbox.id.clone()), + (LABEL_SANDBOX_NAME.into(), sandbox.name.clone()), + (LABEL_SANDBOX_NAMESPACE.into(), sandbox.namespace.clone()), + (LABEL_SANDBOX_WORKSPACE.into(), sandbox.workspace.clone()), + (crate::isolation::LABEL_ROLE.into(), "browser".into()), + ]); + browser.hostname = format!("browser-{}", sandbox.id); + browser.env.clear(); + browser.unsetenv = browser_image + .environment + .iter() + .filter_map(|value| value.split_once('=').map(|(key, _)| key.to_string())) + .collect(); + browser.entrypoint = vec![entrypoint.to_string()]; + browser.command = command.to_vec(); + browser.user = "1000:1000".into(); + browser.groups.clear(); + browser.work_dir = "/sandbox".into(); + browser.cap_drop = vec!["ALL".into()]; + browser.cap_add = vec!["SYS_CHROOT".into()]; + browser.no_new_privileges = true; + // Keep the runtime's default seccomp filter. Never use "unconfined". + browser.seccomp_profile_path.clear(); + browser.sysctl.clear(); + browser.volumes.clear(); + browser.image_volumes.clear(); + browser.mounts.clear(); + browser.secret_env.clear(); + browser.secrets.clear(); + browser.hostadd.clear(); + browser.dns_search.clear(); + browser.dns_option.clear(); + browser.use_image_resolve_conf = None; + browser.netns.nsmode = "none".into(); + browser.networks.clear(); + browser.portmappings.clear(); + browser.devices = None; + browser.userns = None; + browser.idmappings = None; + browser.healthconfig.test = vec!["NONE".into()]; + browser.restart_policy = "no".into(); + browser.image_pull_policy = "never".into(); + Ok(browser) +} + pub fn build_isolation_specs( input: IsolationSpecInput<'_>, ) -> Result { @@ -1934,6 +2032,102 @@ mod tests { use crate::client::ImageConfig; use openshell_core::proto::compute::v1::{GpuResourceRequirements, ResourceRequirements}; + #[test] + fn browser_spec_isolated_from_agent_control_and_egress() { + let mut sandbox = test_sandbox("browser-test", "browser-test"); + sandbox.namespace = "project".into(); + let mut image = resolved_image( + "operator/browser", + &format!("sha256:{}", "a".repeat(64)), + "sandbox:sandbox", + "/sandbox", + ); + image.environment = vec!["LD_PRELOAD=/tmp/attacker.so".into()]; + let spec = build_browser_container_spec( + &sandbox, + &test_config(), + &image, + "/usr/local/bin/verify-sandbox", + &[], + ) + .expect("build isolated browser spec"); + let value = serde_json::to_value(spec).expect("encode browser Podman spec"); + + assert_eq!(value["name"], "openshell-browser-browser-test"); + assert_eq!(value["labels"][crate::isolation::LABEL_ROLE], "browser"); + assert_eq!(value["user"], "1000:1000"); + assert_eq!(value["cap_drop"], serde_json::json!(["ALL"])); + assert_eq!(value["cap_add"], serde_json::json!(["SYS_CHROOT"])); + assert_eq!(value["no_new_privileges"], true); + assert_eq!(value["netns"]["nsmode"], "none"); + assert_eq!(value["image_pull_policy"], "never"); + assert_eq!(value["restart_policy"], "no"); + assert!(value["networks"].as_object().unwrap().is_empty()); + for field in [ + "volumes", + "image_volumes", + "mounts", + "secrets", + "portmappings", + "hostadd", + "groups", + "devices", + ] { + assert!( + value[field].is_null() || value[field].as_array().is_some_and(Vec::is_empty), + "browser spec inherited forbidden {field}: {}", + value[field], + ); + } + assert!(value["secret_env"].as_object().unwrap().is_empty()); + assert!(value["env"].as_object().unwrap().is_empty()); + assert!( + value["unsetenv"] + .as_array() + .unwrap() + .contains(&serde_json::json!("LD_PRELOAD")) + ); + assert!(value["seccomp_profile_path"].is_null()); + } + + #[test] + fn browser_spec_rejects_unsafe_operator_inputs() { + let sandbox = test_sandbox("browser-test", "browser-test"); + let image = resolved_image( + "operator/browser", + "mutable:latest", + "1000:1000", + "/sandbox", + ); + assert!( + build_browser_container_spec( + &sandbox, + &test_config(), + &image, + "/usr/bin/chromium", + &[], + ) + .is_err() + ); + + let pinned = resolved_image( + "operator/browser", + &format!("sha256:{}", "a".repeat(64)), + "1000:1000", + "/sandbox", + ); + let mut config = test_config(); + config.userns = Some("host".into()); + assert!( + build_browser_container_spec(&sandbox, &config, &pinned, "/usr/bin/chromium", &[],) + .is_err() + ); + assert!( + build_browser_container_spec(&sandbox, &test_config(), &pinned, "../../bin/sh", &[],) + .is_err() + ); + } + static ENV_LOCK: std::sync::LazyLock> = std::sync::LazyLock::new(|| std::sync::Mutex::new(()));