Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 194 additions & 0 deletions crates/openshell-driver-podman/src/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are these podman-only? What are the expectations for the other drivers?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @elezar, that's a valid point.

The initial implementation is podman-specific because I started with the runtime where I could reproduce the Chromium namespace restriction and validate native chromium renderer sandboxing in a standalone, restricted container.

I don't intend podman-only support to be the final scope of #4098. The issue explicitly covers both Podman and microVM, so both need supported implementations and regression coverage. For Docker and Kubernetes, I haven't validated an equivalent boundary yet, and I wouldn't want to claim support or relax their existing security restrictions.

My preference is to keep the security requirements runtime-independent, while allowing each driver to implement and verify an appropriate isolation mechanism. Unsupported configurations should fail explicitly without falling back to "--no-sandbox".

Would you prefer a shared browser-execution capability or contract across compute drivers, with runtime-specific implementations, rather than introducing the browser specification directly in the Podman driver?

I also want to confirm whether the separately managed browser boundary is an acceptable direction before extending the implementation.

Happy to adjust the design based on your guidance.

sandbox: &DriverSandbox,
config: &PodmanComputeConfig,
browser_image: &ResolvedPodmanImage,
entrypoint: &str,
command: &[String],
) -> Result<ContainerSpec, ComputeDriverError> {
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<IsolationSpecs, ComputeDriverError> {
Expand Down Expand Up @@ -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::Mutex<()>> =
std::sync::LazyLock::new(|| std::sync::Mutex::new(()));

Expand Down
18 changes: 18 additions & 0 deletions e2e/chromium/Dockerfile
Original file line number Diff line number Diff line change
@@ -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"]
102 changes: 102 additions & 0 deletions e2e/chromium/README.md
Original file line number Diff line number Diff line change
@@ -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.
60 changes: 60 additions & 0 deletions e2e/chromium/verify-sandbox.sh
Original file line number Diff line number Diff line change
@@ -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"
Loading
Loading