diff --git a/.github/workflows/branch-checks.yml b/.github/workflows/branch-checks.yml
index 613793092b..80573e3871 100644
--- a/.github/workflows/branch-checks.yml
+++ b/.github/workflows/branch-checks.yml
@@ -294,6 +294,7 @@ jobs:
cargo fmt --manifest-path tests/tmachine/Cargo.toml --all -- --check
cargo fmt --manifest-path tests/runner/Cargo.toml --all -- --check
cargo fmt --manifest-path tests/suites/conformance/Cargo.toml --all -- --check
+ cargo fmt --manifest-path tests/suites/drivers/docker/Cargo.toml --all -- --check
cargo fmt --manifest-path tests/suites/drivers/podman/Cargo.toml --all -- --check
cargo fmt --manifest-path tests/suites/features/Cargo.toml --all -- --check
cargo fmt --manifest-path tests/support/Cargo.toml --all -- --check
@@ -359,6 +360,7 @@ jobs:
cargo clippy --locked --manifest-path tests/tmachine/Cargo.toml --all-targets -- -D warnings
cargo clippy --locked --manifest-path tests/runner/Cargo.toml --all-targets -- -D warnings
cargo clippy --locked --manifest-path tests/suites/conformance/Cargo.toml --workspace --all-targets -- -D warnings
+ cargo clippy --locked --manifest-path tests/suites/drivers/docker/Cargo.toml --workspace --all-targets -- -D warnings
cargo clippy --locked --manifest-path tests/suites/drivers/podman/Cargo.toml --workspace --all-targets -- -D warnings
cargo clippy --locked --manifest-path tests/suites/features/Cargo.toml --workspace --all-targets -- -D warnings
cargo clippy --locked --manifest-path tests/support/Cargo.toml --all-targets -- -D warnings
diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml
index 71e193beac..1c311c18b7 100644
--- a/.github/workflows/branch-e2e.yml
+++ b/.github/workflows/branch-e2e.yml
@@ -247,7 +247,7 @@ jobs:
set -euo pipefail
# Retry dependency preparation, then build once.
nix build --no-link .#openshell-test-runner || nix build --no-link .#openshell-test-runner
- for family in features drivers/podman; do
+ for family in features drivers/docker drivers/podman; do
nix run .#openshell-test-runner -- build \
--family "$family" --out "artifacts/e2e-bundles/${family//\//-}"
done
@@ -257,6 +257,12 @@ jobs:
path: artifacts/e2e-bundles/features
retention-days: 5
if-no-files-found: error
+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: openshell-e2e-bundle-drivers-docker-x86_64-unknown-linux-musl
+ path: artifacts/e2e-bundles/drivers-docker
+ retention-days: 5
+ if-no-files-found: error
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: openshell-e2e-bundle-drivers-podman-x86_64-unknown-linux-musl
diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml
index 361737cb7a..39cbbfb9c3 100644
--- a/.github/workflows/e2e-suites.yml
+++ b/.github/workflows/e2e-suites.yml
@@ -10,8 +10,8 @@
# results. With `prebuilt`, the rows run what the caller built once for the
# run instead: conformance rows the static `openshell-conformance`, the other
# rows their family's test bundle. The `family` input selects the rows of one
-# family, including the workspaces under it (drivers selects drivers/podman);
-# leave it empty to run every row.
+# family, including the workspaces under it (drivers selects drivers/docker
+# and drivers/podman); leave it empty to run every row.
name: E2E Suites
@@ -90,6 +90,9 @@ jobs:
{"environment":"ubuntu-docker-rootful-cdi","installer":"deb","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootful-cdi","installer":"rpm","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootless-cdi","installer":"rpm","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"ubuntu-docker-rootful-driver-config","installer":"deb","family":"features","package":"driver-config","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"fedora-podman-rootful-driver-config","installer":"rpm","family":"features","package":"driver-config","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"fedora-podman-rootless-driver-config","installer":"rpm","family":"features","package":"driver-config","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"ubuntu-docker-rootful-keycloak","installer":"deb","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"oci-image","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootful","installer":"rpm","family":"features","package":"oci-image","gateway":"openshell","runner":"ubuntu-24.04"},
@@ -99,9 +102,20 @@ jobs:
{"environment":"fedora-podman-rootless","installer":"rpm","family":"features","package":"host-gateway","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"ubuntu-k3s","installer":"k3s","family":"features","package":"host-gateway","gateway":"tmachine","runner":"ubuntu-24.04"},
{"environment":"ubuntu-k3s","installer":"k3s-ha","family":"features","package":"host-gateway","gateway":"tmachine","runner":"ubuntu-24.04"},
+ {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"routable-host-ip","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"fedora-podman-rootful","installer":"rpm","family":"features","package":"routable-host-ip","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"ubuntu-k3s","installer":"k3s","family":"features","package":"routable-host-ip","gateway":"tmachine","runner":"ubuntu-24.04"},
+ {"environment":"ubuntu-k3s","installer":"k3s-ha","family":"features","package":"routable-host-ip","gateway":"tmachine","runner":"ubuntu-24.04"},
{"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"connect-ssh-supervision","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"resource-limits","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"fedora-podman-rootful","installer":"rpm","family":"features","package":"resource-limits","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"fedora-podman-rootless","installer":"rpm","family":"features","package":"resource-limits","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"ocsf","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"fedora-podman-rootful","installer":"rpm","family":"features","package":"ocsf","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"fedora-podman-rootless","installer":"rpm","family":"features","package":"ocsf","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootful-keycloak","installer":"rpm","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootless-keycloak","installer":"rpm","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"ubuntu-docker-rootful","installer":"deb","family":"drivers/docker","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootful-userns-default","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootful-userns-auto","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootful-userns-keep-id","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"},
diff --git a/.github/workflows/rust-cache.yml b/.github/workflows/rust-cache.yml
index dcf7c8027d..a1c6434756 100644
--- a/.github/workflows/rust-cache.yml
+++ b/.github/workflows/rust-cache.yml
@@ -96,7 +96,7 @@ jobs:
run: |
set -euo pipefail
nix build --no-link .#openshell-test-runner || nix build --no-link .#openshell-test-runner
- for family in features drivers/podman; do
+ for family in features drivers/docker drivers/podman; do
nix run .#openshell-test-runner -- build \
--family "$family" --out "$RUNNER_TEMP/e2e-bundles/${family//\//-}"
done
diff --git a/CI.md b/CI.md
index 200a8b6785..813595c671 100644
--- a/CI.md
+++ b/CI.md
@@ -176,11 +176,11 @@ selected. DEB and RPM packages build only when integration qualification is sele
the DEB on Ubuntu with Docker and installs the CLI and gateway RPMs on Fedora with
rootful and rootless Podman. These lanes run conformance using the matching runtime
images. Release Dev, Release, and Pre-release use the same package installers.
-The feature suites (`tests/suites/features`) and the Podman driver suite
-(`tests/suites/drivers/podman`) run the same way, on the package installers; the
-driver suite's environments merge their Podman settings into the packaged
-gateway's configuration (see `TESTING.md`). The `e2e-podman` lane runs on the
-RPM installer as well. The driver suite and `e2e-podman` run
+The feature suites (`tests/suites/features`) and the Docker and Podman driver
+suites (`tests/suites/drivers/{docker,podman}`) run the same way, on the package
+installers; the Podman driver suite's environments merge their Podman settings
+into the packaged gateway's configuration (see `TESTING.md`). The `e2e-podman`
+lane runs on the RPM installer as well. The driver suites and `e2e-podman` run
only in `Branch E2E Checks`. The manual Integration Tests workflow runs the
remaining tmachine testsuites, such as `e2e-podman`, and downloads the packages
selected by its matrix.
diff --git a/TESTING.md b/TESTING.md
index 4e642f338e..0c7f86da4d 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -345,6 +345,11 @@ can run the suite. The expectations characterize the sandbox's behavior today,
not a specification, and the `echo-socket` check needs `perl` in the workload
image, which the default image has.
+The `-driver-config` environments let callers pass driver config with
+volume and bind mounts, and turn off resource admission, which blocks bind
+mounts. The driver-config suite (`tests/suites/features/driver-config`) runs
+there on Docker and Podman.
+
### Python E2E (`e2e/python/`)
`mise run e2e:python` builds `openshell/e2e-python:dev` from
@@ -567,8 +572,7 @@ nix run .#generate-podman-e2e-ci-tests
The `e2e-podman` testsuite runs a nextest archive built with the corresponding
Rust feature and preloads its Python workload image into the rootless Podman
store. The E2E archive excludes binaries that still depend on wrapper-owned
-gateway controls, SPIFFE fixtures, the caller driver-config setting, or other
-guest setup. `tests/tmachine/artifacts.nix` keeps the follow-up exclusions explicit and uses
+gateway controls, SPIFFE fixtures, or other guest setup. `tests/tmachine/artifacts.nix` keeps the follow-up exclusions explicit and uses
the same filter for the generated inventory, so excluded binaries cannot appear
as false passes or silently re-enter the archive.
@@ -576,9 +580,12 @@ Driver suites live in `tests/suites/drivers/`, with the package named
after the driver. Each driver suite is its own workspace with its own lockfile,
so a change to one driver's tests or dependencies doesn't touch another's. Add
a new one to the `rust:format`, `rust:format:check` and `rust:lint` tasks, the
-matching lines in `branch-checks.yml`, and `ALIGNED_WORKSPACES`. The Podman
-driver suite (`tests/suites/drivers/podman`) compares OpenShell and direct
-Podman user-namespace mappings.
+matching lines in `branch-checks.yml`, `ALIGNED_WORKSPACES`, and the bundle
+builds in `branch-e2e.yml` and `rust-cache.yml`. The Docker and Podman driver
+suites (`tests/suites/drivers/{docker,podman}`) check what the driver does with
+a sandbox's containers when its workload stops or an ephemeral sandbox
+finishes. The Podman suite also compares OpenShell and direct Podman
+user-namespace mappings.
Each `fedora-podman-{rootful,rootless}-userns-` environment configures
the gateway with one mode (`default`, `auto`, `keep-id` or `private`) and works
with every installer; CI runs it with `rpm`:
@@ -650,6 +657,14 @@ rootful and rootless, and the `k3s` and `k3s-ha` installers. The tests run on
the K3s node, so the K3s installers set the chart's `server.hostGatewayIP` to
the node's address.
+The `routable-host-ip` feature suite (`tests/suites/features/routable-host-ip`)
+checks that a policy endpoint whose host is an IP literal reaches that address,
+with or without `allowed_ips`. The sandbox uses the address
+`host.openshell.internal` resolves to, which must be one the supervisor lets an
+IP literal reach. Rootless Podman's is link-local and always blocked, so CI runs
+the suite on Docker rootful, Podman rootful, and the `k3s` and `k3s-ha`
+installers.
+
The `connect-ssh-supervision` feature suite
(`tests/suites/features/connect-ssh-supervision`) checks how `sandbox connect`
supervises its `ssh` process: it reconnects after losing the SSH transport and
diff --git a/e2e/rust/Cargo.lock b/e2e/rust/Cargo.lock
index 17eb2b5e0c..b68c749916 100644
--- a/e2e/rust/Cargo.lock
+++ b/e2e/rust/Cargo.lock
@@ -298,49 +298,6 @@ dependencies = [
"hybrid-array",
]
-[[package]]
-name = "bollard"
-version = "0.20.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ee04c4c84f1f811b017f2fbb7dd8815c976e7ca98593de9c1e2afad0f636bff4"
-dependencies = [
- "base64 0.22.1",
- "bollard-stubs",
- "bytes",
- "futures-core",
- "futures-util",
- "hex",
- "http",
- "http-body-util",
- "hyper",
- "hyper-named-pipe",
- "hyper-util",
- "hyperlocal",
- "log",
- "pin-project-lite",
- "serde",
- "serde_derive",
- "serde_json",
- "serde_urlencoded",
- "thiserror",
- "tokio",
- "tokio-util",
- "tower-service",
- "url",
- "winapi",
-]
-
-[[package]]
-name = "bollard-stubs"
-version = "1.52.1-rc.29.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0f0a8ca8799131c1837d1282c3f81f31e76ceb0ce426e04a7fe1ccee3287c066"
-dependencies = [
- "serde",
- "serde_json",
- "serde_repr",
-]
-
[[package]]
name = "borrow-or-share"
version = "0.2.4"
@@ -1224,20 +1181,6 @@ dependencies = [
"tower-service",
]
-[[package]]
-name = "hyper-named-pipe"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fab3637d6b04a8037af8a266fdf6cf92ea957e8c53981a2bf6136572531025bf"
-dependencies = [
- "hex",
- "hyper",
- "hyper-util",
- "pin-project-lite",
- "tokio",
- "tower-service",
-]
-
[[package]]
name = "hyper-rustls"
version = "0.27.9"
@@ -1288,21 +1231,6 @@ dependencies = [
"tracing",
]
-[[package]]
-name = "hyperlocal"
-version = "0.9.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "986c5ce3b994526b3cd75578e62554abd09f0899d6206de48b3e96ab34ccc8c7"
-dependencies = [
- "hex",
- "http-body-util",
- "hyper",
- "hyper-util",
- "pin-project-lite",
- "tokio",
- "tower-service",
-]
-
[[package]]
name = "iana-time-zone"
version = "0.1.65"
@@ -2004,7 +1932,6 @@ name = "openshell-e2e"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
- "bollard",
"bytes",
"flate2",
"futures-util",
@@ -2832,18 +2759,6 @@ dependencies = [
"syn 3.0.3",
]
-[[package]]
-name = "serde_urlencoded"
-version = "0.7.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
-dependencies = [
- "form_urlencoded",
- "itoa",
- "ryu",
- "serde",
-]
-
[[package]]
name = "serde_yaml"
version = "0.9.34+deprecated"
@@ -3845,28 +3760,6 @@ version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c"
-[[package]]
-name = "winapi"
-version = "0.3.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
-dependencies = [
- "winapi-i686-pc-windows-gnu",
- "winapi-x86_64-pc-windows-gnu",
-]
-
-[[package]]
-name = "winapi-i686-pc-windows-gnu"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
-
-[[package]]
-name = "winapi-x86_64-pc-windows-gnu"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
-
[[package]]
name = "windows-core"
version = "0.62.2"
diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml
index 1e0e822236..9c8b5a1d0e 100644
--- a/e2e/rust/Cargo.toml
+++ b/e2e/rust/Cargo.toml
@@ -99,11 +99,6 @@ name = "additional_ca"
path = "tests/additional_ca.rs"
required-features = ["e2e-additional-ca"]
-[[test]]
-name = "driver_config_volume"
-path = "tests/driver_config_volume.rs"
-required-features = ["e2e-local-container-driver"]
-
[[test]]
name = "gateway_start"
path = "tests/gateway_start.rs"
@@ -139,11 +134,6 @@ name = "podman_corporate_proxy"
path = "tests/podman_corporate_proxy.rs"
required-features = ["e2e-podman"]
-[[test]]
-name = "podman_resource_limits"
-path = "tests/podman_resource_limits.rs"
-required-features = ["e2e-podman"]
-
[[test]]
name = "provider_refresh_handles"
path = "tests/provider_refresh_handles.rs"
@@ -189,11 +179,6 @@ name = "credential_drivers"
path = "tests/credential_drivers.rs"
required-features = ["e2e-kubernetes-credential-drivers"]
-[[test]]
-name = "websocket_conformance"
-path = "tests/websocket_conformance.rs"
-required-features = ["e2e-host-gateway"]
-
[[test]]
name = "user_namespaces"
path = "tests/user_namespaces.rs"
@@ -204,21 +189,6 @@ name = "host_gateway_alias"
path = "tests/host_gateway_alias.rs"
required-features = ["e2e-host-gateway"]
-[[test]]
-name = "forward_proxy_l7_bypass"
-path = "tests/forward_proxy_l7_bypass.rs"
-required-features = ["e2e-host-gateway"]
-
-[[test]]
-name = "forward_proxy_graphql_l7"
-path = "tests/forward_proxy_graphql_l7.rs"
-required-features = ["e2e-host-gateway"]
-
-[[test]]
-name = "forward_proxy_jsonrpc_l7"
-path = "tests/forward_proxy_jsonrpc_l7.rs"
-required-features = ["e2e-host-gateway"]
-
[[test]]
name = "workspace_lifecycle"
path = "tests/workspace_lifecycle.rs"
@@ -229,11 +199,6 @@ name = "supervisor_middleware_http_hooks"
path = "tests/supervisor_middleware_http_hooks.rs"
required-features = ["e2e-docker"]
-[[test]]
-name = "proxy_egress_pipeline"
-path = "tests/proxy_egress_pipeline.rs"
-required-features = ["e2e-host-gateway"]
-
[[test]]
name = "workspace_namespace_managed"
path = "tests/workspace_namespace_managed.rs"
@@ -259,7 +224,6 @@ openshell-crypto = { path = "../../crates/openshell-crypto" }
openshell-otel-test-support = { path = "../../crates/openshell-otel-test-support" }
opentelemetry-proto = { version = "0.33", default-features = false, features = ["gen-tonic", "trace"] }
base64 = "0.22"
-bollard = "0.20"
bytes = "1"
futures-util = "0.3"
http-body-util = "0.1"
diff --git a/e2e/rust/e2e-podman.sh b/e2e/rust/e2e-podman.sh
index d5a54741b7..de39ddf2cc 100755
--- a/e2e/rust/e2e-podman.sh
+++ b/e2e/rust/e2e-podman.sh
@@ -22,17 +22,10 @@ source "${ROOT}/e2e/support/conformance.sh"
# unfiltered e2e:podman task remains available while the omitted targets are
# stabilized and can be added here.
PODMAN_CI_TESTS=(
- bypass_detection
ephemeral_cleanup
- driver_config_volume
edge_tunnel_e2e
- forward_proxy_graphql_l7
- forward_proxy_jsonrpc_l7
- forward_proxy_l7_bypass
host_gateway_alias
- live_policy_update
local_driver_token_restart
- no_proxy
ocsf_jsonl_conformance
otlp_relay
podman_corporate_proxy
diff --git a/e2e/rust/src/harness/sandbox.rs b/e2e/rust/src/harness/sandbox.rs
index 9f57a29daa..bf71208f98 100644
--- a/e2e/rust/src/harness/sandbox.rs
+++ b/e2e/rust/src/harness/sandbox.rs
@@ -647,26 +647,6 @@ impl SandboxGuard {
Ok(combined)
}
- /// Spawn `openshell forward start` as a background process.
- ///
- /// Returns the child process handle. The caller is responsible for killing
- /// it (or it will be killed on drop since `kill_on_drop(true)` is set).
- ///
- /// # Errors
- ///
- /// Returns an error if the process cannot be spawned.
- pub fn spawn_forward(&self, port: u16) -> Result {
- let mut cmd = openshell_cmd();
- cmd.arg("forward")
- .arg("start")
- .arg(port.to_string())
- .arg(&self.name);
- cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
-
- cmd.spawn()
- .map_err(|e| format!("failed to spawn port forward: {e}"))
- }
-
/// Delete the sandbox explicitly.
///
/// Also kills the background child process if one exists. This is called
diff --git a/e2e/rust/tests/bypass_detection.rs b/e2e/rust/tests/bypass_detection.rs
deleted file mode 100644
index 569e3a60d6..0000000000
--- a/e2e/rust/tests/bypass_detection.rs
+++ /dev/null
@@ -1,79 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-//! Verify that direct TCP bypass attempts fail promptly at the sandbox
-//! syscall boundary instead of reaching the runtime's external network.
-//!
-//! This test is implementation-agnostic — it validates the observable
-//! behavior rather than a particular packet-filter implementation.
-
-#![cfg(feature = "e2e")]
-
-use openshell_e2e::harness::sandbox::SandboxGuard;
-
-/// Python script that attempts a raw TCP connect bypassing the proxy.
-///
-/// `socket.connect()` does not honor proxy environment variables. The script
-/// reports the outcome and wall-clock time so the test can assert that the
-/// sandbox's seccomp mediation blocks it before the outer fence is needed.
-///
-/// Target 198.51.100.1 is RFC 5737 TEST-NET-2 — documentation-only address
-/// space that will never route.
-fn bypass_attempt_script() -> &'static str {
- r#"
-import json, socket, time
-
-start = time.monotonic()
-result = "unknown"
-try:
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.settimeout(10)
- s.connect(("198.51.100.1", 80))
- result = "connected"
- s.close()
-except ConnectionRefusedError:
- result = "refused"
-except PermissionError:
- result = "denied"
-except socket.timeout:
- result = "timeout"
-except OSError as e:
- result = f"error:{e}"
-
-elapsed_ms = int((time.monotonic() - start) * 1000)
-print(json.dumps({"bypass_result": result, "elapsed_ms": elapsed_ms}), flush=True)
-"#
-}
-
-/// A direct TCP connection bypassing supervision should be denied without
-/// waiting for the socket's network timeout.
-#[tokio::test]
-async fn bypass_attempt_is_rejected_fast() {
- let guard = SandboxGuard::create(&["--", "python3", "-c", bypass_attempt_script()])
- .await
- .expect("sandbox create");
-
- let json_line = guard
- .create_output
- .lines()
- .find(|l| l.contains("bypass_result"))
- .unwrap_or_else(|| panic!("no bypass_result JSON in output:\n{}", guard.create_output));
-
- let parsed: serde_json::Value = serde_json::from_str(json_line.trim())
- .unwrap_or_else(|e| panic!("failed to parse JSON '{json_line}': {e}"));
-
- let result = parsed["bypass_result"].as_str().unwrap();
- let elapsed_ms = parsed["elapsed_ms"].as_u64().unwrap();
-
- assert_eq!(
- result, "denied",
- "expected seccomp mediation to deny the direct connect, got '{result}' after {elapsed_ms}ms.\n\
- Full output:\n{}",
- guard.create_output
- );
-
- assert!(
- elapsed_ms < 8000,
- "bypass rejection took {elapsed_ms}ms — expected < 8000ms."
- );
-}
diff --git a/e2e/rust/tests/driver_config_volume.rs b/e2e/rust/tests/driver_config_volume.rs
deleted file mode 100644
index bcef6a429c..0000000000
--- a/e2e/rust/tests/driver_config_volume.rs
+++ /dev/null
@@ -1,539 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-#![cfg(feature = "e2e-local-container-driver")]
-
-use std::fs;
-use std::io::Write;
-use std::os::unix::fs::PermissionsExt;
-use std::path::{Path, PathBuf};
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::time::{SystemTime, UNIX_EPOCH};
-
-use bollard::Docker;
-use bollard::models::{ContainerCreateBody, HostConfig, Mount, MountTypeEnum, VolumeCreateRequest};
-use bollard::query_parameters::{
- CreateContainerOptionsBuilder, CreateImageOptionsBuilder, LogsOptions, RemoveContainerOptions,
- RemoveVolumeOptionsBuilder, StartContainerOptions, WaitContainerOptions,
-};
-use futures_util::TryStreamExt;
-#[cfg(feature = "e2e-docker")]
-use openshell_e2e::harness::container::ImageGuard;
-use openshell_e2e::harness::container::e2e_driver;
-use openshell_e2e::harness::sandbox::SandboxGuard;
-use serde_json::{Map, Value};
-
-const TEST_IMAGE: &str = "nvcr.io/nvidia/base/ubuntu:24.04";
-const VOLUME_TARGET: &str = "/sandbox/e2e-volume";
-const BIND_TARGET: &str = "/sandbox/e2e-bind";
-#[cfg(feature = "e2e-docker")]
-const OCI_VOLUME_TARGET: &str = "/workspace/project/e2e-volume";
-#[cfg(feature = "e2e-docker")]
-const OCI_USER_DOCKERFILE: &str = r#"FROM public.ecr.aws/docker/library/python:3.13-slim
-
-RUN apt-get update && apt-get install -y --no-install-recommends iproute2 \
- && rm -rf /var/lib/apt/lists/*
-
-WORKDIR /workspace/project
-RUN chown 2234:2235 .
-USER 2234:2235
-CMD ["sleep", "infinity"]
-"#;
-
-static NEXT_VOLUME_ID: AtomicU64 = AtomicU64::new(0);
-
-struct VolumeGuard {
- docker: Docker,
- name: String,
-}
-
-impl VolumeGuard {
- async fn create(driver: &str) -> Result {
- let name = unique_volume_name(driver);
- let docker = connect_container_api(driver).await?;
- docker
- .create_volume(VolumeCreateRequest {
- name: Some(name.clone()),
- ..Default::default()
- })
- .await
- .map_err(|err| format!("create {driver} volume {name}: {err}"))?;
- Ok(Self { docker, name })
- }
-}
-
-impl Drop for VolumeGuard {
- fn drop(&mut self) {
- let docker = self.docker.clone();
- let name = self.name.clone();
- tokio::spawn(async move {
- let _ = docker
- .remove_volume(
- &name,
- Some(RemoveVolumeOptionsBuilder::new().force(true).build()),
- )
- .await;
- });
- }
-}
-
-#[tokio::test]
-async fn sandbox_mounts_existing_driver_config_volume() {
- let driver = e2e_driver().expect("OPENSHELL_E2E_DRIVER must be set by the e2e wrapper");
- assert!(
- matches!(driver.as_str(), "docker" | "podman"),
- "driver_config volume e2e requires docker or podman, got {driver}"
- );
-
- let volume = VolumeGuard::create(&driver)
- .await
- .expect("create named test volume");
-
- seed_volume(&volume).await.expect("seed named test volume");
-
- let driver_config = format!(
- r#"{{"{driver}":{{"mounts":[{{"type":"volume","source":"{}","target":"{VOLUME_TARGET}","read_only":false}}]}}}}"#,
- volume.name
- );
- let mut sandbox = SandboxGuard::create(&[
- "--driver-config-json",
- &driver_config,
- "--",
- "sh",
- "-lc",
- "set -eu; test \"$(cat /sandbox/e2e-volume/input.txt)\" = host-volume-ok; printf sandbox-volume-ok > /sandbox/e2e-volume/output.txt; cat /sandbox/e2e-volume/output.txt",
- ])
- .await
- .expect("sandbox create with driver-config volume");
-
- assert!(
- sandbox.create_output.contains("sandbox-volume-ok"),
- "sandbox should read and write the mounted volume:\n{}",
- sandbox.create_output
- );
-
- sandbox.cleanup().await;
- verify_volume(&volume)
- .await
- .expect("verify sandbox wrote to named test volume");
-}
-
-#[tokio::test]
-#[cfg(feature = "e2e-docker")]
-async fn oci_workspace_preparation_skips_nested_volume_ownership() {
- let driver = e2e_driver().expect("OPENSHELL_E2E_DRIVER must be set by the e2e wrapper");
- assert!(
- driver == "docker",
- "OCI workspace mount e2e requires docker, got {driver}"
- );
-
- let volume = VolumeGuard::create(&driver)
- .await
- .expect("create named test volume");
- seed_volume(&volume).await.expect("seed named test volume");
-
- let image_context = tempfile::tempdir().expect("create OCI image context");
- let dockerfile = image_context.path().join("Dockerfile");
- fs::write(&dockerfile, OCI_USER_DOCKERFILE).expect("write OCI image Dockerfile");
- let image = ImageGuard::build(
- &format!("{driver}-oci-user"),
- &dockerfile,
- image_context.path(),
- )
- .expect("build OCI-user image with selected container engine");
-
- let driver_config = format!(
- r#"{{"{driver}":{{"mounts":[{{"type":"volume","source":"{}","target":"{OCI_VOLUME_TARGET}","read_only":false}}]}}}}"#,
- volume.name
- );
- let mut sandbox = SandboxGuard::create_keep_with_args(
- &[
- "--from",
- image.tag(),
- "--driver-config-json",
- &driver_config,
- "--no-tty",
- ],
- &[
- "sh",
- "-lc",
- "set -eu; test \"$(id -u):$(id -g)\" = 2234:2235; \
- test \"$(pwd -P)\" = /workspace/project; test \"$HOME\" = /workspace/project; \
- test \"$(stat -c %u:%g /workspace/project/e2e-volume/input.txt)\" = 0:0; \
- touch direct-write; echo Ready; sleep infinity",
- ],
- "Ready",
- )
- .await
- .expect("create OCI-user sandbox with nested volume");
-
- let ssh_output = sandbox
- .exec(&[
- "sh",
- "-lc",
- "set -eu; test \"$(pwd -P)\" = /workspace/project; \
- test \"$HOME\" = /workspace/project; \
- test \"$(stat -c %u:%g /workspace/project/e2e-volume/input.txt)\" = 0:0; \
- touch ssh-write; echo nested-mount-owner-ok",
- ])
- .await
- .expect("SSH child should preserve nested volume ownership");
- assert!(
- ssh_output.contains("nested-mount-owner-ok"),
- "expected nested mount ownership marker:\n{ssh_output}"
- );
-
- sandbox.cleanup().await;
- verify_volume_ownership(&volume)
- .await
- .expect("nested volume ownership should remain unchanged");
-}
-
-#[tokio::test]
-async fn sandbox_mounts_enabled_driver_config_bind() {
- let driver = e2e_driver().expect("OPENSHELL_E2E_DRIVER must be set by the e2e wrapper");
- assert!(
- matches!(driver.as_str(), "docker" | "podman"),
- "driver_config bind e2e requires docker or podman, got {driver}"
- );
-
- let cwd = std::env::current_dir().expect("resolve current dir");
- let host_dir = tempfile::Builder::new()
- .prefix("openshell-e2e-driver-config-bind-")
- .tempdir_in(cwd)
- .expect("create bind mount host dir");
- fs::set_permissions(host_dir.path(), fs::Permissions::from_mode(0o777))
- .expect("make bind mount host dir writable by sandbox user");
- let input_path = host_dir.path().join("input.txt");
- fs::write(&input_path, "host-bind-ok").expect("seed bind mount host dir");
- fs::set_permissions(&input_path, fs::Permissions::from_mode(0o666))
- .expect("make bind mount input readable by sandbox user");
-
- let bind_source = bind_mount_source_path(&driver, host_dir.path());
- let bind_mount = serde_json::json!({
- "type": "bind",
- "source": bind_source,
- "target": BIND_TARGET,
- "read_only": false,
- "selinux_label": "private"
- });
- let driver_config = driver_config_mount_json(&driver, &bind_mount);
- // Host bind mounts are explicitly unsafe: this test validates driver mount
- // wiring, not Landlock enforcement over Docker Desktop's fakeowner mounts.
- let policy = write_bind_mount_policy().expect("write bind mount policy");
- let policy_path = policy.path().to_str().expect("policy path must be utf-8");
- let mut sandbox = SandboxGuard::create(&[
- "--policy",
- policy_path,
- "--driver-config-json",
- &driver_config,
- "--",
- "sh",
- "-lc",
- "set -eu; test \"$(cat /sandbox/e2e-bind/input.txt)\" = host-bind-ok; printf sandbox-bind-ok > /sandbox/e2e-bind/output.txt; cat /sandbox/e2e-bind/output.txt",
- ])
- .await
- .expect("sandbox create with driver-config bind mount");
-
- assert!(
- sandbox.create_output.contains("sandbox-bind-ok"),
- "sandbox should read and write the bind mount:\n{}",
- sandbox.create_output
- );
-
- sandbox.cleanup().await;
- let output = fs::read_to_string(host_dir.path().join("output.txt"))
- .expect("read sandbox output from bind mount host dir");
- assert_eq!(output, "sandbox-bind-ok");
-}
-
-fn write_bind_mount_policy() -> Result {
- let mut file =
- tempfile::NamedTempFile::new().map_err(|err| format!("create bind policy: {err}"))?;
- file.write_all(
- br#"version: 1
-
-filesystem_policy:
- include_workdir: false
- read_only:
- - "/bin"
- - "/dev"
- - "/etc"
- - "/lib"
- - "/proc"
- - "/usr"
- read_write:
- - "/sandbox/e2e-bind"
- - "/tmp"
-
-landlock:
- compatibility: best_effort
-
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-"#,
- )
- .map_err(|err| format!("write bind policy: {err}"))?;
- Ok(file)
-}
-
-async fn seed_volume(volume: &VolumeGuard) -> Result<(), String> {
- run_volume_container(
- volume,
- "seed",
- false,
- "set -eu; chmod 0777 /vol; printf host-volume-ok > /vol/input.txt",
- )
- .await?;
- Ok(())
-}
-
-async fn verify_volume(volume: &VolumeGuard) -> Result<(), String> {
- let output = run_volume_container(
- volume,
- "verify",
- true,
- "set -eu; test \"$(cat /vol/input.txt)\" = host-volume-ok; test \"$(cat /vol/output.txt)\" = sandbox-volume-ok; echo volume-ok",
- )
- .await?;
- if !output.contains("volume-ok") {
- return Err(format!(
- "volume verification did not print expected marker:\n{output}"
- ));
- }
- Ok(())
-}
-
-#[cfg(feature = "e2e-docker")]
-async fn verify_volume_ownership(volume: &VolumeGuard) -> Result<(), String> {
- let output = run_volume_container(
- volume,
- "verify-owner",
- true,
- "set -eu; test \"$(stat -c %u:%g /vol/input.txt)\" = 0:0; echo owner-ok",
- )
- .await?;
- if !output.contains("owner-ok") {
- return Err(format!(
- "volume ownership verification did not print expected marker:\n{output}"
- ));
- }
- Ok(())
-}
-
-async fn run_volume_container(
- volume: &VolumeGuard,
- purpose: &str,
- read_only: bool,
- script: &str,
-) -> Result {
- ensure_test_image(&volume.docker).await?;
-
- let container_name = format!("{}-{purpose}", volume.name);
- let create_options = CreateContainerOptionsBuilder::new()
- .name(&container_name)
- .build();
- let host_config = HostConfig {
- mounts: Some(vec![Mount {
- target: Some("/vol".to_string()),
- source: Some(volume.name.clone()),
- typ: Some(MountTypeEnum::VOLUME),
- read_only: Some(read_only),
- ..Default::default()
- }]),
- ..Default::default()
- };
- volume
- .docker
- .create_container(
- Some(create_options),
- ContainerCreateBody {
- image: Some(TEST_IMAGE.to_string()),
- user: Some("0:0".to_string()),
- entrypoint: Some(vec!["sh".to_string()]),
- cmd: Some(vec!["-lc".to_string(), script.to_string()]),
- attach_stdout: Some(true),
- attach_stderr: Some(true),
- host_config: Some(host_config),
- ..Default::default()
- },
- )
- .await
- .map_err(|err| format!("create helper container {container_name}: {err}"))?;
-
- let result = run_created_container(volume, &container_name).await;
- let remove_result = volume
- .docker
- .remove_container(&container_name, None::)
- .await;
-
- match (result, remove_result) {
- (Ok(output), Ok(())) => Ok(output),
- (Ok(_), Err(err)) => Err(format!("remove helper container {container_name}: {err}")),
- (Err(err), Ok(())) => Err(err),
- (Err(err), Err(remove_err)) => Err(format!(
- "{err}\nremove helper container {container_name}: {remove_err}"
- )),
- }
-}
-
-async fn ensure_test_image(docker: &Docker) -> Result<(), String> {
- if docker.inspect_image(TEST_IMAGE).await.is_ok() {
- return Ok(());
- }
-
- let pull_events = docker
- .create_image(
- Some(
- CreateImageOptionsBuilder::new()
- .from_image(TEST_IMAGE)
- .build(),
- ),
- None,
- None,
- )
- .try_collect::>()
- .await
- .map_err(|err| format!("pull helper image {TEST_IMAGE}: {err}"))?;
-
- let pull_errors = pull_events
- .iter()
- .filter_map(|event| {
- event
- .error_detail
- .as_ref()
- .and_then(|detail| detail.message.as_deref())
- })
- .collect::>();
- if pull_errors.is_empty() {
- return Ok(());
- }
-
- Err(format!(
- "pull helper image {TEST_IMAGE} failed:\n{}",
- pull_errors.join("\n")
- ))
-}
-
-async fn run_created_container(
- volume: &VolumeGuard,
- container_name: &str,
-) -> Result {
- volume
- .docker
- .start_container(container_name, None::)
- .await
- .map_err(|err| format!("start helper container {container_name}: {err}"))?;
-
- let wait_result = volume
- .docker
- .wait_container(container_name, None::)
- .try_collect::>()
- .await;
- let logs = volume
- .docker
- .logs(
- container_name,
- Some(LogsOptions {
- stdout: true,
- stderr: true,
- tail: "all".to_string(),
- ..Default::default()
- }),
- )
- .try_collect::>()
- .await
- .map(|chunks| {
- chunks
- .into_iter()
- .map(|chunk| chunk.to_string())
- .collect::()
- });
-
- match (wait_result, logs) {
- (Ok(_), Ok(output)) => Ok(output),
- (Ok(_), Err(err)) => Err(format!(
- "read helper container {container_name} logs: {err}"
- )),
- (Err(err), Ok(output)) => Err(format!(
- "helper container {container_name} failed: {err}\n{output}"
- )),
- (Err(err), Err(log_err)) => Err(format!(
- "helper container {container_name} failed: {err}\nread logs failed: {log_err}"
- )),
- }
-}
-
-async fn connect_container_api(driver: &str) -> Result {
- let docker = match driver {
- "docker" => Docker::connect_with_local_defaults()
- .map_err(|err| format!("connect to Docker API: {err}"))?,
- "podman" => {
- let socket = podman_socket_path()?;
- let socket_display = socket.display().to_string();
- Docker::connect_with_unix(
- socket
- .to_str()
- .ok_or_else(|| format!("podman socket path is not UTF-8: {socket_display}"))?,
- 120,
- bollard::API_DEFAULT_VERSION,
- )
- .map_err(|err| format!("connect to Podman Docker-compatible API: {err}"))?
- }
- other => return Err(format!("unsupported e2e driver for volume API: {other}")),
- };
- docker
- .ping()
- .await
- .map_err(|err| format!("ping {driver} Docker-compatible API: {err}"))?;
- Ok(docker)
-}
-
-fn podman_socket_path() -> Result {
- let path = std::env::var_os("OPENSHELL_PODMAN_SOCKET").ok_or_else(|| {
- "OPENSHELL_PODMAN_SOCKET must be set by e2e/with-podman-gateway.sh".to_string()
- })?;
- Ok(PathBuf::from(path))
-}
-
-fn unique_volume_name(driver: &str) -> String {
- let nanos = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .expect("system clock should be after Unix epoch")
- .as_nanos();
- let sequence = NEXT_VOLUME_ID.fetch_add(1, Ordering::Relaxed);
- format!(
- "openshell-e2e-driver-config-volume-{driver}-{}-{nanos}-{sequence}",
- std::process::id()
- )
-}
-
-fn driver_config_mount_json(driver: &str, mount: &Value) -> String {
- let mut root = Map::new();
- root.insert(
- driver.to_string(),
- serde_json::json!({
- "mounts": [mount]
- }),
- );
- Value::Object(root).to_string()
-}
-
-fn bind_mount_source_path(driver: &str, path: &Path) -> PathBuf {
- if driver == "docker" {
- github_actions_host_work_path(path).unwrap_or_else(|| path.to_path_buf())
- } else {
- path.to_path_buf()
- }
-}
-
-fn github_actions_host_work_path(path: &Path) -> Option {
- if std::env::var("GITHUB_ACTIONS").ok().as_deref() != Some("true") {
- return None;
- }
-
- let relative = path.strip_prefix("/__w").ok()?;
- let mapped = Path::new("/home/runner/_work").join(relative);
- mapped.exists().then_some(mapped)
-}
diff --git a/e2e/rust/tests/forward_proxy_graphql_l7.rs b/e2e/rust/tests/forward_proxy_graphql_l7.rs
deleted file mode 100644
index 5c25556cfa..0000000000
--- a/e2e/rust/tests/forward_proxy_graphql_l7.rs
+++ /dev/null
@@ -1,415 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-//! E2E tests for GraphQL L7 inspection through transparent interception.
-//!
-//! The upstream server deliberately does not implement GraphQL. `OpenShell`
-//! parses and enforces GraphQL before forwarding, so any HTTP server that
-//! accepts POST /graphql is enough to prove allowed requests reach upstream
-//! and denied requests are stopped by the sandbox proxy.
-
-#![cfg(feature = "e2e")]
-
-use std::io::Write;
-
-use openshell_e2e::harness::container::ContainerHttpServer;
-use openshell_e2e::harness::sandbox::SandboxGuard;
-use tempfile::NamedTempFile;
-
-const TEST_SERVER_ALIAS: &str = "graphql-l7.openshell.test";
-
-async fn start_test_server() -> Result {
- let script = r#"from http.server import BaseHTTPRequestHandler, HTTPServer
-
-class Handler(BaseHTTPRequestHandler):
- def read_chunked(self):
- while True:
- size_line = self.rfile.readline()
- if not size_line:
- return
- size = int(size_line.split(b";", 1)[0].strip(), 16)
- if size == 0:
- while self.rfile.readline().strip():
- pass
- return
- self.rfile.read(size)
- self.rfile.read(2)
- def do_GET(self):
- if self.path == "/" or self.path.startswith("/graphql?"):
- self.send_response(200)
- else:
- self.send_response(418)
- self.end_headers()
- self.wfile.write(b'{"ok":true}')
- def do_POST(self):
- if self.headers.get("Transfer-Encoding", "").lower() == "chunked":
- self.read_chunked()
- else:
- _ = self.rfile.read(int(self.headers.get("Content-Length", "0")))
- self.send_response(200)
- self.send_header("Content-Type", "application/json")
- self.end_headers()
- self.wfile.write(b'{"ok":true}')
- def log_message(self, format, *args):
- pass
-
-HTTPServer(("0.0.0.0", 8000), Handler).serve_forever()
-"#;
-
- ContainerHttpServer::start_python(TEST_SERVER_ALIAS, script).await
-}
-
-fn write_graphql_policy(host: &str, port: u16) -> Result {
- let mut file = NamedTempFile::new().map_err(|e| format!("create temp policy file: {e}"))?;
- let policy = format!(
- r#"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only:
- - /usr
- - /lib
- - /proc
- - /dev/urandom
- - /app
- - /etc
- - /var/log
- read_write:
- - /sandbox
- - /tmp
- - /dev/null
-
-landlock:
- compatibility: best_effort
-
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-
-network_policies:
- test_graphql_l7:
- name: test_graphql_l7
- endpoints:
- - host: {host}
- port: {port}
- protocol: graphql
- enforcement: enforce
- persisted_queries: allow_registered
- graphql_persisted_queries:
- abc123:
- operation_type: query
- operation_name: Viewer
- fields: [viewer]
- allowed_ips:
- - "10.0.0.0/8"
- - "172.0.0.0/8"
- - "192.168.0.0/16"
- - "fc00::/7"
- rules:
- - allow:
- operation_type: query
- fields: [viewer]
- - allow:
- operation_type: mutation
- fields: [createIssue]
- deny_rules:
- - operation_type: mutation
- fields: [deleteRepository]
- binaries:
- - path: /usr/bin/python*
- - path: /usr/local/bin/python*
- - path: /sandbox/.uv/python/*/bin/python*
-"#
- );
- file.write_all(policy.as_bytes())
- .map_err(|e| format!("write temp policy file: {e}"))?;
- file.flush()
- .map_err(|e| format!("flush temp policy file: {e}"))?;
- Ok(file)
-}
-
-#[tokio::test]
-#[allow(clippy::too_many_lines)]
-async fn graphql_l7_enforces_high_level_and_raw_transparent_paths() {
- let server = start_test_server().await.expect("start test server");
- let policy = write_graphql_policy(&server.host, server.port).expect("write custom policy");
- let policy_path = policy
- .path()
- .to_str()
- .expect("temp policy path should be utf-8")
- .to_string();
-
- let script = format!(
- r#"
-import json
-import socket
-import time
-import urllib.error
-import urllib.parse
-import urllib.request
-
-HOST = {host:?}
-PORT = {port}
-DETAILS = {{}}
-
-QUERY_VIEWER = "query Viewer {{ viewer {{ login }} }}"
-QUERY_REPOSITORY = "query Repo {{ repository(owner:\"o\", name:\"r\") {{ id }} }}"
-MUTATION_CREATE = "mutation Create {{ createIssue(input:{{repositoryId:\"r\", title:\"t\", body:\"b\"}}) {{ issue {{ id }} }} }}"
-MUTATION_DELETE = "mutation Delete {{ deleteRepository(input:{{repositoryId:\"r\"}}) {{ clientMutationId }} }}"
-
-def forward_status(query):
- body = json.dumps({{"query": query}}).encode()
- request = urllib.request.Request(
- f"http://{{HOST}}:{{PORT}}/graphql",
- data=body,
- headers={{"Content-Type": "application/json"}},
- method="POST",
- )
- try:
- with urllib.request.urlopen(request, timeout=15) as response:
- response.read()
- return response.status
- except urllib.error.HTTPError as error:
- error.read()
- return error.code
-
-def forward_get_status(query):
- encoded = urllib.parse.urlencode({{"query": query}})
- request = urllib.request.Request(
- f"http://{{HOST}}:{{PORT}}/graphql?{{encoded}}",
- method="GET",
- )
- try:
- with urllib.request.urlopen(request, timeout=15) as response:
- response.read()
- return response.status
- except urllib.error.HTTPError as error:
- error.read()
- return error.code
-
-def forward_duplicate_get_status():
- safe = urllib.parse.quote_plus(QUERY_VIEWER)
- unsafe = urllib.parse.quote_plus(MUTATION_DELETE)
- request = urllib.request.Request(
- f"http://{{HOST}}:{{PORT}}/graphql?query={{safe}}&query={{unsafe}}",
- method="GET",
- )
- try:
- with urllib.request.urlopen(request, timeout=15) as response:
- response.read()
- return response.status
- except urllib.error.HTTPError as error:
- error.read()
- return error.code
-
-def forward_persisted_get_status(hash_value):
- extensions = json.dumps({{"persistedQuery": {{"version": 1, "sha256Hash": hash_value}}}})
- encoded = urllib.parse.urlencode({{"operationName": "Viewer", "extensions": extensions}})
- request = urllib.request.Request(
- f"http://{{HOST}}:{{PORT}}/graphql?{{encoded}}",
- method="GET",
- )
- try:
- with urllib.request.urlopen(request, timeout=15) as response:
- response.read()
- return response.status
- except urllib.error.HTTPError as error:
- error.read()
- return error.code
-
-def forward_chunked_status(query):
- target = f"{{HOST}}:{{PORT}}"
- body = json.dumps({{"query": query}}).encode()
- chunk = f"{{len(body):x}}\r\n".encode() + body + b"\r\n0\r\n\r\n"
-
- with socket.create_connection((HOST, PORT), timeout=15) as sock:
- request = (
- f"POST /graphql HTTP/1.1\r\n"
- f"Host: {{target}}\r\n"
- f"Content-Type: application/json\r\n"
- f"Transfer-Encoding: chunked\r\n"
- f"Connection: close\r\n"
- f"\r\n"
- ).encode() + chunk
- sock.sendall(request)
- response, body = read_response(sock)
- DETAILS["forward_chunked_query_allowed_detail"] = body.decode(errors="replace")
- return status_code(response, "forward_chunked_response")
-
-def read_until(sock, marker):
- data = b""
- while marker not in data:
- chunk = sock.recv(4096)
- if not chunk:
- break
- data += chunk
- return data
-
-def read_response(sock):
- response = read_until(sock, b"\r\n\r\n")
- headers, _, body = response.partition(b"\r\n\r\n")
- content_length = 0
- for line in headers.split(b"\r\n")[1:]:
- if line.lower().startswith(b"content-length:"):
- content_length = int(line.split(b":", 1)[1].strip())
- break
- while len(body) < content_length:
- chunk = sock.recv(4096)
- if not chunk:
- break
- body += chunk
- return response, body
-
-def status_code(response, label):
- parts = response.split()
- if len(parts) < 2:
- DETAILS[f"{{label}}_raw"] = response.decode(errors="replace")
- raise RuntimeError(f"{{label}}: malformed HTTP response: {{response!r}}")
- try:
- return int(parts[1])
- except ValueError as error:
- DETAILS[f"{{label}}_raw"] = response.decode(errors="replace")
- raise RuntimeError(f"{{label}}: non-numeric HTTP status: {{response!r}}") from error
-
-def raw_http_status(label, request):
- last_error = None
- for attempt in range(5):
- try:
- with socket.create_connection((HOST, PORT), timeout=15) as sock:
- sock.sendall(request)
- sock.shutdown(socket.SHUT_WR)
- response = read_until(sock, b"\r\n\r\n")
- return status_code(response, f"{{label}}_response")
- except (OSError, RuntimeError) as error:
- last_error = error
- DETAILS[f"{{label}}_attempt_{{attempt + 1}}_error"] = str(error)
- time.sleep(0.2)
-
- raise RuntimeError(f"{{label}}: failed after 5 attempts: {{last_error}}")
-
-def raw_status(query, label):
- target = f"{{HOST}}:{{PORT}}"
- body = json.dumps({{"query": query}}).encode()
-
- request = (
- f"POST /graphql HTTP/1.1\r\n"
- f"Host: {{target}}\r\n"
- f"Content-Type: application/json\r\n"
- f"Content-Length: {{len(body)}}\r\n"
- f"Connection: close\r\n"
- f"\r\n"
- ).encode() + body
- return raw_http_status(label, request)
-
-def raw_get_status(query, label):
- target = f"{{HOST}}:{{PORT}}"
- encoded = urllib.parse.urlencode({{"query": query}})
-
- request = (
- f"GET /graphql?{{encoded}} HTTP/1.1\r\n"
- f"Host: {{target}}\r\n"
- f"Connection: close\r\n"
- f"\r\n"
- ).encode()
- return raw_http_status(label, request)
-
-def raw_duplicate_get_status():
- target = f"{{HOST}}:{{PORT}}"
- safe = urllib.parse.quote_plus(QUERY_VIEWER)
- unsafe = urllib.parse.quote_plus(MUTATION_DELETE)
-
- request = (
- f"GET /graphql?query={{safe}}&query={{unsafe}} HTTP/1.1\r\n"
- f"Host: {{target}}\r\n"
- f"Connection: close\r\n"
- f"\r\n"
- ).encode()
- return raw_http_status("raw_duplicate_get_denied", request)
-
-def raw_persisted_get_status(hash_value, label):
- target = f"{{HOST}}:{{PORT}}"
- extensions = json.dumps({{"persistedQuery": {{"version": 1, "sha256Hash": hash_value}}}})
- encoded = urllib.parse.urlencode({{"operationName": "Viewer", "extensions": extensions}})
-
- request = (
- f"GET /graphql?{{encoded}} HTTP/1.1\r\n"
- f"Host: {{target}}\r\n"
- f"Connection: close\r\n"
- f"\r\n"
- ).encode()
- return raw_http_status(label, request)
-
-def raw_chunked_status(query):
- target = f"{{HOST}}:{{PORT}}"
- body = json.dumps({{"query": query}}).encode()
- chunk = f"{{len(body):x}}\r\n".encode() + body + b"\r\n0\r\n\r\n"
-
- request = (
- f"POST /graphql HTTP/1.1\r\n"
- f"Host: {{target}}\r\n"
- f"Content-Type: application/json\r\n"
- f"Transfer-Encoding: chunked\r\n"
- f"Connection: close\r\n"
- f"\r\n"
- ).encode() + chunk
- return raw_http_status("raw_chunked_query_allowed", request)
-
-results = {{
- "forward_query_allowed": forward_status(QUERY_VIEWER),
- "forward_get_query_allowed": forward_get_status(QUERY_VIEWER),
- "forward_duplicate_get_denied": forward_duplicate_get_status(),
- "forward_persisted_get_allowed": forward_persisted_get_status("abc123"),
- "forward_unregistered_persisted_get_denied": forward_persisted_get_status("missing"),
- "forward_chunked_query_allowed": forward_chunked_status(QUERY_VIEWER),
- "forward_unlisted_field_denied": forward_status(QUERY_REPOSITORY),
- "forward_mutation_allowed": forward_status(MUTATION_CREATE),
- "forward_deny_rule_denied": forward_status(MUTATION_DELETE),
- "raw_query_allowed": raw_status(QUERY_VIEWER, "raw_query_allowed"),
- "raw_get_query_allowed": raw_get_status(QUERY_VIEWER, "raw_get_query_allowed"),
- "raw_duplicate_get_denied": raw_duplicate_get_status(),
- "raw_persisted_get_allowed": raw_persisted_get_status("abc123", "raw_persisted_get_allowed"),
- "raw_unregistered_persisted_get_denied": raw_persisted_get_status("missing", "raw_unregistered_persisted_get_denied"),
- "raw_chunked_query_allowed": raw_chunked_status(QUERY_VIEWER),
- "raw_unlisted_field_denied": raw_status(QUERY_REPOSITORY, "raw_unlisted_field_denied"),
- "raw_mutation_allowed": raw_status(MUTATION_CREATE, "raw_mutation_allowed"),
- "raw_deny_rule_denied": raw_status(MUTATION_DELETE, "raw_deny_rule_denied"),
-}}
-results.update(DETAILS)
-print(json.dumps(results, sort_keys=True))
-"#,
- host = server.host,
- port = server.port,
- );
-
- let guard = SandboxGuard::create(&["--policy", &policy_path, "--", "python3", "-c", &script])
- .await
- .expect("sandbox create");
-
- for (key, expected) in [
- ("forward_query_allowed", 200),
- ("forward_get_query_allowed", 200),
- ("forward_duplicate_get_denied", 403),
- ("forward_persisted_get_allowed", 200),
- ("forward_unregistered_persisted_get_denied", 403),
- ("forward_chunked_query_allowed", 200),
- ("forward_unlisted_field_denied", 403),
- ("forward_mutation_allowed", 200),
- ("forward_deny_rule_denied", 403),
- ("raw_query_allowed", 200),
- ("raw_get_query_allowed", 200),
- ("raw_duplicate_get_denied", 403),
- ("raw_persisted_get_allowed", 200),
- ("raw_unregistered_persisted_get_denied", 403),
- ("raw_chunked_query_allowed", 200),
- ("raw_unlisted_field_denied", 403),
- ("raw_mutation_allowed", 200),
- ("raw_deny_rule_denied", 403),
- ] {
- let expected_fragment = format!(r#""{key}": {expected}"#);
- assert!(
- guard.create_output.contains(&expected_fragment),
- "expected {key}={expected}, got:\n{}",
- guard.create_output
- );
- }
-}
diff --git a/e2e/rust/tests/forward_proxy_jsonrpc_l7.rs b/e2e/rust/tests/forward_proxy_jsonrpc_l7.rs
deleted file mode 100644
index b46dac1313..0000000000
--- a/e2e/rust/tests/forward_proxy_jsonrpc_l7.rs
+++ /dev/null
@@ -1,498 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-//! E2E tests for JSON-RPC L7 inspection through transparent interception.
-//!
-//! The upstream server deliberately does not implement JSON-RPC. `OpenShell`
-//! parses and enforces JSON-RPC before forwarding, so any HTTP server that
-//! accepts POST /rpc is enough to prove allowed requests reach upstream
-//! and denied requests are stopped by the sandbox proxy.
-
-#![cfg(feature = "e2e")]
-
-use std::io::Write;
-
-use openshell_e2e::harness::container::ContainerHttpServer;
-use openshell_e2e::harness::sandbox::SandboxGuard;
-use tempfile::NamedTempFile;
-
-const RULES_TEST_SERVER_ALIAS: &str = "jsonrpc-l7-rules.openshell.test";
-const AUDIT_TEST_SERVER_ALIAS: &str = "jsonrpc-l7-audit.openshell.test";
-
-async fn start_test_server(alias: &str) -> Result {
- let script = r#"from http.server import BaseHTTPRequestHandler, HTTPServer
-
-class Handler(BaseHTTPRequestHandler):
- def read_body(self):
- if self.headers.get("Transfer-Encoding", "").lower() == "chunked":
- data = b""
- while True:
- size_line = self.rfile.readline()
- if not size_line:
- break
- size = int(size_line.split(b";", 1)[0].strip(), 16)
- if size == 0:
- while self.rfile.readline().strip():
- pass
- break
- data += self.rfile.read(size)
- self.rfile.read(2)
- return data
- return self.rfile.read(int(self.headers.get("Content-Length", "0")))
-
- def do_GET(self):
- self.send_response(200)
- self.end_headers()
-
- def do_POST(self):
- self.read_body()
- self.send_response(200)
- self.send_header("Content-Type", "application/json")
- self.end_headers()
- self.wfile.write(b'{"jsonrpc":"2.0","id":1,"result":{}}')
-
- def log_message(self, format, *args):
- pass
-
-HTTPServer(("0.0.0.0", 8000), Handler).serve_forever()
-"#;
-
- ContainerHttpServer::start_python(alias, script).await
-}
-
-fn write_jsonrpc_policy(host: &str, port: u16) -> Result {
- let mut file = NamedTempFile::new().map_err(|e| format!("create temp policy file: {e}"))?;
- let policy = format!(
- r#"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only:
- - /usr
- - /lib
- - /proc
- - /dev/urandom
- - /app
- - /etc
- - /var/log
- read_write:
- - /sandbox
- - /tmp
- - /dev/null
-
-landlock:
- compatibility: best_effort
-
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-
-network_policies:
- test_jsonrpc_l7:
- name: test_jsonrpc_l7
- endpoints:
- - host: {host}
- port: {port}
- path: /rpc
- protocol: json-rpc
- enforcement: enforce
- allowed_ips:
- - "10.0.0.0/8"
- - "172.0.0.0/8"
- - "192.168.0.0/16"
- - "fc00::/7"
- json_rpc:
- max_body_bytes: 65536
- rules:
- - allow:
- method: initialize
- - allow:
- method: tools/list
- - allow:
- method: tools/call
- deny_rules:
- - method: tools/delete
- binaries:
- - path: /usr/bin/python*
- - path: /usr/local/bin/python*
- - path: /sandbox/.uv/python/*/bin/python*
-"#
- );
- file.write_all(policy.as_bytes())
- .map_err(|e| format!("write temp policy file: {e}"))?;
- file.flush()
- .map_err(|e| format!("flush temp policy file: {e}"))?;
- Ok(file)
-}
-
-fn write_jsonrpc_default_audit_policy(host: &str, port: u16) -> Result {
- let mut file = NamedTempFile::new().map_err(|e| format!("create temp policy file: {e}"))?;
- let policy = format!(
- r#"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only:
- - /usr
- - /lib
- - /proc
- - /dev/urandom
- - /app
- - /etc
- - /var/log
- read_write:
- - /sandbox
- - /tmp
- - /dev/null
-
-landlock:
- compatibility: best_effort
-
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-
-network_policies:
- test_jsonrpc_l7_audit:
- name: test_jsonrpc_l7_audit
- endpoints:
- - host: {host}
- port: {port}
- path: /rpc
- protocol: json-rpc
- allowed_ips:
- - "10.0.0.0/8"
- - "100.64.0.0/10"
- - "172.0.0.0/8"
- - "198.18.0.0/15"
- - "192.168.0.0/16"
- - "fc00::/7"
- json_rpc:
- max_body_bytes: 65536
- rules:
- - allow:
- method: initialize
- binaries:
- - path: /usr/bin/python*
- - path: /usr/local/bin/python*
- - path: /sandbox/.uv/python/*/bin/python*
-"#
- );
- file.write_all(policy.as_bytes())
- .map_err(|e| format!("write temp policy file: {e}"))?;
- file.flush()
- .map_err(|e| format!("flush temp policy file: {e}"))?;
- Ok(file)
-}
-
-#[tokio::test]
-#[allow(clippy::too_many_lines)]
-async fn jsonrpc_l7_enforces_high_level_and_raw_transparent_paths() {
- let server = start_test_server(RULES_TEST_SERVER_ALIAS)
- .await
- .expect("start test server");
- let policy = write_jsonrpc_policy(&server.host, server.port).expect("write custom policy");
- let policy_path = policy
- .path()
- .to_str()
- .expect("temp policy path should be utf-8")
- .to_string();
-
- let script = format!(
- r#"
-import json
-import socket
-import time
-import urllib.error
-import urllib.request
-
-HOST = {host:?}
-PORT = {port}
-DETAILS = {{
- "debug_target": {{"host": HOST, "port": PORT}},
-}}
-
-def text(data):
- return data.decode(errors="replace")
-
-def selected_headers(headers):
- return {{
- key.lower(): value
- for key, value in headers.items()
- if key.lower() in ("content-type", "content-length", "server")
- }}
-
-def record_http_error(label, error, request_body):
- response_body = error.read()
- DETAILS[f"{{label}}_request"] = request_body
- DETAILS[f"{{label}}_response"] = {{
- "status": error.code,
- "reason": str(error.reason),
- "headers": selected_headers(error.headers),
- "body": text(response_body),
- }}
- return error.code
-
-def post_jsonrpc(label, method, params=None, req_id=1):
- body = {{"jsonrpc": "2.0", "id": req_id, "method": method}}
- if params is not None:
- body["params"] = params
- encoded = json.dumps(body).encode()
- request = urllib.request.Request(
- f"http://{{HOST}}:{{PORT}}/rpc",
- data=encoded,
- headers={{"Content-Type": "application/json"}},
- method="POST",
- )
- try:
- with urllib.request.urlopen(request, timeout=15) as response:
- response.read()
- return response.status
- except urllib.error.HTTPError as error:
- return record_http_error(label, error, body)
-
-def post_jsonrpc_batch(label, requests):
- encoded = json.dumps(requests).encode()
- request = urllib.request.Request(
- f"http://{{HOST}}:{{PORT}}/rpc",
- data=encoded,
- headers={{"Content-Type": "application/json"}},
- method="POST",
- )
- try:
- with urllib.request.urlopen(request, timeout=15) as response:
- response.read()
- return response.status
- except urllib.error.HTTPError as error:
- return record_http_error(label, error, requests)
-
-def post_invalid_json(label):
- encoded = b"not valid json {{"
- request = urllib.request.Request(
- f"http://{{HOST}}:{{PORT}}/rpc",
- data=encoded,
- headers={{"Content-Type": "application/json", "Content-Length": str(len(encoded))}},
- method="POST",
- )
- try:
- with urllib.request.urlopen(request, timeout=15) as response:
- response.read()
- return response.status
- except urllib.error.HTTPError as error:
- return record_http_error(label, error, text(encoded))
-
-def read_until(sock, marker):
- data = b""
- while marker not in data:
- chunk = sock.recv(4096)
- if not chunk:
- break
- data += chunk
- return data
-
-def read_response(sock):
- response = read_until(sock, b"\r\n\r\n")
- headers, _, body = response.partition(b"\r\n\r\n")
- content_length = 0
- for line in headers.split(b"\r\n")[1:]:
- if line.lower().startswith(b"content-length:"):
- content_length = int(line.split(b":", 1)[1].strip())
- break
- while len(body) < content_length:
- chunk = sock.recv(4096)
- if not chunk:
- break
- body += chunk
- return response, body
-
-def status_code(response, label):
- parts = response.split()
- if len(parts) < 2:
- DETAILS[f"{{label}}_raw"] = response.decode(errors="replace")
- raise RuntimeError(f"{{label}}: malformed HTTP response: {{response!r}}")
- try:
- return int(parts[1])
- except ValueError as error:
- DETAILS[f"{{label}}_raw"] = response.decode(errors="replace")
- raise RuntimeError(f"{{label}}: non-numeric HTTP status: {{response!r}}") from error
-
-def record_raw_response(label, response, body=b""):
- code = status_code(response, label)
- if code != 200:
- DETAILS[f"{{label}}_raw"] = text(response)
- if body:
- DETAILS[f"{{label}}_body"] = text(body)
- return code
-
-def raw_http_status(label, request):
- last_error = None
- for attempt in range(5):
- try:
- with socket.create_connection((HOST, PORT), timeout=15) as sock:
- sock.sendall(request)
- sock.shutdown(socket.SHUT_WR)
- response, body = read_response(sock)
- return record_raw_response(f"{{label}}_response", response, body)
- except (OSError, RuntimeError) as error:
- last_error = error
- DETAILS[f"{{label}}_attempt_{{attempt + 1}}_error"] = str(error)
- time.sleep(0.2)
-
- raise RuntimeError(f"{{label}}: failed after 5 attempts: {{last_error}}")
-
-def raw_jsonrpc_status(method, params, label):
- target = f"{{HOST}}:{{PORT}}"
- body = {{"jsonrpc": "2.0", "id": 1, "method": method}}
- if params is not None:
- body["params"] = params
- encoded = json.dumps(body).encode()
- request = (
- f"POST /rpc HTTP/1.1\r\n"
- f"Host: {{target}}\r\n"
- f"Content-Type: application/json\r\n"
- f"Content-Length: {{len(encoded)}}\r\n"
- f"Connection: close\r\n"
- f"\r\n"
- ).encode() + encoded
- return raw_http_status(label, request)
-
-results = {{
- # forward proxy — method-only allow rules
- "forward_method_initialize_allowed": post_jsonrpc("forward_method_initialize_allowed", "initialize", {{"protocolVersion": "2025-11-25", "capabilities": {{}}}}),
- "forward_method_tools_list_allowed": post_jsonrpc("forward_method_tools_list_allowed", "tools/list"),
-
- # forward proxy — method allow/deny rules
- "forward_method_tools_call_allowed": post_jsonrpc("forward_method_tools_call_allowed", "tools/call", {{"name": "read_status"}}),
- "forward_method_tools_call_with_unmatched_params_allowed": post_jsonrpc("forward_method_tools_call_with_unmatched_params_allowed", "tools/call", {{"name": "blocked_action", "arguments": {{"scope": "ignored"}}}}),
- "forward_method_tools_delete_denied": post_jsonrpc("forward_method_tools_delete_denied", "tools/delete", {{"name": "purge_cache"}}),
-
- # forward proxy — batch: all requests allowed
- "forward_batch_all_allowed": post_jsonrpc_batch("forward_batch_all_allowed", [
- {{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}},
- {{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {{"name": "read_status"}}}},
- ]),
-
- # forward proxy — batch: one denied request causes full batch denial
- "forward_batch_one_denied": post_jsonrpc_batch("forward_batch_one_denied", [
- {{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}},
- {{"jsonrpc": "2.0", "id": 2, "method": "tools/delete", "params": {{"name": "purge_cache"}}}},
- ]),
-
- # forward proxy — invalid JSON body fails closed before generic rules apply
- "forward_invalid_json_denied": post_invalid_json("forward_invalid_json_denied"),
-
- # raw socket path — representative allowed and denied cases
- "raw_method_initialize_allowed": raw_jsonrpc_status("initialize", {{"protocolVersion": "2025-11-25", "capabilities": {{}}}}, "raw_method_initialize_allowed"),
- "raw_method_tools_list_allowed": raw_jsonrpc_status("tools/list", None, "raw_method_tools_list_allowed"),
- "raw_method_tools_call_allowed": raw_jsonrpc_status("tools/call", {{"name": "read_status"}}, "raw_method_tools_call_allowed"),
- "raw_method_tools_call_with_unmatched_params_allowed": raw_jsonrpc_status("tools/call", {{"name": "blocked_action", "arguments": {{"scope": "ignored"}}}}, "raw_method_tools_call_with_unmatched_params_allowed"),
- "raw_method_tools_delete_denied": raw_jsonrpc_status("tools/delete", {{"name": "purge_cache"}}, "raw_method_tools_delete_denied"),
-}}
-results.update(DETAILS)
-print(json.dumps(results, sort_keys=True))
-"#,
- host = server.host,
- port = server.port,
- );
-
- let guard = SandboxGuard::create(&["--policy", &policy_path, "--", "python3", "-c", &script])
- .await
- .expect("sandbox create");
-
- for (key, expected) in [
- // forward proxy — allowed
- ("forward_method_initialize_allowed", 200),
- ("forward_method_tools_list_allowed", 200),
- ("forward_method_tools_call_allowed", 200),
- (
- "forward_method_tools_call_with_unmatched_params_allowed",
- 200,
- ),
- // forward proxy — method denied
- ("forward_method_tools_delete_denied", 403),
- // forward proxy — batch
- ("forward_batch_all_allowed", 200),
- ("forward_batch_one_denied", 403),
- // forward proxy — parse error
- ("forward_invalid_json_denied", 403),
- // raw socket path — allowed
- ("raw_method_initialize_allowed", 200),
- ("raw_method_tools_list_allowed", 200),
- ("raw_method_tools_call_allowed", 200),
- ("raw_method_tools_call_with_unmatched_params_allowed", 200),
- // raw socket path — method denied
- ("raw_method_tools_delete_denied", 403),
- ] {
- let expected_fragment = format!(r#""{key}": {expected}"#);
- assert!(
- guard.create_output.contains(&expected_fragment),
- "expected {key}={expected}, got:\n{}",
- guard.create_output
- );
- }
-}
-
-#[tokio::test]
-async fn jsonrpc_forward_proxy_hard_denies_response_frames_in_default_audit_mode() {
- let server = start_test_server(AUDIT_TEST_SERVER_ALIAS)
- .await
- .expect("start test server");
- let policy =
- write_jsonrpc_default_audit_policy(&server.host, server.port).expect("write custom policy");
- let policy_path = policy
- .path()
- .to_str()
- .expect("temp policy path should be utf-8")
- .to_string();
-
- let script = format!(
- r#"
-import json
-import urllib.error
-import urllib.request
-
-HOST = {host:?}
-PORT = {port}
-
-def post_jsonrpc(body):
- encoded = json.dumps(body).encode()
- request = urllib.request.Request(
- f"http://{{HOST}}:{{PORT}}/rpc",
- data=encoded,
- headers={{"Content-Type": "application/json"}},
- method="POST",
- )
- try:
- with urllib.request.urlopen(request, timeout=15) as response:
- response.read()
- return response.status
- except urllib.error.HTTPError as error:
- error.read()
- return error.code
-
-results = {{
- "forward_unknown_method_audited": post_jsonrpc({{"jsonrpc": "2.0", "id": 1, "method": "unknown/method"}}),
- "forward_response_frame_hard_denied": post_jsonrpc({{"jsonrpc": "2.0", "id": 1, "result": {{}}}}),
-}}
-print(json.dumps(results, sort_keys=True))
-"#,
- host = server.host,
- port = server.port,
- );
-
- let guard = SandboxGuard::create(&["--policy", &policy_path, "--", "python3", "-c", &script])
- .await
- .expect("sandbox create");
-
- for (key, expected) in [
- ("forward_unknown_method_audited", 200),
- ("forward_response_frame_hard_denied", 403),
- ] {
- let expected_fragment = format!(r#""{key}": {expected}"#);
- assert!(
- guard.create_output.contains(&expected_fragment),
- "expected {key}={expected}, got:\n{}",
- guard.create_output
- );
- }
-}
diff --git a/e2e/rust/tests/forward_proxy_l7_bypass.rs b/e2e/rust/tests/forward_proxy_l7_bypass.rs
deleted file mode 100644
index f274f20e93..0000000000
--- a/e2e/rust/tests/forward_proxy_l7_bypass.rs
+++ /dev/null
@@ -1,239 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-//! Regression tests: the forward proxy path must evaluate L7 rules for
-//! endpoints that have them configured. Allowed requests (e.g. GET on a
-//! read-only endpoint) should succeed; denied requests (e.g. POST) should
-//! receive 403.
-
-#![cfg(feature = "e2e")]
-
-use std::io::Write;
-
-use openshell_e2e::harness::container::ContainerHttpServer;
-use openshell_e2e::harness::sandbox::SandboxGuard;
-use tempfile::NamedTempFile;
-
-async fn start_test_server(alias: &str) -> Result {
- let script = r#"from http.server import BaseHTTPRequestHandler, HTTPServer
-
-class Handler(BaseHTTPRequestHandler):
- def do_GET(self):
- if self.headers.get("Upgrade"):
- self.send_response(101)
- self.send_header("Connection", "Upgrade")
- self.send_header("Upgrade", "websocket")
- self.send_header("Sec-WebSocket-Accept", "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=")
- self.end_headers()
- return
- self.send_response(200)
- self.end_headers()
- self.wfile.write(b'{"ok":true}')
- def do_DELETE(self):
- self.send_response(200)
- self.end_headers()
- self.wfile.write(b'{"ok":true}')
- def log_message(self, format, *args):
- pass
-
-HTTPServer(("0.0.0.0", 8000), Handler).serve_forever()
-"#;
-
- ContainerHttpServer::start_python(alias, script).await
-}
-
-fn write_policy_with_l7_rules(host: &str, port: u16) -> Result {
- let mut file = NamedTempFile::new().map_err(|e| format!("create temp policy file: {e}"))?;
- let policy = format!(
- r#"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only:
- - /usr
- - /lib
- - /proc
- - /dev/urandom
- - /app
- - /etc
- - /var/log
- read_write:
- - /sandbox
- - /tmp
- - /dev/null
-
-landlock:
- compatibility: best_effort
-
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-
-network_policies:
- test_l7:
- name: test_l7
- endpoints:
- - host: {host}
- port: {port}
- protocol: rest
- enforcement: enforce
- allowed_ips:
- - "10.0.0.0/8"
- - "172.0.0.0/8"
- - "192.168.0.0/16"
- - "fc00::/7"
- rules:
- - allow:
- method: GET
- path: /allowed
- binaries:
- - path: /usr/bin/curl
- - path: /usr/bin/python*
- - path: /usr/local/bin/python*
- - path: /sandbox/.uv/python/*/bin/python*
-"#
- );
- file.write_all(policy.as_bytes())
- .map_err(|e| format!("write temp policy file: {e}"))?;
- file.flush()
- .map_err(|e| format!("flush temp policy file: {e}"))?;
- Ok(file)
-}
-
-/// GET /allowed should succeed — the L7 policy explicitly allows it.
-#[tokio::test]
-async fn forward_proxy_allows_l7_permitted_request() {
- let server = start_test_server("rest-l7-allow.openshell.test")
- .await
- .expect("start test server");
- let policy =
- write_policy_with_l7_rules(&server.host, server.port).expect("write custom policy");
- let policy_path = policy
- .path()
- .to_str()
- .expect("temp policy path should be utf-8")
- .to_string();
-
- let script = format!(
- r#"
-import urllib.request, urllib.error, json, sys
-url = "http://{host}:{port}/allowed"
-try:
- resp = urllib.request.urlopen(url, timeout=15)
- last = {{"status": resp.status, "error": None}}
-except urllib.error.HTTPError as e:
- last = {{"status": e.code, "error": str(e)}}
-except Exception as e:
- last = {{"status": -1, "error": str(e)}}
-print(json.dumps(last))
-"#,
- host = server.host,
- port = server.port,
- );
-
- let guard = SandboxGuard::create(&["--policy", &policy_path, "--", "python3", "-c", &script])
- .await
- .expect("sandbox create");
-
- // L7 policy allows GET /allowed — should succeed.
- assert!(
- guard.create_output.contains("\"status\": 200"),
- "expected 200 for L7-allowed GET, got:\n{}",
- guard.create_output
- );
-}
-
-/// POST /allowed should be denied — the L7 policy only allows GET.
-#[tokio::test]
-async fn forward_proxy_denies_l7_blocked_request() {
- let server = start_test_server("rest-l7-deny.openshell.test")
- .await
- .expect("start test server");
- let policy =
- write_policy_with_l7_rules(&server.host, server.port).expect("write custom policy");
- let policy_path = policy
- .path()
- .to_str()
- .expect("temp policy path should be utf-8")
- .to_string();
-
- let script = format!(
- r#"
-import urllib.request, urllib.error, json, sys
-url = "http://{host}:{port}/allowed"
-req = urllib.request.Request(url, data=b"test", method="POST")
-try:
- resp = urllib.request.urlopen(req, timeout=15)
- print(json.dumps({{"status": resp.status, "error": None}}))
-except urllib.error.HTTPError as e:
- print(json.dumps({{"status": e.code, "error": str(e)}}))
-except Exception as e:
- print(json.dumps({{"status": -1, "error": str(e)}}))
-"#,
- host = server.host,
- port = server.port,
- );
-
- let guard = SandboxGuard::create(&["--policy", &policy_path, "--", "python3", "-c", &script])
- .await
- .expect("sandbox create");
-
- // L7 policy denies POST — should return 403.
- assert!(
- guard.create_output.contains("\"status\": 403"),
- "expected 403 for L7-denied POST, got:\n{}",
- guard.create_output
- );
-}
-
-/// A permitted GET cannot switch a REST endpoint into an uninspected tunnel.
-#[tokio::test]
-async fn rest_upgrade_is_refused_in_enforce_and_audit_modes() {
- let server = start_test_server("rest-upgrade.openshell.test")
- .await
- .expect("start backend");
- for enforcement in ["enforce", "audit"] {
- let source = write_policy_with_l7_rules(&server.host, server.port).unwrap();
- let policy = std::fs::read_to_string(source.path()).unwrap().replace(
- "enforcement: enforce",
- &format!("enforcement: {enforcement}"),
- );
- let mut file = NamedTempFile::new().unwrap();
- file.write_all(policy.as_bytes()).unwrap();
- file.flush().unwrap();
- let policy_path = file.path().to_str().unwrap();
- let script = format!(
- r#"
-import socket
-for target in ["/allowed", "http://{host}:{port}/allowed"]:
- s = socket.create_connection(("{host}", {port}), timeout=15)
- request = ("GET " + target + " HTTP/1.1\r\nHost: {host}:{port}\r\n"
- "Connection: Upgrade\r\nUpgrade: websocket\r\n"
- "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n")
- s.sendall(request.encode())
- response = b""
- while True:
- chunk = s.recv(4096)
- if not chunk:
- break
- response += chunk
- s.close()
- assert response.startswith(b"HTTP/1.1 403"), response
- assert b"unsupported_l7_protocol" in response, response
- assert b"REST endpoints" in response, response
-print("REST_UPGRADE_REFUSED")
-"#,
- host = server.host,
- port = server.port
- );
- let guard =
- SandboxGuard::create(&["--policy", policy_path, "--", "python3", "-c", &script])
- .await
- .expect("sandbox create");
- assert!(
- guard.create_output.contains("REST_UPGRADE_REFUSED"),
- "{enforcement}: {}",
- guard.create_output
- );
- }
-}
diff --git a/e2e/rust/tests/host_gateway_alias.rs b/e2e/rust/tests/host_gateway_alias.rs
index e3f8cb1c9f..2f5647356b 100644
--- a/e2e/rust/tests/host_gateway_alias.rs
+++ b/e2e/rust/tests/host_gateway_alias.rs
@@ -4,76 +4,14 @@
#![cfg(feature = "e2e")]
use std::io::Write;
-use std::process::Stdio;
-use openshell_e2e::harness::binary::openshell_cmd;
-use openshell_e2e::harness::container::is_e2e_driver;
use openshell_e2e::harness::sandbox::SandboxGuard;
-use tempfile::{Builder as TempFileBuilder, NamedTempFile};
+use tempfile::NamedTempFile;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
-const BINDING_PROVIDER_A_NAME: &str = "e2e-static-endpoint-binding-provider-a";
-const BINDING_PROVIDER_B_NAME: &str = "e2e-static-endpoint-binding-provider-b";
-const BINDING_PROFILE_A_ID: &str = "e2e-static-endpoint-binding-a";
-const BINDING_PROFILE_B_ID: &str = "e2e-static-endpoint-binding-b";
-
-async fn run_cli(args: &[&str]) -> Result {
- let mut cmd = openshell_cmd();
- cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
-
- let output = cmd
- .output()
- .await
- .map_err(|e| format!("failed to spawn openshell {}: {e}", args.join(" ")))?;
-
- let stdout = String::from_utf8_lossy(&output.stdout).to_string();
- let stderr = String::from_utf8_lossy(&output.stderr).to_string();
- let combined = format!("{stdout}{stderr}");
-
- if !output.status.success() {
- return Err(format!(
- "openshell {} failed (exit {:?}):\n{combined}",
- args.join(" "),
- output.status.code()
- ));
- }
-
- Ok(combined)
-}
-
-async fn wait_for_sandbox_logs(
- sandbox_name: &str,
- expected: impl Fn(&str) -> bool,
-) -> Result {
- let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
-
- loop {
- let logs = run_cli(&[
- "logs",
- sandbox_name,
- "-n",
- "500",
- "--since",
- "2m",
- "--source",
- "sandbox",
- ])
- .await?;
- if expected(&logs) {
- return Ok(logs);
- }
- if tokio::time::Instant::now() >= deadline {
- return Err(format!(
- "timed out waiting for expected sandbox logs:\n{logs}"
- ));
- }
- tokio::time::sleep(std::time::Duration::from_millis(250)).await;
- }
-}
-
struct HostServer {
port: u16,
task: JoinHandle<()>,
@@ -81,13 +19,6 @@ struct HostServer {
impl HostServer {
async fn start(response_body: &str) -> Result {
- Self::start_with_auth_check(response_body, None).await
- }
-
- async fn start_with_auth_check(
- response_body: &str,
- expected_authorization: Option<&str>,
- ) -> Result {
let listener = TcpListener::bind(("0.0.0.0", 0))
.await
.map_err(|e| format!("bind host test server: {e}"))?;
@@ -96,14 +27,12 @@ impl HostServer {
.map_err(|e| format!("read host test server address: {e}"))?
.port();
let response_body = response_body.as_bytes().to_vec();
- let expected_authorization = expected_authorization.map(str::to_string);
let task = tokio::spawn(async move {
loop {
let Ok((mut stream, _)) = listener.accept().await else {
break;
};
let body = response_body.clone();
- let expected_authorization = expected_authorization.clone();
tokio::spawn(async move {
let mut request = Vec::new();
let mut buf = [0_u8; 1024];
@@ -119,17 +48,6 @@ impl HostServer {
break;
}
}
-
- let body = expected_authorization.map_or(body, |expected| {
- let request = String::from_utf8_lossy(&request);
- format!(
- r#"{{"authorized":{}}}"#,
- request.lines().any(|line| {
- line.eq_ignore_ascii_case(&format!("Authorization: {expected}"))
- })
- )
- .into_bytes()
- });
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
@@ -147,114 +65,11 @@ impl HostServer {
}
}
-fn write_binding_profile(
- id: &str,
- display_name: &str,
- env_var: &str,
- host: &str,
- port: u16,
-) -> Result {
- let mut file = TempFileBuilder::new()
- .suffix(".yaml")
- .tempfile()
- .map_err(|e| format!("create provider profile: {e}"))?;
- let profile = format!(
- r#"id: {id}
-display_name: {display_name}
-category: other
-credentials:
- - name: bound_token
- env_vars: [{env_var}]
- required: true
- auth_style: bearer
- header_name: authorization
-endpoints:
- - host: {host}
- port: {port}
- path: /allowed/**
- protocol: rest
- access: full
- enforcement: enforce
-binaries: [/usr/bin/bash]
-"#
- );
- file.write_all(profile.as_bytes())
- .map_err(|e| format!("write provider profile: {e}"))?;
- file.flush()
- .map_err(|e| format!("flush provider profile: {e}"))?;
- Ok(file)
-}
-
-fn write_binding_policy(port: u16) -> Result {
- let mut file = NamedTempFile::new().map_err(|e| format!("create binding policy: {e}"))?;
- let policy = format!(
- r#"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only: [/bin, /usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log]
- read_write: [/sandbox, /tmp, /dev/null]
-
-landlock:
- compatibility: best_effort
-
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-
-network_policies:
- binding_test:
- name: binding_test
- endpoints:
- - host: host.openshell.internal
- port: {port}
- path: /**
- protocol: rest
- access: full
- enforcement: enforce
- - host: host.docker.internal
- port: {port}
- path: /**
- protocol: rest
- access: full
- enforcement: enforce
- binaries:
- - path: /usr/bin/bash
-"#
- );
- file.write_all(policy.as_bytes())
- .map_err(|e| format!("write binding policy: {e}"))?;
- file.flush()
- .map_err(|e| format!("flush binding policy: {e}"))?;
- Ok(file)
-}
-
impl Drop for HostServer {
fn drop(&mut self) {
self.task.abort();
}
}
-
-async fn delete_provider(name: &str) {
- let mut cmd = openshell_cmd();
- cmd.arg("provider")
- .arg("delete")
- .arg(name)
- .stdout(Stdio::null())
- .stderr(Stdio::null());
- let _ = cmd.status().await;
-}
-
-async fn delete_provider_profile(id: &str) {
- let mut cmd = openshell_cmd();
- cmd.arg("profile")
- .arg("delete")
- .arg(id)
- .stdout(Stdio::null())
- .stderr(Stdio::null());
- let _ = cmd.status().await;
-}
-
fn write_policy(port: u16) -> Result {
let mut file = NamedTempFile::new().map_err(|e| format!("create temp policy file: {e}"))?;
let policy = format!(
@@ -340,229 +155,3 @@ async fn sandbox_reaches_host_openshell_internal_via_host_gateway_alias() {
guard.create_output
);
}
-
-#[tokio::test]
-async fn sandbox_receives_eof_after_closing_http_response() {
- for response in [
- "HTTP/1.0 200 OK\r\nContent-Length: 3\r\n\r\nOK\n",
- "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 3\r\n\r\nOK\n",
- "HTTP/1.1 200 OK\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nOK\n\r\n0\r\n\r\n",
- ] {
- let listener = TcpListener::bind(("0.0.0.0", 0)).await.unwrap();
- let port = listener.local_addr().unwrap().port();
- let server = HostServer {
- port,
- task: tokio::spawn(async move {
- let (mut stream, _) = listener.accept().await.unwrap();
- stream.set_nodelay(true).expect("disable Nagle on fixture");
- let mut request = Vec::new();
- while !request.ends_with(b"\r\n\r\n") {
- request.push(stream.read_u8().await.unwrap());
- assert!(request.len() < 4096);
- }
- stream.write_all(response.as_bytes()).await.unwrap();
- stream.shutdown().await.unwrap();
- }),
- };
- let policy = write_policy(server.port).unwrap();
- let command = format!(
- r#"set -eu
-exec 3<>/dev/tcp/host.openshell.internal/{port}
-printf 'GET / HTTP/1.1\r\nHost: host.openshell.internal:{port}\r\n\r\n' >&3
-while true; do
- line=
- if IFS= read -r -t 5 line <&3; then
- printf '%s\n' "$line"
- else
- status=$?
- [ "$status" -eq 1 ] || {{ echo EOF_TIMEOUT; exit 1; }}
- [ -z "$line" ] || printf '%s\n' "$line"
- break
- fi
-done
-printf 'RESPONSE_EOF\n'
-"#,
- );
- let mut sandbox = SandboxGuard::create(&[
- "--policy",
- policy.path().to_str().unwrap(),
- "--no-auto-providers",
- "--",
- "/usr/bin/bash",
- "-c",
- &command,
- ])
- .await
- .expect("closing response must finish without a client timeout");
- assert!(
- sandbox.create_output.lines().any(|line| line == "OK"),
- "{}",
- sandbox.create_output
- );
- assert!(
- sandbox.create_output.contains("RESPONSE_EOF"),
- "{}",
- sandbox.create_output
- );
- assert!(
- !sandbox.create_output.contains("EOF_TIMEOUT"),
- "{}",
- sandbox.create_output
- );
- sandbox.cleanup().await;
- }
-}
-
-#[tokio::test]
-async fn static_provider_credentials_are_bound_to_profile_endpoints() {
- let server = HostServer::start_with_auth_check("", Some("Bearer e2e-bound-secret"))
- .await
- .expect("start credential echo server");
- let profile_a = write_binding_profile(
- BINDING_PROFILE_A_ID,
- "E2E static endpoint binding A",
- "BOUND_TOKEN_A",
- "host.openshell.internal",
- server.port,
- )
- .expect("write provider A binding profile");
- let profile_b = write_binding_profile(
- BINDING_PROFILE_B_ID,
- "E2E static endpoint binding B",
- "BOUND_TOKEN_B",
- "host.docker.internal",
- server.port,
- )
- .expect("write provider B binding profile");
- let policy = write_binding_policy(server.port).expect("write binding policy");
- let profile_a_path = profile_a.path().to_string_lossy().into_owned();
- let profile_b_path = profile_b.path().to_string_lossy().into_owned();
- let policy_path = policy.path().to_string_lossy().into_owned();
-
- delete_provider(BINDING_PROVIDER_A_NAME).await;
- delete_provider(BINDING_PROVIDER_B_NAME).await;
- delete_provider_profile(BINDING_PROFILE_A_ID).await;
- delete_provider_profile(BINDING_PROFILE_B_ID).await;
- run_cli(&["profile", "import", "--file", &profile_a_path])
- .await
- .expect("import provider A endpoint-binding profile");
- run_cli(&["profile", "import", "--file", &profile_b_path])
- .await
- .expect("import provider B endpoint-binding profile");
- run_cli(&[
- "provider",
- "create",
- "--name",
- BINDING_PROVIDER_A_NAME,
- "--type",
- BINDING_PROFILE_A_ID,
- "--credential",
- "BOUND_TOKEN_A=e2e-bound-secret",
- ])
- .await
- .expect("create endpoint-bound provider A");
- run_cli(&[
- "provider",
- "create",
- "--name",
- BINDING_PROVIDER_B_NAME,
- "--type",
- BINDING_PROFILE_B_ID,
- "--credential",
- "BOUND_TOKEN_B=e2e-provider-b-secret",
- ])
- .await
- .expect("create endpoint-bound provider B");
-
- let command = format!(
- r#"
-http_request() {{
- local host="$1" path="$2" status_line line
- HTTP_STATUS= HTTP_BODY=
- if ! exec 3<>"/dev/tcp/$host/{port}"; then
- HTTP_STATUS=connect-denied
- return 1
- fi
- printf 'GET %s HTTP/1.1\r\nHost: %s:{port}\r\nAuthorization: Bearer %s\r\nConnection: close\r\n\r\n' "$path" "$host" "$BOUND_TOKEN_A" >&3
- IFS= read -r status_line <&3 || return 1
- status_line="${{status_line%$'\r'}}"
- HTTP_STATUS="${{status_line#* }}"
- HTTP_STATUS="${{HTTP_STATUS%% *}}"
- while IFS= read -r line <&3; do
- line="${{line%$'\r'}}"
- [[ -z "$line" ]] && break
- done
- while IFS= read -r line <&3 || [[ -n "$line" ]]; do HTTP_BODY+="$line"; done
- exec 3>&- 3<&-
-}}
-http_request host.openshell.internal /allowed/check; allowed="$HTTP_BODY"
-http_request host.docker.internal /allowed/check || true; host_denied="$HTTP_STATUS"
-http_request host.openshell.internal /other/check; path_denied="$HTTP_STATUS"
-printf 'ALLOWED=%s HOST_DENIED=%s PATH_DENIED=%s\n' "$allowed" "$host_denied" "$path_denied"
-"#,
- port = server.port,
- );
- let mut guard = SandboxGuard::create(&[
- "--policy",
- &policy_path,
- "--provider",
- BINDING_PROVIDER_A_NAME,
- "--provider",
- BINDING_PROVIDER_B_NAME,
- "--no-auto-providers",
- "--",
- "/usr/bin/bash",
- "-c",
- &command,
- ])
- .await
- .expect("run endpoint-binding requests");
-
- let logs = wait_for_sandbox_logs(&guard.name, |logs| {
- logs.contains("openshell.provider_credential.endpoint_mismatch")
- && logs.contains("credential_endpoint_mismatch")
- })
- .await
- .expect("fetch endpoint mismatch logs");
- assert!(
- guard
- .create_output
- .contains(r#"ALLOWED={"authorized":true}"#),
- "credential should resolve at the bound endpoint:\n{}\nlogs:\n{logs}",
- guard.create_output,
- );
- let expected_host_denial = if is_e2e_driver("podman") {
- "HOST_DENIED=connect-denied"
- } else {
- "HOST_DENIED=403"
- };
- assert!(
- guard.create_output.contains(expected_host_denial),
- "same placeholder must be denied at an unbound host:\n{}",
- guard.create_output
- );
- assert!(
- guard.create_output.contains("PATH_DENIED=403"),
- "same placeholder must be denied at an unbound path on its bound host:\n{}",
- guard.create_output
- );
-
- assert!(
- logs.contains("openshell.provider_credential.endpoint_mismatch")
- && logs.contains("credential_endpoint_mismatch"),
- "OCSF logs should explain the endpoint-binding denial without secret material:\n{logs}"
- );
- assert!(
- !logs.contains("e2e-bound-secret")
- && !logs.contains("e2e-provider-b-secret")
- && !logs.contains("BOUND_TOKEN_A")
- && !logs.contains("BOUND_TOKEN_B"),
- "OCSF logs must not contain credential values or environment keys:\n{logs}"
- );
-
- guard.cleanup().await;
- delete_provider(BINDING_PROVIDER_A_NAME).await;
- delete_provider(BINDING_PROVIDER_B_NAME).await;
- delete_provider_profile(BINDING_PROFILE_A_ID).await;
- delete_provider_profile(BINDING_PROFILE_B_ID).await;
-}
diff --git a/e2e/rust/tests/live_policy_update.rs b/e2e/rust/tests/live_policy_update.rs
deleted file mode 100644
index b6a35c8898..0000000000
--- a/e2e/rust/tests/live_policy_update.rs
+++ /dev/null
@@ -1,704 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-//! E2E tests for live policy updates on a running sandbox.
-//!
-//! Covers the full round-trip:
-//! - Create sandbox with policy A
-//! - Verify initial policy version via `policy get`
-//! - Push same policy A again -> no version bump (idempotent)
-//! - Push different policy B -> new version, `--wait` for sandbox to load it
-//! - Verify policy history via `policy list`
-//!
-//! These tests replace the Python e2e tests `test_live_policy_update_and_logs`
-//! and `test_live_policy_update_from_empty_network_policies`, which were flaky
-//! due to hard-coded 90s poll timeouts. The Rust tests use the CLI's built-in
-//! `--wait` flag for reliable synchronization.
-//!
-//! Note: the removed Python tests also covered `GetSandboxLogs` RPC and
-//! verified actual proxy connectivity after policy update. Those are tracked
-//! as follow-up coverage gaps -- the proxy enforcement path is covered by the
-//! existing L4/L7/SSRF Python e2e tests, and log fetching needs a dedicated
-//! test.
-
-#![cfg(feature = "e2e")]
-
-use std::fmt::Write as _;
-use std::io::Write;
-use std::process::Stdio;
-
-use openshell_e2e::harness::binary::openshell_cmd;
-use openshell_e2e::harness::output::{extract_field, strip_ansi};
-use openshell_e2e::harness::sandbox::SandboxGuard;
-use tempfile::NamedTempFile;
-
-const SPARSE_POLICY: &str = include_str!(concat!(
- env!("CARGO_MANIFEST_DIR"),
- "/../../examples/policy-advisor/sandbox-policy.yaml"
-));
-
-// ---------------------------------------------------------------------------
-// Policy YAML builders
-// ---------------------------------------------------------------------------
-
-/// Build a policy YAML that allows any binary to reach the given hosts on
-/// port 443. Keep its filesystem paths aligned with the empty-network policy
-/// so live network updates do not remove startup filesystem access.
-///
-/// NOTE: The indentation in the format string is load-bearing YAML structure.
-fn write_policy(hosts: &[&str]) -> Result {
- let mut file = NamedTempFile::new().map_err(|e| format!("create temp policy file: {e}"))?;
-
- let mut network_rules = String::new();
- for (i, host) in hosts.iter().enumerate() {
- let _ = write!(
- network_rules,
- r#" rule_{i}:
- name: rule_{i}
- endpoints:
- - host: {host}
- port: 443
- binaries:
- - path: "/**"
-"#
- );
- }
-
- let policy = format!(
- r"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only:
- - /bin
- - /usr
- - /lib
- - /proc
- - /dev/urandom
- - /app
- - /etc
- - /var/log
- read_write:
- - /sandbox
- - /tmp
- - /dev/null
-
-landlock:
- compatibility: best_effort
-
-network_policies:
-{network_rules}"
- );
-
- file.write_all(policy.as_bytes())
- .map_err(|e| format!("write temp policy file: {e}"))?;
- file.flush()
- .map_err(|e| format!("flush temp policy file: {e}"))?;
- Ok(file)
-}
-
-/// Build a minimal policy YAML with no network rules. Both /bin and /usr
-/// are readable so shell entrypoints work on merged and unmerged images.
-fn write_empty_network_policy() -> Result {
- let mut file = NamedTempFile::new().map_err(|e| format!("create temp policy file: {e}"))?;
-
- let policy = r"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only:
- - /bin
- - /usr
- - /lib
- - /proc
- - /dev/urandom
- - /app
- - /etc
- - /var/log
- read_write:
- - /sandbox
- - /tmp
- - /dev/null
-
-landlock:
- compatibility: best_effort
-";
-
- file.write_all(policy.as_bytes())
- .map_err(|e| format!("write temp policy file: {e}"))?;
- file.flush()
- .map_err(|e| format!("flush temp policy file: {e}"))?;
- Ok(file)
-}
-
-fn write_sparse_policy() -> Result {
- let mut file = NamedTempFile::new().map_err(|e| format!("create temp policy file: {e}"))?;
- file.write_all(SPARSE_POLICY.as_bytes())
- .map_err(|e| format!("write temp policy file: {e}"))?;
- file.flush()
- .map_err(|e| format!("flush temp policy file: {e}"))?;
- Ok(file)
-}
-
-// ---------------------------------------------------------------------------
-// CLI helpers
-// ---------------------------------------------------------------------------
-
-struct CliResult {
- success: bool,
- output: String,
- exit_code: Option,
-}
-
-/// Run an `openshell` CLI command and return the result.
-async fn run_cli(args: &[&str]) -> CliResult {
- let mut cmd = openshell_cmd();
- cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
-
- let output = cmd.output().await.expect("spawn openshell command");
- let stdout = String::from_utf8_lossy(&output.stdout).to_string();
- let stderr = String::from_utf8_lossy(&output.stderr).to_string();
- let combined = strip_ansi(&format!("{stdout}{stderr}"));
-
- CliResult {
- success: output.status.success(),
- output: combined,
- exit_code: output.status.code(),
- }
-}
-
-/// Extract the policy version number from `policy get` output.
-///
-/// Uses the shared `extract_field` helper to find `Version: ` or
-/// `Revision: ` in CLI tabular output.
-fn extract_version(output: &str) -> Option {
- extract_field(output, "Version")
- .or_else(|| extract_field(output, "Revision"))
- .and_then(|v| v.parse::().ok())
-}
-
-/// Extract the policy hash from `policy get` output.
-fn extract_hash(output: &str) -> Option {
- extract_field(output, "Hash").or_else(|| extract_field(output, "Policy hash"))
-}
-
-/// Check that a version number appears in `policy list` output as a
-/// distinct field value (not just a substring of some other number).
-///
-/// Looks for the version number preceded by whitespace or at the start
-/// of a line, to avoid matching "2" inside "12" or timestamps.
-fn list_output_contains_version(output: &str, version: u32) -> bool {
- let v = version.to_string();
- output.lines().any(|line| {
- line.split_whitespace()
- .any(|word| word == v || word.starts_with(&format!("{v} ")))
- })
-}
-
-// ---------------------------------------------------------------------------
-// Tests
-// ---------------------------------------------------------------------------
-
-/// Read the effective policy through the same CLI boundary used by operators.
-async fn l7_scope_snapshot(name: &str) -> serde_json::Value {
- let result = run_cli(&["policy", "get", name, "--full", "--output", "json"]).await;
- assert!(result.success, "policy snapshot failed: {}", result.output);
- let snapshot: serde_json::Value =
- serde_json::from_str(&result.output).expect("policy get returns JSON");
- assert!(snapshot["version"].as_u64().is_some());
- assert!(
- snapshot["hash"]
- .as_str()
- .is_some_and(|hash| !hash.is_empty())
- );
- assert!(snapshot["policy"]["network_policies"].is_object());
- snapshot
-}
-
-/// Incomplete declarations reject without a revision; an explicit target
-/// changes only its endpoint even when another rule shares the host and ports.
-#[tokio::test]
-#[allow(clippy::too_many_lines)]
-async fn l7_append_target_scope_round_trip() {
- let mut policy = write_empty_network_policy().expect("write base policy");
- policy
- .write_all(
- br"
-network_policies:
- internal_api:
- name: internal_api
- binaries:
- - path: /usr/bin/curl
- - path: /usr/bin/python3
- endpoints:
- - host: api.example.com
- ports: [443, 8443]
- protocol: rest
- access: read-only
- - host: other.example.com
- port: 443
- protocol: rest
- access: read-only
- sibling:
- name: sibling
- binaries:
- - path: /usr/bin/wget
- endpoints:
- - host: api.example.com
- ports: [443, 8443]
- protocol: rest
- access: read-only
-",
- )
- .expect("write scoped policy");
- policy.flush().expect("flush scoped policy");
- let path = policy.path().to_str().expect("UTF-8 policy path");
- let mut guard = SandboxGuard::create_keep_with_args(
- &["--policy", path, "--no-tty"],
- &["sh", "-c", "echo Ready && sleep infinity"],
- "Ready",
- )
- .await
- .expect("create scoped-policy sandbox");
- let before = l7_scope_snapshot(&guard.name).await;
-
- // Check each independent axis with the other fully declared, so a guard
- // requiring both mismatches at once cannot satisfy this regression.
- for (ports, binaries) in [
- (
- "api.example.com:443:POST:/admin",
- vec!["/usr/bin/curl", "/usr/bin/python3"],
- ),
- (
- "api.example.com:443,8443:POST:/admin",
- vec!["/usr/bin/curl"],
- ),
- ] {
- let mut args = vec![
- "policy",
- "update",
- &guard.name,
- "--rule-name",
- "internal_api",
- "--add-allow",
- ports,
- ];
- for binary in binaries {
- args.extend(["--binary", binary]);
- }
- let rejected = run_cli(&args).await;
- assert!(
- !rejected.success,
- "partial scope was accepted: {}",
- rejected.output
- );
- let unchanged = l7_scope_snapshot(&guard.name).await;
- for field in ["version", "hash", "policy"] {
- assert_eq!(unchanged[field], before[field], "rejection changed {field}");
- }
- }
-
- let common = [
- "policy",
- "update",
- &guard.name,
- "--rule-name",
- "internal_api",
- "--binary",
- "/usr/bin/curl",
- "--binary",
- "/usr/bin/python3",
- ];
- let mut allow_args = common.to_vec();
- allow_args.extend([
- "--add-allow",
- "api.example.com:443,8443:POST:/admin",
- "--wait",
- ]);
- let accepted = run_cli(&allow_args).await;
- assert!(
- accepted.success,
- "explicit allow failed: {}",
- accepted.output
- );
- let after_allow = l7_scope_snapshot(&guard.name).await;
- assert!(after_allow["version"].as_u64() > before["version"].as_u64());
- assert_ne!(after_allow["hash"], before["hash"]);
- let rules = &after_allow["policy"]["network_policies"];
- assert_eq!(
- rules["sibling"],
- before["policy"]["network_policies"]["sibling"]
- );
- assert_eq!(
- rules["internal_api"]["endpoints"][1],
- before["policy"]["network_policies"]["internal_api"]["endpoints"][1]
- );
- assert!(
- rules["internal_api"]["endpoints"][0]["rules"]
- .as_array()
- .expect("allow rules")
- .iter()
- .any(|rule| rule["allow"]["method"] == "POST" && rule["allow"]["path"] == "/admin")
- );
-
- let mut deny_args = common.to_vec();
- deny_args.extend([
- "--add-deny",
- "api.example.com:443,8443:POST:/admin/private",
- "--wait",
- ]);
- let denied = run_cli(&deny_args).await;
- assert!(denied.success, "explicit deny failed: {}", denied.output);
- let after_deny = l7_scope_snapshot(&guard.name).await;
- assert!(after_deny["version"].as_u64() > after_allow["version"].as_u64());
- assert_eq!(
- after_deny["policy"]["network_policies"]["sibling"],
- before["policy"]["network_policies"]["sibling"]
- );
- assert!(
- after_deny["policy"]["network_policies"]["internal_api"]["endpoints"][0]["deny_rules"]
- .as_array()
- .expect("deny rules")
- .iter()
- .any(|rule| rule["method"] == "POST" && rule["path"] == "/admin/private")
- );
- guard.cleanup().await;
-}
-
-/// Test the full live policy update lifecycle:
-///
-/// 1. Create sandbox with policy A and `--keep`
-/// 2. Verify initial version >= 1
-/// 3. Push same policy A -> version unchanged (idempotent)
-/// 4. Push policy B (adds example.com) with `--wait` -> new version
-/// 5. Push policy B again -> idempotent
-/// 6. Verify policy list shows both versions
-#[tokio::test]
-#[allow(clippy::too_many_lines)]
-async fn live_policy_update_round_trip() {
- // --- Write two distinct policy files ---
- let policy_a = write_policy(&["api.anthropic.com"]).expect("write policy A");
- let policy_b = write_policy(&["api.anthropic.com", "example.com"]).expect("write policy B");
-
- let policy_a_path = policy_a
- .path()
- .to_str()
- .expect("policy A path should be utf-8")
- .to_string();
- let policy_b_path = policy_b
- .path()
- .to_str()
- .expect("policy B path should be utf-8")
- .to_string();
-
- // --- Create a long-running sandbox with its startup-only policy fields ---
- let mut guard = SandboxGuard::create_keep_with_args(
- &["--policy", &policy_a_path, "--no-tty"],
- &["sh", "-c", "echo Ready && sleep infinity"],
- "Ready",
- )
- .await
- .expect("create keep sandbox with policy A");
-
- // --- Verify initial policy version ---
- let r = run_cli(&["policy", "get", &guard.name]).await;
- assert!(
- r.success,
- "policy get should succeed (exit {:?}):\n{}",
- r.exit_code, r.output
- );
-
- let initial_version = extract_version(&r.output).unwrap_or_else(|| {
- panic!(
- "could not parse version from policy get output:\n{}",
- r.output
- )
- });
- assert!(
- initial_version >= 1,
- "initial policy version should be >= 1, got {initial_version}"
- );
-
- let initial_hash = extract_hash(&r.output);
-
- // --- Push same policy A again -> should be idempotent ---
- let r = run_cli(&[
- "policy",
- "set",
- &guard.name,
- "--policy",
- &policy_a_path,
- "--wait",
- "--timeout",
- "120",
- ])
- .await;
- assert!(
- r.success,
- "policy set A (repeat) should succeed (exit {:?}):\n{}",
- r.exit_code, r.output
- );
-
- let r = run_cli(&["policy", "get", &guard.name]).await;
- assert!(
- r.success,
- "policy get after repeat should succeed:\n{}",
- r.output
- );
-
- let repeat_version = extract_version(&r.output)
- .unwrap_or_else(|| panic!("could not parse version after repeat:\n{}", r.output));
- assert_eq!(
- repeat_version, initial_version,
- "same policy should not bump version: expected {initial_version}, got {repeat_version}"
- );
-
- if let (Some(ih), Some(rh)) = (&initial_hash, &extract_hash(&r.output)) {
- assert_eq!(ih, rh, "same policy should produce same hash");
- }
-
- // --- Push policy B -> should create new version ---
- let r = run_cli(&[
- "policy",
- "set",
- &guard.name,
- "--policy",
- &policy_b_path,
- "--wait",
- "--timeout",
- "120",
- ])
- .await;
- assert!(
- r.success,
- "policy set B should succeed (exit {:?}):\n{}",
- r.exit_code, r.output
- );
-
- let r = run_cli(&["policy", "get", &guard.name]).await;
- assert!(
- r.success,
- "policy get after B should succeed:\n{}",
- r.output
- );
-
- let new_version = extract_version(&r.output)
- .unwrap_or_else(|| panic!("could not parse version after B:\n{}", r.output));
- assert!(
- new_version > initial_version,
- "different policy should bump version: expected > {initial_version}, got {new_version}"
- );
-
- if let (Some(ih), Some(nh)) = (&initial_hash, &extract_hash(&r.output)) {
- assert_ne!(ih, nh, "different policy should produce different hash");
- }
-
- // --- Push policy B again -> idempotent ---
- let r = run_cli(&[
- "policy",
- "set",
- &guard.name,
- "--policy",
- &policy_b_path,
- "--wait",
- "--timeout",
- "120",
- ])
- .await;
- assert!(
- r.success,
- "policy set B (repeat) should succeed (exit {:?}):\n{}",
- r.exit_code, r.output
- );
-
- let r = run_cli(&["policy", "get", &guard.name]).await;
- assert!(
- r.success,
- "policy get after B repeat should succeed:\n{}",
- r.output
- );
-
- let repeat_b_version = extract_version(&r.output)
- .unwrap_or_else(|| panic!("could not parse version after B repeat:\n{}", r.output));
- assert_eq!(
- repeat_b_version, new_version,
- "same policy B should not bump version: expected {new_version}, got {repeat_b_version}"
- );
-
- // --- Verify policy list shows revision history ---
- let r = run_cli(&["policy", "list", &guard.name]).await;
- assert!(
- r.success,
- "policy list should succeed (exit {:?}):\n{}",
- r.exit_code, r.output
- );
-
- // Both versions should appear in the list output.
- assert!(
- list_output_contains_version(&r.output, new_version),
- "policy list should contain version {new_version}:\n{}",
- r.output
- );
- assert!(
- list_output_contains_version(&r.output, initial_version),
- "policy list should contain initial version {initial_version}:\n{}",
- r.output
- );
-
- guard.cleanup().await;
-}
-
-/// Test live policy update from an initially empty network policy:
-///
-/// 1. Create sandbox with no network rules and `--keep`
-/// 2. Push policy with a network rule using `--wait`
-/// 3. Verify the version bumped
-#[tokio::test]
-async fn live_policy_update_from_empty_network_policies() {
- let empty_policy = write_empty_network_policy().expect("write empty network policy");
- let full_policy = write_policy(&["example.com"]).expect("write full policy");
-
- let empty_path = empty_policy
- .path()
- .to_str()
- .expect("empty policy path should be utf-8")
- .to_string();
- let full_path = full_policy
- .path()
- .to_str()
- .expect("full policy path should be utf-8")
- .to_string();
-
- // Create the sandbox with the empty network policy so subsequent live
- // updates retain the same startup-only filesystem, landlock, and process
- // fields.
- let mut guard = SandboxGuard::create_keep_with_args(
- &["--policy", &empty_path, "--no-tty"],
- &["sh", "-c", "echo Ready && sleep infinity"],
- "Ready",
- )
- .await
- .expect("create keep sandbox with empty network policy");
-
- let r = run_cli(&["policy", "get", &guard.name]).await;
- assert!(
- r.success,
- "policy get (empty) should succeed:\n{}",
- r.output
- );
-
- let initial_version = extract_version(&r.output)
- .unwrap_or_else(|| panic!("could not parse version from empty policy:\n{}", r.output));
-
- // Push policy with network rules.
- let r = run_cli(&[
- "policy",
- "set",
- &guard.name,
- "--policy",
- &full_path,
- "--wait",
- "--timeout",
- "120",
- ])
- .await;
- assert!(
- r.success,
- "policy set (full) should succeed (exit {:?}):\n{}",
- r.exit_code, r.output
- );
-
- let r = run_cli(&["policy", "get", &guard.name]).await;
- assert!(r.success, "policy get (full) should succeed:\n{}", r.output);
-
- let new_version = extract_version(&r.output).unwrap_or_else(|| {
- panic!(
- "could not parse version after adding network rules:\n{}",
- r.output
- )
- });
- assert!(
- new_version > initial_version,
- "adding network rules should create new version > {initial_version}, got {new_version}"
- );
-
- guard.cleanup().await;
-}
-
-/// Regression for #2159: a sparse initial policy that the supervisor enriches
-/// with baseline filesystem paths during startup must have its resulting
-/// revision acknowledged as loaded, not left `Pending`.
-///
-/// Reproduction (matches the maintainer's triage): create a sandbox with the
-/// network-only `examples/policy-advisor/sandbox-policy.yaml`. The supervisor
-/// adds baseline filesystem paths, syncs the enriched policy back to the
-/// gateway (creating revision 2, superseding revision 1), builds the OPA engine
-/// and then acknowledges revision 2 as loaded. Before the fix, revision 2
-/// stayed `Pending` even though the sandbox was `Ready` and the policy was
-/// effective.
-///
-/// NOTE: This exercises the Docker-backed supervisor built from this branch.
-/// The exact `policy list` status wording ("Loaded"/"Superseded") may differ by
-/// CLI version; the assertions below key on the effective version reaching 2 and
-/// no revision remaining `Pending` once the acknowledgement lands.
-#[tokio::test]
-async fn initial_sparse_policy_is_acknowledged_as_loaded() {
- let sparse_policy = write_sparse_policy().expect("write sparse policy fixture");
- let sparse_policy_path = sparse_policy
- .path()
- .to_str()
- .expect("sparse policy path is not UTF-8");
-
- let mut guard = SandboxGuard::create_keep_with_args(
- &[
- "--name",
- "e2e-sparse-enrich",
- "--policy",
- sparse_policy_path,
- "--no-tty",
- ],
- &["sh", "-c", "echo Ready && sleep infinity"],
- "Ready",
- )
- .await
- .expect("create keep sandbox with sparse policy");
-
- // The enriched revision (2) is synced during startup; the acknowledgement
- // (LOADED) is delivered by the supervisor's poll loop shortly after Ready.
- // Poll until the effective policy is version 2 and no revision is Pending.
- let mut acknowledged = false;
- let mut last_list = String::new();
- for _ in 0..30 {
- let get = run_cli(&["policy", "get", &guard.name]).await;
- let version = get.success.then(|| extract_version(&get.output)).flatten();
-
- let list = run_cli(&["policy", "list", &guard.name]).await;
- last_list = list.output.clone();
- let pending = list.output.to_lowercase().contains("pending");
-
- if version == Some(2) && list.success && !pending {
- acknowledged = true;
- break;
- }
- tokio::time::sleep(std::time::Duration::from_secs(2)).await;
- }
-
- assert!(
- acknowledged,
- "enriched initial policy should reach revision 2 with no Pending revision.\n\
- last `policy list` output:\n{last_list}"
- );
-
- // Both the superseded original (1) and the loaded enriched revision (2)
- // must appear in the revision history.
- assert!(
- list_output_contains_version(&last_list, 2),
- "policy list should contain revision 2:\n{last_list}"
- );
- assert!(
- list_output_contains_version(&last_list, 1),
- "policy list should contain revision 1:\n{last_list}"
- );
-
- guard.cleanup().await;
-}
diff --git a/e2e/rust/tests/mcp_sessionless.rs b/e2e/rust/tests/mcp_sessionless.rs
deleted file mode 100644
index bf2261efa1..0000000000
--- a/e2e/rust/tests/mcp_sessionless.rs
+++ /dev/null
@@ -1,381 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-//! MCP request profiles through the sandbox's transparent network interception.
-//!
-//! A shared fixture serves legacy initialization, sessionless discovery, named
-//! tools, and a bounded subscription stream. Upstream receipts distinguish a
-//! policy denial from a tool request accepted by the fixture.
-
-#![cfg(feature = "e2e-host-gateway")]
-
-use std::io::Write;
-
-use openshell_e2e::harness::container::ContainerHttpServer;
-use openshell_e2e::harness::sandbox::SandboxGuard;
-use tempfile::NamedTempFile;
-
-const SERVER_ALIAS: &str = "mcp-sessionless.openshell.test";
-
-const SERVER_SCRIPT: &str = r#"
-import json
-from http.server import BaseHTTPRequestHandler, HTTPServer
-
-SESSIONLESS_VERSION = "2026-07-28"
-received = []
-
-class Handler(BaseHTTPRequestHandler):
- def reply(self, status, payload, content_type="application/json"):
- self.send_response(status)
- self.send_header("Content-Type", content_type)
- self.send_header("Content-Length", str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
-
- def do_GET(self):
- # The container fixture's readiness probe uses the root URL.
- self.reply(200 if self.path == "/" else 405, b"")
-
- def read_body(self):
- if self.headers.get("Transfer-Encoding", "").lower() != "chunked":
- return self.rfile.read(int(self.headers.get("Content-Length", "0")))
- body = bytearray()
- while True:
- size = int(self.rfile.readline().split(b";", 1)[0].strip(), 16)
- if size == 0:
- while self.rfile.readline().strip():
- pass
- return bytes(body)
- body.extend(self.rfile.read(size))
- self.rfile.read(2)
-
- def do_POST(self):
- message = json.loads(self.read_body())
- method = message["method"]
- params = message.get("params", {})
- version = (params.get("protocolVersion") if method == "initialize"
- else self.headers.get("MCP-Protocol-Version"))
- # Record parsed requests before fixture admission so rejected revisions
- # and tool attempts stay visible. HTTPServer handles requests serially.
- received.append([version, method, params.get("name")])
- if self.path != "/mcp" or version not in SUPPORTED_VERSIONS:
- self.reply(400, b"request revision did not reach the fixture intact")
- return
- if version == SESSIONLESS_VERSION:
- meta = params.get("_meta", {})
- if (self.headers.get("MCP-Protocol-Version") != version
- or self.headers.get("Mcp-Method") != method
- or meta.get("io.modelcontextprotocol/protocolVersion") != version
- or meta.get("io.modelcontextprotocol/clientCapabilities") != {}
- or (method == "tools/call"
- and self.headers.get("Mcp-Name") != params["name"])):
- self.reply(400, b"request metadata did not reach the fixture intact")
- return
-
- if method == "initialize" and version != SESSIONLESS_VERSION:
- result = {
- "protocolVersion": version,
- "capabilities": {"tools": {}},
- "serverInfo": {"name": "openshell-profile-fixture", "version": "1"},
- }
- elif method == "notifications/initialized" and version != SESSIONLESS_VERSION:
- self.reply(202, b"")
- return
- elif method == "server/discover" and version == SESSIONLESS_VERSION:
- result = {
- "supportedVersions": [version],
- "capabilities": {"tools": {"listChanged": True}},
- "ttlMs": 0,
- "cacheScope": "private",
- "_meta": {
- "io.modelcontextprotocol/serverInfo": {
- "name": "openshell-sessionless-fixture", "version": "1"
- }
- },
- }
- elif method == "tools/call":
- # Both tool names work upstream; OpenShell owns the policy denial.
- result = {
- "content": [{"type": "text", "text": params["name"]}],
- "isError": False,
- "_meta": {"fixtureRequests": list(received)},
- }
- if version == SESSIONLESS_VERSION:
- result["resultType"] = "complete"
- elif method == "subscriptions/listen" and version == SESSIONLESS_VERSION:
- subscription_meta = {"io.modelcontextprotocol/subscriptionId": message["id"]}
- events = [
- {
- "jsonrpc": "2.0",
- "method": "notifications/subscriptions/acknowledged",
- "params": {"notifications": params["notifications"], "_meta": subscription_meta},
- },
- {
- "jsonrpc": "2.0",
- "method": "notifications/tools/list_changed",
- "params": {"_meta": subscription_meta},
- },
- {
- "jsonrpc": "2.0",
- "id": message["id"],
- "result": {"resultType": "complete", "_meta": subscription_meta},
- },
- ]
- body = "".join("event: message\ndata: " + json.dumps(event) + "\n\n" for event in events)
- self.reply(200, body.encode(), "text/event-stream")
- return
- else:
- self.reply(400, b"unexpected method for the selected fixture revision")
- return
-
- self.reply(200, json.dumps({"jsonrpc": "2.0", "id": message["id"], "result": result}).encode())
-
- def log_message(self, format, *args):
- pass
-
-HTTPServer(("0.0.0.0", 8000), Handler).serve_forever()
-"#;
-
-const CLIENT_HELPERS: &str = r#"
-import json
-import urllib.error
-import urllib.request
-# Direct client connections pass through the sandbox's transparent interception.
-opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
-
-def post(request_id, method, params, version):
- params = dict(params)
- headers = {
- "Content-Type": "application/json",
- "Accept": "application/json, text/event-stream",
- }
- if method != "initialize":
- headers["MCP-Protocol-Version"] = version
- if version == "2026-07-28":
- params["_meta"] = {
- "io.modelcontextprotocol/protocolVersion": version,
- "io.modelcontextprotocol/clientCapabilities": {},
- "io.modelcontextprotocol/clientInfo": {"name": "openshell-e2e", "version": "1"},
- }
- headers["Mcp-Method"] = method
- if method == "tools/call":
- headers["Mcp-Name"] = params["name"]
- message = {"jsonrpc": "2.0", "method": method, "params": params}
- if request_id is not None:
- message["id"] = request_id
- request = urllib.request.Request(
- f"http://{HOST}:{PORT}/mcp",
- data=json.dumps(message).encode(),
- headers=headers,
- method="POST",
- )
- try:
- with opener.open(request, timeout=15) as response:
- return response.status, response.headers.get_content_type(), response.read()
- except urllib.error.HTTPError as error:
- return error.code, error.headers.get_content_type(), error.read()
-"#;
-
-const CLIENT_SCRIPT: &str = r#"
-VERSION = "2026-07-28"
-
-status, content_type, body = post(1, "server/discover", {}, VERSION)
-assert status == 200, ("discovery", status, body)
-assert content_type == "application/json", content_type
-discovery = json.loads(body)
-assert discovery["id"] == 1, discovery
-assert discovery["result"]["supportedVersions"] == [VERSION], discovery
-
-status, _, body = post(2, "tools/call", {"name": "read_status", "arguments": {}}, VERSION)
-assert status == 200, ("allowed tool", status, body)
-tool = json.loads(body)
-assert tool["id"] == 2, tool
-assert tool["result"]["content"] == [{"type": "text", "text": "read_status"}], tool
-
-status, _, body = post(3, "tools/call", {"name": "read_details", "arguments": {}}, VERSION)
-assert status == 403, ("denied tool", status, body)
-
-status, content_type, body = post(4, "subscriptions/listen", {"notifications": {"toolsListChanged": True}}, VERSION)
-assert status == 200, ("subscription", status, body)
-assert content_type == "text/event-stream", (content_type, body)
-events = [json.loads(line[6:]) for line in body.decode().splitlines() if line.startswith("data: ")]
-assert len(events) == 3, events
-assert events[0]["method"] == "notifications/subscriptions/acknowledged", events
-assert events[0]["params"]["notifications"] == {"toolsListChanged": True}, events
-assert events[1]["method"] == "notifications/tools/list_changed", events
-assert events[1]["params"]["_meta"]["io.modelcontextprotocol/subscriptionId"] == 4, events
-assert events[2]["id"] == 4 and events[2]["result"]["resultType"] == "complete", events
-
-print("MCP_SESSIONLESS_OK discovery=200 allowed_tool=200 denied_tool=403 subscription=200")
-"#;
-
-const PROFILE_CLIENT_SCRIPT: &str = r#"
-expected_receipts = []
-for version in SELECTED_VERSIONS:
- if version == "2026-07-28":
- status, _, body = post(1, "server/discover", {}, version)
- assert status == 200, (version, "discovery", status, body)
- assert json.loads(body)["result"]["supportedVersions"] == [version], body
- expected_receipts.append([version, "server/discover", None])
- else:
- status, _, body = post(1, "initialize", {
- "protocolVersion": version,
- "capabilities": {},
- "clientInfo": {"name": "openshell-e2e", "version": "1"},
- }, version)
- assert status == 200, (version, "initialize", status, body)
- assert json.loads(body)["result"]["protocolVersion"] == version, body
- expected_receipts.append([version, "initialize", None])
- status, _, body = post(None, "notifications/initialized", {}, version)
- assert status == 202, (version, "initialized", status, body)
- expected_receipts.append([version, "notifications/initialized", None])
-
- status, _, body = post(2, "tools/call", {"name": "read_status", "arguments": {}}, version)
- assert status == 200, (version, "allowed tool", status, body)
- tool = json.loads(body)
- assert tool["id"] == 2, tool
- assert tool["result"]["content"] == [{"type": "text", "text": "read_status"}], tool
- expected_receipts.append([version, "tools/call", "read_status"])
- assert tool["result"]["_meta"]["fixtureRequests"] == expected_receipts, tool
-
- status, _, body = post(3, "tools/call", {"name": "read_details", "arguments": {}}, version)
- assert status == 403, (version, "denied tool", status, body)
-
- # The fixture accepts both tools. A later allowed call proves the denial
- # came from the proxy and no denied operation reached the upstream.
- status, _, body = post(4, "tools/call", {"name": "read_status", "arguments": {}}, version)
- assert status == 200, (version, "receipt tool", status, body)
- receipt = json.loads(body)
- assert receipt["id"] == 4, receipt
- expected_receipts.append([version, "tools/call", "read_status"])
- assert receipt["result"]["_meta"]["fixtureRequests"] == expected_receipts, receipt
- print(f"MCP_PROFILE_OK version={version} allowed_tool=200 denied_tool=403 receipts=verified")
-"#;
-
-async fn start_server(alias: &str, versions: &[&str]) -> Result {
- let versions = serde_json::to_string(versions).map_err(|err| err.to_string())?;
- let script = format!("SUPPORTED_VERSIONS = {versions}\n{SERVER_SCRIPT}");
- ContainerHttpServer::start_python(alias, &script).await
-}
-
-fn write_policy(host: &str, port: u16, versions: &[&str]) -> Result {
- let mut file = NamedTempFile::new().map_err(|err| format!("create temp policy: {err}"))?;
- let legacy_rules = if versions.iter().any(|version| *version != "2026-07-28") {
- " - allow:\n method: initialize\n - allow:\n method: notifications/initialized\n"
- } else {
- ""
- };
- let versions = serde_json::to_string(versions).map_err(|err| err.to_string())?;
- let policy = format!(
- r#"version: 1
-filesystem_policy:
- include_workdir: true
- read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log]
- read_write: [/sandbox, /tmp, /dev/null]
-landlock:
- compatibility: best_effort
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-network_policies:
- mcp_sessionless:
- name: mcp_sessionless
- endpoints:
- - host: {host}
- port: {port}
- path: /mcp
- protocol: mcp
- enforcement: enforce
- allowed_ips: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]
- mcp:
- versions: {versions}
- max_body_bytes: 65536
- rules:
-{legacy_rules} - allow:
- method: server/discover
- - allow:
- method: tools/call
- tool: read_status
- - allow:
- method: subscriptions/listen
- deny_rules:
- - method: tools/call
- tool: read_details
- binaries:
- - path: /usr/bin/python*
- - path: /usr/local/bin/python*
- - path: /sandbox/.uv/python/*/bin/python*
-"#
- );
- file.write_all(policy.as_bytes())
- .map_err(|err| format!("write temp policy: {err}"))?;
- file.flush()
- .map_err(|err| format!("flush temp policy: {err}"))?;
- Ok(file)
-}
-
-async fn run_client(
- server: &ContainerHttpServer,
- versions: &[&str],
- client: &str,
-) -> Result {
- let policy = write_policy(&server.host, server.port, versions)?;
- let policy_path = policy
- .path()
- .to_str()
- .ok_or("temp policy path is not UTF-8")?;
- let selected_versions = serde_json::to_string(versions).map_err(|err| err.to_string())?;
- let script = format!(
- "HOST = {:?}\nPORT = {}\nSELECTED_VERSIONS = {selected_versions}\n{CLIENT_HELPERS}\n{client}",
- server.host, server.port
- );
- SandboxGuard::create(&["--policy", policy_path, "--", "python3", "-c", &script]).await
-}
-
-#[tokio::test]
-async fn sessionless_discovery_tools_and_subscription_use_request_metadata() {
- let versions = ["2026-07-28"];
- let server = start_server(SERVER_ALIAS, &versions)
- .await
- .expect("start sessionless MCP fixture");
- let sandbox = run_client(&server, &versions, CLIENT_SCRIPT)
- .await
- .expect("run sessionless MCP client in sandbox");
-
- assert!(
- sandbox.create_output.contains(
- "MCP_SESSIONLESS_OK discovery=200 allowed_tool=200 denied_tool=403 subscription=200"
- ),
- "expected completed sessionless MCP assertions, got:\n{}",
- sandbox.create_output
- );
-}
-
-#[tokio::test]
-async fn legacy_and_multi_version_profiles_authorize_tools_through_sandbox() {
- for versions in [
- &["2025-03-26"][..],
- &["2025-06-18"][..],
- &["2025-11-25", "2026-07-28"][..],
- ] {
- // Each scenario starts with fresh upstream receipts. Its distinct alias
- // avoids the sessionless test's fixture, and cleanup precedes alias reuse.
- let server = start_server("mcp-profiles.openshell.test", versions)
- .await
- .unwrap_or_else(|err| panic!("{versions:?}: start MCP fixture: {err}"));
- let mut sandbox = run_client(&server, versions, PROFILE_CLIENT_SCRIPT)
- .await
- .unwrap_or_else(|err| panic!("{versions:?}: run MCP sandbox client: {err}"));
- for version in versions {
- let marker = format!(
- "MCP_PROFILE_OK version={version} allowed_tool=200 denied_tool=403 receipts=verified"
- );
- assert!(
- sandbox.create_output.contains(&marker),
- "{versions:?}: expected completed {version} assertions, got:\n{}",
- sandbox.create_output
- );
- }
- sandbox.cleanup().await;
- }
-}
diff --git a/e2e/rust/tests/ocsf_console.rs b/e2e/rust/tests/ocsf_console.rs
deleted file mode 100644
index fbd2f6318b..0000000000
--- a/e2e/rust/tests/ocsf_console.rs
+++ /dev/null
@@ -1,160 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-#![cfg(feature = "e2e-docker")]
-
-//! Full OCSF collection through supervisor stderr, without filesystem access.
-
-use std::time::Duration;
-
-use openshell_e2e::harness::binary::openshell_cmd;
-use openshell_e2e::harness::sandbox::SandboxGuard;
-use serde_json::Value;
-use tokio::process::Command;
-use tokio::time::{Instant, sleep};
-
-async fn cli(args: &[&str]) -> String {
- let output = openshell_cmd().args(args).output().await.unwrap();
- assert!(
- output.status.success(),
- "CLI failed: {}",
- String::from_utf8_lossy(&output.stderr)
- );
- format!(
- "{}{}",
- String::from_utf8_lossy(&output.stdout),
- String::from_utf8_lossy(&output.stderr)
- )
-}
-
-async fn docker(args: &[&str]) -> (String, String) {
- let output = Command::new("docker").args(args).output().await.unwrap();
- assert!(
- output.status.success(),
- "Docker failed: {}",
- String::from_utf8_lossy(&output.stderr)
- );
- (
- String::from_utf8_lossy(&output.stdout).into_owned(),
- String::from_utf8_lossy(&output.stderr).into_owned(),
- )
-}
-
-fn json_records(stderr: &str) -> Vec {
- stderr
- .lines()
- .filter_map(|line| {
- let (_, payload) = line.split_once(" OCSF-JSON ")?;
- assert!(!payload.contains('\x1b'));
- Some(serde_json::from_str(payload).expect("complete JSON record on one line"))
- })
- .collect()
-}
-
-#[tokio::test]
-async fn network_events_are_json_on_supervisor_stderr_only() {
- let mut sandbox = SandboxGuard::create(&["--from", "nvcr.io/nvidia/base/ubuntu:24.04"])
- .await
- .expect("create sandbox");
- let filter = format!("label=openshell.ai/sandbox-name={}", sandbox.name);
- let (containers, _) = docker(&[
- "ps",
- "-q",
- "--filter",
- &filter,
- "--filter",
- "label=openshell.ai/isolation-role=supervisor",
- ])
- .await;
- let ids: Vec<_> = containers.lines().collect();
- assert_eq!(ids.len(), 1, "expected one supervisor: {containers}");
- let supervisor = ids[0];
- let (workload, _) = docker(&[
- "ps",
- "-q",
- "--filter",
- &filter,
- "--filter",
- "label=openshell.ai/isolation-role=sandbox",
- ])
- .await;
- let workload_ids: Vec<_> = workload.lines().collect();
- assert_eq!(workload_ids.len(), 1, "expected one workload: {workload}");
- let (image_uid, _) = docker(&["inspect", "--format", "{{.Image}}", workload_ids[0]]).await;
- let (_, before) = docker(&["logs", supervisor]).await;
- assert!(json_records(&before).is_empty(), "JSON must be opt-in");
-
- cli(&[
- "settings",
- "set",
- &sandbox.name,
- "--key",
- "ocsf_json_enabled",
- "--value",
- "true",
- ])
- .await;
- let started = Instant::now();
- let records = loop {
- cli(&[
- "sandbox",
- "exec",
- &sandbox.name,
- "--timeout",
- "10",
- "--",
- "bash",
- "-c",
- "echo > /dev/tcp/1.1.1.1/443 || true",
- ])
- .await;
- let (stdout, stderr) = docker(&["logs", supervisor]).await;
- assert!(
- !stdout.contains(" OCSF-JSON "),
- "audit JSON should be on stderr"
- );
- let records = json_records(&stderr);
- if records.iter().any(|record| {
- record["class_uid"] == 4001
- && record["dst_endpoint"]["port"] == 443
- && record["action"] == "Denied"
- }) {
- assert!(
- stderr.contains(" OCSF NET:OPEN "),
- "shorthand remains available"
- );
- break records;
- }
- assert!(
- started.elapsed() < Duration::from_secs(40),
- "no JSON network denial in stderr: {stderr}"
- );
- sleep(Duration::from_secs(1)).await;
- };
- for record in records {
- assert_eq!(record["metadata"]["version"], "1.8.0");
- assert!(
- record["metadata"]["uid"]
- .as_str()
- .is_some_and(|uid| !uid.is_empty())
- );
- assert_eq!(record["device"]["container"]["name"], sandbox.name);
- assert_eq!(
- record["device"]["container"]["image"]["uid"],
- image_uid.trim()
- );
- assert_eq!(
- record["device"]["container"]["image"]["name"],
- "nvcr.io/nvidia/base/ubuntu:24.04"
- );
- }
- // Allow the existing best-effort push batch to reach the gateway.
- sleep(Duration::from_secs(2)).await;
- let gateway_logs = cli(&["logs", &sandbox.name, "--source", "sandbox", "-n", "200"]).await;
- assert!(gateway_logs.contains("NET:OPEN"));
- assert!(
- !gateway_logs.contains("OCSF-JSON"),
- "gateway stream must remain unchanged"
- );
- sandbox.cleanup().await;
-}
diff --git a/e2e/rust/tests/podman_resource_limits.rs b/e2e/rust/tests/podman_resource_limits.rs
deleted file mode 100644
index 225f77ff8f..0000000000
--- a/e2e/rust/tests/podman_resource_limits.rs
+++ /dev/null
@@ -1,89 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-#![cfg(feature = "e2e-podman")]
-
-//! Podman-specific E2E coverage verifying that declared sandbox CPU/memory
-//! resource limits are actually enforced by cgroups inside the workload, not
-//! just echoed back by the API/template layer.
-//!
-//! The conformance `templates` suite already verifies that
-//! `sandbox template create --cpu ... --memory ...` is stored and returned
-//! correctly, but it never inspects the resulting container's real resource
-//! state. This test creates a sandbox with those flags directly and reads the
-//! cgroup v2 interface files from inside the sandbox itself, so it exercises
-//! the actual enforcement boundary the workload experiences.
-
-use openshell_e2e::harness::sandbox::SandboxGuard;
-
-const CGROUP_READ_POLICY: &str = r"version: 1
-filesystem_policy:
- include_workdir: true
- read_only: [/usr, /lib, /lib64, /proc, /etc, /sys/fs/cgroup]
- read_write: [/sandbox, /tmp, /dev/null]
-landlock:
- compatibility: best_effort
-network_policies: {}
-";
-
-const CPU_REQUEST: &str = "500m";
-const MEMORY_REQUEST: &str = "512Mi";
-
-// "500m" (500 millicores) becomes a 50000us quota over Podman's 100000us
-// (100ms) CFS period — see
-// crates/openshell-driver-podman/src/container.rs's parse_cpu_to_microseconds.
-// Verified directly against a real `podman run --cpus=0.5` container, whose
-// cpu.max reads "50000 100000".
-const EXPECTED_CPU_MAX: &str = "50000 100000";
-
-// "512Mi" (mebibytes) becomes exactly 512 * 1024 * 1024 bytes — see
-// crates/openshell-driver-podman/src/container.rs's parse_memory_to_bytes.
-// Verified directly against a real `podman run --memory=512m` container,
-// whose memory.max reads "536870912".
-const EXPECTED_MEMORY_MAX: &str = "536870912";
-
-#[tokio::test]
-async fn sandbox_resource_limits_are_enforced_via_cgroups() {
- if std::env::var("OPENSHELL_E2E_DRIVER").as_deref() != Ok("podman") {
- eprintln!("Skipping Podman resource-limit test: e2e driver is not podman");
- return;
- }
-
- let policy = tempfile::NamedTempFile::new().expect("create cgroup read policy file");
- std::fs::write(policy.path(), CGROUP_READ_POLICY).expect("write cgroup read policy");
- let policy_path = policy.path().to_str().expect("policy path is UTF-8");
- let mut sandbox = SandboxGuard::create(&[
- "--cpu",
- CPU_REQUEST,
- "--memory",
- MEMORY_REQUEST,
- "--policy",
- policy_path,
- ])
- .await
- .expect("sandbox create with resource limits should succeed");
-
- let memory_max = sandbox
- .exec(&["cat", "/sys/fs/cgroup/memory.max"])
- .await
- .expect("read memory.max from sandbox cgroup")
- .trim()
- .to_string();
- assert_eq!(
- memory_max, EXPECTED_MEMORY_MAX,
- "sandbox cgroup should enforce the declared {MEMORY_REQUEST} memory limit, got {memory_max}"
- );
-
- let cpu_max = sandbox
- .exec(&["cat", "/sys/fs/cgroup/cpu.max"])
- .await
- .expect("read cpu.max from sandbox cgroup")
- .trim()
- .to_string();
- assert_eq!(
- cpu_max, EXPECTED_CPU_MAX,
- "sandbox cgroup should enforce the declared {CPU_REQUEST} CPU limit, got {cpu_max}"
- );
-
- sandbox.cleanup().await;
-}
diff --git a/e2e/rust/tests/port_forward.rs b/e2e/rust/tests/port_forward.rs
deleted file mode 100644
index e91919d177..0000000000
--- a/e2e/rust/tests/port_forward.rs
+++ /dev/null
@@ -1,140 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-#![cfg(feature = "e2e")]
-
-//! E2E test: TCP port forwarding through a sandbox.
-//!
-//! Prerequisites:
-//! - A running openshell gateway (`mise run gateway:docker`)
-//! - The `openshell` binary (built automatically from the workspace)
-
-use std::time::Duration;
-
-use tokio::io::{AsyncReadExt, AsyncWriteExt};
-use tokio::net::TcpStream;
-
-use openshell_e2e::harness::port::{find_free_port, wait_for_port};
-use openshell_e2e::harness::sandbox::SandboxGuard;
-
-/// Python script that runs a single-threaded TCP echo server inside the
-/// sandbox. It prints `echo-server-ready` to stdout once listening, which
-/// the harness uses as the readiness marker.
-fn echo_server_script(port: u16) -> String {
- format!(
- r"
-import socket, sys, signal
-signal.signal(signal.SIGHUP, signal.SIG_IGN)
-signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
-port = {port}
-sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-sock.bind(('127.0.0.1', port))
-sock.listen(1)
-sock.settimeout(300)
-print('echo-server-ready', flush=True)
-try:
- while True:
- conn, _ = sock.accept()
- data = conn.recv(4096)
- if data:
- conn.sendall(b'echo:' + data)
- conn.close()
-except (socket.timeout, OSError):
- pass
-finally:
- sock.close()
-"
- )
-}
-
-/// Create a sandbox with a TCP echo server, forward the port locally, send
-/// data through it, and verify the echoed response.
-#[tokio::test]
-async fn port_forward_echo() {
- let port = find_free_port();
- let script = echo_server_script(port);
-
- // ---------------------------------------------------------------
- // Step 1 — Create a sandbox with the echo server running.
- // ---------------------------------------------------------------
- let mut guard = SandboxGuard::create_keep(&["python3", "-c", &script], "echo-server-ready")
- .await
- .expect("sandbox create with echo server");
-
- // ---------------------------------------------------------------
- // Step 2 — Start port forwarding in the background.
- // ---------------------------------------------------------------
- let mut forward_child = guard.spawn_forward(port).expect("spawn port forward");
-
- // Wait for the local port to accept connections.
- wait_for_port("127.0.0.1", port, Duration::from_secs(30))
- .await
- .expect("local port should open for forwarding");
-
- // Give the SSH tunnel a moment to fully establish the direct-tcpip channel.
- tokio::time::sleep(Duration::from_secs(2)).await;
-
- // ---------------------------------------------------------------
- // Step 3 — Send data through the forwarded port and verify response.
- // ---------------------------------------------------------------
- let expected = "echo:hello-nav";
- let mut last_response = String::new();
-
- for attempt in 1..=5 {
- match try_echo(port).await {
- Ok(resp) if resp.starts_with(expected) => {
- last_response = resp;
- break;
- }
- Ok(resp) => {
- last_response = resp;
- eprintln!("attempt {attempt}: unexpected response '{last_response}', retrying...");
- }
- Err(e) => {
- eprintln!("attempt {attempt}: connection error: {e}, retrying...");
- }
- }
- tokio::time::sleep(Duration::from_secs(2)).await;
- }
-
- assert!(
- last_response.starts_with(expected),
- "expected response starting with '{expected}', got '{last_response}'"
- );
-
- // ---------------------------------------------------------------
- // Cleanup — kill forward process, then sandbox guard handles the rest.
- // ---------------------------------------------------------------
- let _ = forward_child.kill().await;
- let _ = forward_child.wait().await;
- guard.cleanup().await;
-}
-
-/// Attempt to send `hello-nav\n` to the echo server and read the response.
-#[allow(
- clippy::disallowed_methods,
- reason = "the e2e workspace does not depend on openshell-core"
-)]
-async fn try_echo(port: u16) -> Result {
- let mut stream = TcpStream::connect(format!("127.0.0.1:{port}"))
- .await
- .map_err(|e| format!("connect: {e}"))?;
-
- stream
- .write_all(b"hello-nav\n")
- .await
- .map_err(|e| format!("write: {e}"))?;
-
- let mut buf = vec![0u8; 4096];
- let n = tokio::time::timeout(Duration::from_secs(10), stream.read(&mut buf))
- .await
- .map_err(|_| "read timeout".to_string())?
- .map_err(|e| format!("read: {e}"))?;
-
- let response = String::from_utf8_lossy(&buf[..n])
- .trim_end_matches(['\r', '\n'])
- .to_string();
-
- Ok(response)
-}
diff --git a/e2e/rust/tests/proxy_egress_pipeline.rs b/e2e/rust/tests/proxy_egress_pipeline.rs
deleted file mode 100644
index 09eda47615..0000000000
--- a/e2e/rust/tests/proxy_egress_pipeline.rs
+++ /dev/null
@@ -1,1683 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-#![cfg(feature = "e2e")]
-
-//! E2E coverage for the transparent sandbox egress pipeline.
-//!
-//! Workloads connect directly to their requested destinations. Seccomp
-//! notification diverts those sockets to the supervisor without proxy
-//! environment variables or explicit CONNECT requests. These tests cover:
-//! - live policy reloads affect new requests and close a pre-existing HTTP
-//! stream before its next request is forwarded;
-//! - `tls: skip` selects a byte-transparent TCP relay;
-//! - provider placeholders in HTTP headers and opted-in REST bodies are
-//! resolved without appearing in test output.
-
-use std::io::{self, Error, ErrorKind, Write};
-use std::process::Stdio;
-use std::sync::{
- Arc, Mutex,
- atomic::{AtomicUsize, Ordering},
-};
-
-use openshell_e2e::harness::binary::openshell_cmd;
-use openshell_e2e::harness::container::{SupportContainer, e2e_network_name};
-use openshell_e2e::harness::sandbox::SandboxGuard;
-use serde_json::Value;
-use serial_test::serial;
-use tempfile::{Builder as TempFileBuilder, NamedTempFile};
-use tokio::io::{AsyncReadExt, AsyncWriteExt};
-use tokio::net::{TcpListener, TcpStream};
-use tokio::task::JoinHandle;
-
-const TEST_SERVER_HOST: &str = "host.openshell.internal";
-const PROVIDER_NAME: &str = "e2e-proxy-egress-credentials";
-const PROVIDER_PROFILE_ID: &str = "e2e-proxy-egress-credentials";
-const TOKEN_ENV: &str = "PROXY_E2E_TOKEN";
-const TEST_SECRET: &str = "sk-e2e-proxy-egress-secret";
-const PLACEHOLDER_PREFIX: &str = "openshell:resolve:env:";
-const PRIVATE_ALLOWED_IPS: &str = r#" allowed_ips:
- - "10.0.0.0/8"
- - "172.0.0.0/8"
- - "192.168.0.0/16"
- - "fc00::/7""#;
-static PROVIDER_LOCK: Mutex<()> = Mutex::new(());
-
-async fn run_cli(args: &[&str]) -> Result {
- let mut cmd = openshell_cmd();
- cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
-
- let output = cmd
- .output()
- .await
- .map_err(|error| format!("failed to spawn openshell {}: {error}", args.join(" ")))?;
- let stdout = String::from_utf8_lossy(&output.stdout);
- let stderr = String::from_utf8_lossy(&output.stderr);
- let combined = format!("{stdout}{stderr}");
-
- if !output.status.success() {
- return Err(format!(
- "openshell {} failed (exit {:?}):\n{combined}",
- args.join(" "),
- output.status.code()
- ));
- }
-
- Ok(combined)
-}
-
-async fn wait_for_sandbox_logs(
- sandbox_name: &str,
- expected: impl Fn(&str) -> bool,
-) -> Result {
- let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
-
- loop {
- let logs = run_cli(&[
- "logs",
- sandbox_name,
- "-n",
- "500",
- "--since",
- "2m",
- "--source",
- "sandbox",
- ])
- .await?;
- if expected(&logs) {
- return Ok(logs);
- }
- if tokio::time::Instant::now() >= deadline {
- return Err(format!(
- "timed out waiting for expected sandbox logs:\n{logs}"
- ));
- }
- tokio::time::sleep(std::time::Duration::from_millis(250)).await;
- }
-}
-
-async fn delete_provider(name: &str) {
- let mut cmd = openshell_cmd();
- cmd.args(["provider", "delete", name])
- .stdout(Stdio::null())
- .stderr(Stdio::null());
- let _ = cmd.status().await;
-}
-
-async fn delete_provider_profile(id: &str) {
- let mut cmd = openshell_cmd();
- cmd.args(["profile", "delete", id])
- .stdout(Stdio::null())
- .stderr(Stdio::null());
- let _ = cmd.status().await;
-}
-
-async fn create_bound_provider(name: &str) -> Result {
- let credential = format!("{TOKEN_ENV}={TEST_SECRET}");
- run_cli(&[
- "provider",
- "create",
- "--name",
- name,
- "--type",
- PROVIDER_PROFILE_ID,
- "--credential",
- &credential,
- ])
- .await
-}
-
-fn write_credential_profile(port: u16) -> Result {
- let mut file = TempFileBuilder::new()
- .suffix(".yaml")
- .tempfile()
- .map_err(|error| format!("create provider profile: {error}"))?;
- let profile = format!(
- r#"id: {PROVIDER_PROFILE_ID}
-display_name: E2E proxy egress credentials
-category: other
-credentials:
- - name: proxy_e2e_token
- env_vars: [{TOKEN_ENV}]
- required: true
- auth_style: bearer
- header_name: authorization
-endpoints:
- - host: {TEST_SERVER_HOST}
- port: {port}
- path: /probe
- protocol: rest
- access: full
- enforcement: enforce
- request_body_credential_rewrite: true
- allowed_ips:
- - "10.0.0.0/8"
- - "172.0.0.0/8"
- - "192.168.0.0/16"
- - "fc00::/7"
-binaries: ["/**"]
-"#
- );
- file.write_all(profile.as_bytes())
- .map_err(|error| format!("write provider profile: {error}"))?;
- file.flush()
- .map_err(|error| format!("flush provider profile: {error}"))?;
- Ok(file)
-}
-
-fn write_policy_document(
- host: &str,
- port: u16,
- endpoint_options: &str,
- network_middlewares: &str,
-) -> Result {
- let mut file = NamedTempFile::new().map_err(|error| format!("create policy: {error}"))?;
- let policy = format!(
- r#"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only:
- - /usr
- - /lib
- - /proc
- - /dev/urandom
- - /app
- - /etc
- - /var/log
- read_write:
- - /sandbox
- - /tmp
- - /dev/null
-
-landlock:
- compatibility: best_effort
-
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-
-{network_middlewares}
-network_policies:
- proxy_egress_test:
- name: proxy_egress_test
- endpoints:
- - host: {host}
- port: {port}
-{endpoint_options}
-{PRIVATE_ALLOWED_IPS}
- binaries:
- - path: "/**"
-"#
- );
- file.write_all(policy.as_bytes())
- .map_err(|error| format!("write policy: {error}"))?;
- file.flush()
- .map_err(|error| format!("flush policy: {error}"))?;
- Ok(file)
-}
-
-fn write_policy(host: &str, port: u16, endpoint_options: &str) -> Result {
- write_policy_document(host, port, endpoint_options, "")
-}
-
-fn write_middleware_policy(
- host: &str,
- port: u16,
- endpoint_options: &str,
- on_error: &str,
-) -> Result {
- let network_middlewares = format!(
- r#"network_middlewares:
- regex-redactor:
- name: Redact API tokens
- middleware: openshell/regex
- order: 10
- config:
- mode: redact
- on_error: {on_error}
- endpoints:
- include: ["{host}"]
- exclude: []
-"#
- );
- write_policy_document(host, port, endpoint_options, &network_middlewares)
-}
-
-fn write_denied_policy() -> Result {
- let mut file = NamedTempFile::new().map_err(|error| format!("create policy: {error}"))?;
- let policy = r#"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only:
- - /usr
- - /lib
- - /proc
- - /dev/urandom
- - /app
- - /etc
- - /var/log
- read_write:
- - /sandbox
- - /tmp
- - /dev/null
-
-landlock:
- compatibility: best_effort
-
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-
-network_policies: {}
-"#;
- file.write_all(policy.as_bytes())
- .map_err(|error| format!("write policy: {error}"))?;
- file.flush()
- .map_err(|error| format!("flush policy: {error}"))?;
- Ok(file)
-}
-
-fn write_ambiguous_policy(host: &str, port: u16) -> Result {
- let mut file = NamedTempFile::new().map_err(|error| format!("create policy: {error}"))?;
- let policy = format!(
- r#"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log]
- read_write: [/sandbox, /tmp, /dev/null]
-
-landlock:
- compatibility: best_effort
-
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-
-network_policies:
- terminating:
- name: terminating
- endpoints:
- - host: {host}
- port: {port}
-{PRIVATE_ALLOWED_IPS}
- binaries:
- - path: "/**"
- passthrough:
- name: passthrough
- endpoints:
- - host: {host}
- port: {port}
- tls: skip
-{PRIVATE_ALLOWED_IPS}
- binaries:
- - path: "/**"
-"#
- );
- file.write_all(policy.as_bytes())
- .map_err(|error| format!("write policy: {error}"))?;
- file.flush()
- .map_err(|error| format!("flush policy: {error}"))?;
- Ok(file)
-}
-
-fn write_destination_denial_policy() -> Result {
- let mut file = NamedTempFile::new().map_err(|error| format!("create policy: {error}"))?;
- let policy = r#"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log]
- read_write: [/sandbox, /tmp, /dev/null]
-
-landlock:
- compatibility: best_effort
-
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-
-network_policies:
- destination_denials:
- name: destination_denials
- endpoints:
- - { host: 169.254.169.254, port: 80 }
- - { host: 127.0.0.1, port: 80 }
- - { host: 203.0.113.10, port: 6443 }
- - host: 203.0.113.10
- port: 8080
- allowed_ips: ["198.51.100.0/24"]
- binaries:
- - path: "/**"
-"#;
- file.write_all(policy.as_bytes())
- .map_err(|error| format!("write policy: {error}"))?;
- file.flush()
- .map_err(|error| format!("flush policy: {error}"))?;
- Ok(file)
-}
-
-fn write_ip_literal_success_policy(
- explicit_ip: &str,
- implicit_ip: &str,
- port: u16,
-) -> Result {
- let mut file = NamedTempFile::new().map_err(|error| format!("create policy: {error}"))?;
- let policy = format!(
- r#"version: 1
-
-filesystem_policy:
- include_workdir: true
- read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log]
- read_write: [/sandbox, /tmp, /dev/null]
-
-landlock:
- compatibility: best_effort
-
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-
-network_policies:
- destination_successes:
- name: destination_successes
- endpoints:
- - host: {ip}
- port: {port}
- allowed_ips: ["{explicit_ip}/32"]
- - host: {implicit_ip}
- port: {port}
- binaries:
- - path: "/**"
-"#,
- ip = explicit_ip,
- );
- file.write_all(policy.as_bytes())
- .map_err(|error| format!("write policy: {error}"))?;
- file.flush()
- .map_err(|error| format!("flush policy: {error}"))?;
- Ok(file)
-}
-
-fn policy_path(file: &NamedTempFile) -> String {
- file.path()
- .to_str()
- .expect("temporary policy path should be utf-8")
- .to_string()
-}
-
-async fn read_until(stream: &mut TcpStream, marker: &[u8]) -> io::Result> {
- let mut data = Vec::new();
- let mut buffer = [0_u8; 4096];
- loop {
- let read = stream.read(&mut buffer).await?;
- if read == 0 {
- return Ok(data);
- }
- data.extend_from_slice(&buffer[..read]);
- if data.windows(marker.len()).any(|window| window == marker) {
- return Ok(data);
- }
- }
-}
-
-fn header_end(bytes: &[u8]) -> Option {
- bytes
- .windows(4)
- .position(|window| window == b"\r\n\r\n")
- .map(|position| position + 4)
-}
-
-fn content_length(headers: &[u8]) -> io::Result {
- let text =
- std::str::from_utf8(headers).map_err(|error| Error::new(ErrorKind::InvalidData, error))?;
- Ok(text
- .lines()
- .find_map(|line| {
- let (name, value) = line.split_once(':')?;
- name.trim()
- .eq_ignore_ascii_case("content-length")
- .then(|| value.trim().parse::().ok())
- .flatten()
- })
- .unwrap_or(0))
-}
-
-async fn read_http_request(stream: &mut TcpStream) -> io::Result