diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml
index a2fade9dcc..340ee9273e 100644
--- a/.github/workflows/e2e-suites.yml
+++ b/.github/workflows/e2e-suites.yml
@@ -103,6 +103,7 @@ jobs:
{"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-keycloak","installer":"deb","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"ubuntu-docker-rootful-oidc","installer":"deb","family":"features","package":"oidc-auth","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"},
{"environment":"fedora-podman-rootless","installer":"rpm","family":"features","package":"oci-image","gateway":"openshell","runner":"ubuntu-24.04"},
@@ -111,7 +112,14 @@ 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":"service-exposure","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"fedora-podman-rootful","installer":"rpm","family":"features","package":"service-exposure","gateway":"openshell","runner":"ubuntu-24.04"},
+ {"environment":"fedora-podman-rootless","installer":"rpm","family":"features","package":"service-exposure","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":"fedora-podman-rootful-userns-default","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"},
diff --git a/TESTING.md b/TESTING.md
index ab4a397181..e24fe83874 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -324,7 +324,9 @@ service.
clients there from the variables. A missing variable fails the test; it
never skips it.
- **Documentation.** Document the variables in the fixture's module docs, so
- anyone can run the suite against their own deployment by setting them.
+ anyone can run the suite against their own deployment by setting them, and
+ add a row for each to the
+ [environment contract table](tests/support/README.md#environment-contract).
The Keycloak fixture is `tests/support/keycloak`. Run the suite that uses it
with:
@@ -335,6 +337,15 @@ nix run .#openshell-test-runner -- run \
--family features --package keycloak-provider-refresh
```
+The `oidc-auth` suite runs in `ubuntu-docker-rootful-oidc`, which adds a gateway
+that trusts the Keycloak realm and gives testkit an operator client certificate:
+
+```shell
+nix run .#openshell-test-runner -- run \
+ --environment ubuntu-docker-rootful-oidc --installer deb \
+ --family features --package oidc-auth
+```
+
A suite that needs setup beyond a container engine runs in a feature
environment, named `-`, such as `ubuntu-docker-rootful-keycloak`
or `ubuntu-docker-rootful-cdi`. `features` in `tests/tmachine/config.nix` lists
@@ -631,11 +642,27 @@ nix run .#openshell-test-runner -- run \
#### Gateway overrides in an environment
-An environment overrides gateway settings by writing the tables to change to
-`/etc/openshell-test/gateway-overrides.toml` in a playbook that runs before the
-installer. The file holds whole tables, such as `[openshell.gateway]` or
-`[openshell.drivers.podman]`, and is not a complete configuration. Each
-installer applies it to the gateway's own file:
+An environment overrides gateway settings with the `gateway_overrides` role,
+which takes a name and the tables to change, such as `[openshell.gateway]` or
+`[openshell.drivers.podman]`:
+
+```yaml
+- name: Push configuration to supervisors
+ ansible.builtin.include_role:
+ name: gateway_overrides
+ vars:
+ gateway_overrides_name: config-push
+ gateway_overrides_content: |
+ [openshell.gateway]
+ config_delivery_mode = "push"
+```
+
+The role writes each name as its own marked block in
+`/etc/openshell-test/gateway-overrides.toml`, so writers keep each other's
+settings, and `gateway_overrides_state: absent` removes a name's block.
+Two blocks must not declare the same table. Don't write the file
+directly. The file is not a complete configuration. Each installer applies it
+to the gateway's own file:
- `binaries` applies it to the `/etc/openshell/gateway.toml` it generates.
- `deb` and `rpm` apply it to the service user's
@@ -690,12 +717,29 @@ 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 test reaches a host server by
+`host.openshell.internal`, then uses the address that request arrived at, or
+the host's outbound address when it arrived on loopback from a host-network
+supervisor. The address 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
forwards a SIGTERM to `ssh`. The tests find those processes in `/proc`, so they
need a Linux test host. CI runs them on Docker rootful.
+The `service-exposure` feature suite (`tests/suites/features/service-exposure`)
+exposes a service in a sandbox and checks how the gateway forwards the client's
+`Authorization` header. The test sends requests to the gateway's endpoint with
+the service URL's host as the Host header, so the test machine doesn't resolve
+service hosts. CI runs it on Docker rootful and Podman rootful and rootless. The
+Helm chart turns gateway service routing off, so the K3s installers have no
+service URLs.
+
Run the VM-backed Rust CLI e2e suite:
```shell
diff --git a/e2e/rust/Cargo.lock b/e2e/rust/Cargo.lock
index 30897d9dee..3e8eb1e1cb 100644
--- a/e2e/rust/Cargo.lock
+++ b/e2e/rust/Cargo.lock
@@ -2430,7 +2430,6 @@ dependencies = [
"opentelemetry-proto",
"prost",
"rand 0.9.5",
- "rustls",
"serde",
"serde_json",
"serial_test",
@@ -2438,7 +2437,6 @@ dependencies = [
"sha2 0.10.9",
"tempfile",
"tokio",
- "tokio-rustls",
"tokio-stream",
"tonic",
"tonic-prost",
diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml
index 2efe8ed842..dac5036cd6 100644
--- a/e2e/rust/Cargo.toml
+++ b/e2e/rust/Cargo.toml
@@ -63,11 +63,6 @@ name = "policy_activation"
path = "tests/policy_activation.rs"
required-features = ["e2e-docker"]
-[[test]]
-name = "provider_files"
-path = "tests/provider_files.rs"
-required-features = ["e2e-docker"]
-
[[test]]
name = "oidc_pkce"
path = "tests/oidc_pkce.rs"
@@ -78,11 +73,6 @@ name = "vm_overlay"
path = "tests/vm_overlay.rs"
required-features = ["e2e-vm"]
-[[test]]
-name = "service_bearer_passthrough"
-path = "tests/service_bearer_passthrough.rs"
-required-features = ["e2e-docker"]
-
[[test]]
name = "rootfs_tar"
path = "tests/rootfs_tar.rs"
@@ -198,11 +188,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"
@@ -213,31 +198,11 @@ 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 = "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"
@@ -279,13 +244,11 @@ sha1 = "0.10"
sha2 = "0.10"
hex = "0.4"
rand = "0.9"
-rustls = { version = "0.23", default-features = false, features = ["std", "logging", "tls12"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_yml = { package = "noyalib", version = "0.0.53", default-features = false, features = ["std", "compat-serde-yaml"] }
tonic = { version = "0.14", features = ["transport"] }
tonic-prost = "0.14"
-tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "tls12"] }
tower = "0.5"
url = "2"
diff --git a/e2e/rust/e2e-podman.sh b/e2e/rust/e2e-podman.sh
index 3ba8cb2b2f..bd34cf2d77 100755
--- a/e2e/rust/e2e-podman.sh
+++ b/e2e/rust/e2e-podman.sh
@@ -22,17 +22,11 @@ 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 9293ce2fac..9d14092cb2 100644
--- a/e2e/rust/src/harness/sandbox.rs
+++ b/e2e/rust/src/harness/sandbox.rs
@@ -566,26 +566,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/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 a5d7c4849d..0000000000
--- a/e2e/rust/tests/forward_proxy_jsonrpc_l7.rs
+++ /dev/null
@@ -1,519 +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}
- protocol: rest
- enforcement: enforce
- access: read-write
- allowed_ips:
- - "10.0.0.0/8"
- - "172.0.0.0/8"
- - "192.168.0.0/16"
- - "fc00::/7"
- - 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 = {{
- # The broad REST endpoint still permits requests outside the RPC route.
- "rest_route_allowed": raw_http_status("rest_route_allowed", (
- f"POST /api/status HTTP/1.1\r\n"
- f"Host: {{HOST}}:{{PORT}}\r\n"
- f"Content-Length: 0\r\nConnection: close\r\n\r\n"
- ).encode()),
- # 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_unlisted_method_denied": post_jsonrpc("forward_unlisted_method_denied", "admin.delete"),
-
- # 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"),
- "raw_unlisted_method_denied": raw_jsonrpc_status("admin.delete", None, "raw_unlisted_method_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 [
- ("rest_route_allowed", 200),
- // 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_unlisted_method_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),
- ("raw_unlisted_method_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..98f6ec8159 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!(
@@ -412,157 +227,3 @@ printf 'RESPONSE_EOF\n'
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/oidc_pkce.rs b/e2e/rust/tests/oidc_pkce.rs
index 409d99bf30..461db3b287 100644
--- a/e2e/rust/tests/oidc_pkce.rs
+++ b/e2e/rust/tests/oidc_pkce.rs
@@ -10,912 +10,100 @@
//! callback and token exchange used by a real browser without requiring a GUI.
//! It logs in as the fixture identities and verifies standard-user and admin-only
//! actions against a live Docker- or Podman-backed gateway.
+//!
+//! The rest of this coverage lives in the `oidc-auth` testkit suite. These
+//! four checks duplicate it and are not ported.
-use std::collections::HashMap;
-use std::ffi::OsString;
-use std::fs::Permissions;
-use std::os::unix::fs::PermissionsExt;
-use std::path::Path;
-use std::process::{Output, Stdio};
-use std::time::{Duration, Instant};
-
-use base64::Engine as _;
-use openshell_e2e::harness::binary::openshell_cmd;
-use serde_json::Value;
-use serial_test::serial;
-use tokio::process::Command;
-use tokio::sync::Mutex;
-use url::Url;
-
-static SANDBOX_LIFECYCLE_LOCK: Mutex<()> = Mutex::const_new(());
-
-#[derive(Clone, Copy)]
-struct IdentityScenario {
- gateway_name: &'static str,
- username: &'static str,
- password: &'static str,
- expected_role: &'static str,
-}
-
-const ADMIN: IdentityScenario = IdentityScenario {
- gateway_name: "oidc-pkce-admin",
- username: "admin@test",
- password: "admin",
- expected_role: "openshell-admin",
-};
-
-const USER: IdentityScenario = IdentityScenario {
- gateway_name: "oidc-pkce-user",
- username: "user@test",
- password: "user",
- expected_role: "openshell-user",
-};
-
-const USER_B: IdentityScenario = IdentityScenario {
- gateway_name: "oidc-pkce-user-b",
- username: "user-b@test",
- password: "user-b",
- expected_role: "openshell-user",
-};
-
-struct LoginSession {
- config_home: tempfile::TempDir,
- identity: IdentityScenario,
- subject: String,
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn admin_can_list_sandboxes() {
- let session = login_identity(ADMIN).await;
- assert_allowed(
- &session,
- &["sandbox", "list", "--output", "json"],
- "list sandboxes",
- )
- .await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn user_can_report_gateway_validated_identity() {
- let session = login_identity(USER).await;
- let output = assert_allowed(
- &session,
- &["whoami", "--output", "json"],
- "report current identity",
- )
- .await;
- let stdout = String::from_utf8(output.stdout).expect("whoami output should be UTF-8");
- let json_start = stdout.find('{').expect("whoami output should contain JSON");
- let json_end = stdout
- .rfind('}')
- .expect("whoami output should contain a complete JSON object");
- let identity: Value = serde_json::from_str(&stdout[json_start..=json_end])
- .expect("whoami --output json should return JSON on stdout");
-
- assert_eq!(identity["subject"], session.subject);
- assert_eq!(identity["identity_provider"], "oidc");
- assert!(
- identity["roles"]
- .as_array()
- .is_some_and(|roles| roles.iter().any(|role| role == USER.expected_role)),
- "whoami should report the configured user role: {identity}"
- );
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn user_can_list_sandboxes() {
- const WORKSPACE: &str = "oidc-user-list-sb";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "user").await;
- assert_workspace_allowed(
- &user,
- WORKSPACE,
- &["sandbox", "list", "--output", "json"],
- "list sandboxes",
- )
- .await;
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn admin_can_create_sandbox() {
- let session = login_identity(ADMIN).await;
- let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await;
- assert_can_create_sandbox(&session, "default", "oidc-admin-create").await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn user_can_create_sandbox() {
- const WORKSPACE: &str = "oidc-user-create";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "user").await;
- let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await;
- assert_can_create_sandbox(&user, WORKSPACE, "oidc-user-create").await;
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-/// Workspace users must be able to resolve a provider profile when naming a
-/// provider with `--provider`, without requiring Platform Admin access.
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn user_can_resolve_provider_profile_for_sandbox() {
- const WORKSPACE: &str = "oidc-named-provider";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "user").await;
- let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await;
-
- // `claude-code` names no existing provider, so the CLI has to look up the
- // profile of that id before it can auto-create one. The lane imported the
- // example profiles at platform scope; reaching them from a workspace is
- // what this test guards.
- let output = run_workspace_cli(
- &user,
- WORKSPACE,
- &[
- "sandbox",
- "create",
- "--name",
- "oidc-named-provider",
- "--no-tty",
- "--provider",
- "claude-code",
- ],
- )
- .await;
- let combined = combined_output(&output);
-
- // The provider cannot be auto-created without a terminal to confirm at,
- // so creation stops there. That error proves the profile lookup
- // succeeded; a permission error would mean the workspace user was gated
- // out of the catalog.
- assert!(
- !combined.to_ascii_lowercase().contains("platform admin"),
- "workspace user hit a platform-admin gate while resolving a provider profile:\n{combined}"
- );
- assert!(
- combined.contains("missing required provider"),
- "expected missing-provider error for non-interactive session, got:\n{combined}"
- );
-
- let _ = run_workspace_cli(
- &user,
- WORKSPACE,
- &["sandbox", "delete", "oidc-named-provider"],
- )
- .await;
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn admin_can_delete_sandbox() {
- let session = login_identity(ADMIN).await;
- let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await;
- assert_can_delete_sandbox(&session, "default", "oidc-admin-delete").await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn user_can_delete_sandbox() {
- const WORKSPACE: &str = "oidc-user-delete";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "user").await;
- let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await;
- assert_can_delete_sandbox(&user, WORKSPACE, "oidc-user-delete").await;
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn admin_can_inspect_gateway() {
- let session = login_identity(ADMIN).await;
- let output = assert_allowed(&session, &["gateway", "info"], "inspect gateway info").await;
- let info = combined_output(&output);
- let expected_driver =
- std::env::var("OPENSHELL_E2E_DRIVER").expect("OIDC E2E requires OPENSHELL_E2E_DRIVER");
- assert!(
- info.to_ascii_lowercase()
- .contains(&expected_driver.to_ascii_lowercase()),
- "gateway info should report the {expected_driver} compute driver: {info}"
- );
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn user_cannot_inspect_gateway() {
- let session = login_identity(USER).await;
- let output = run_session_cli(&session, &["gateway", "info"]).await;
- let denied = combined_output(&output);
- assert!(
- !output.status.success(),
- "user accessed gateway info:\n{denied}"
- );
- assert!(
- denied.contains("requires admin privileges"),
- "gateway-info denial should explain that admin privileges are required:\n{denied}"
- );
- assert_admin_role_denial(&output, "inspect gateway info");
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn admin_can_list_providers() {
- let session = login_identity(ADMIN).await;
- assert_allowed(
- &session,
- &["provider", "list", "--output", "json"],
- "list providers",
- )
- .await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn user_can_list_providers() {
- const WORKSPACE: &str = "oidc-user-list-pr";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "user").await;
- assert_workspace_allowed(
- &user,
- WORKSPACE,
- &["provider", "list", "--output", "json"],
- "list providers",
- )
- .await;
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn admin_can_manage_provider() {
- const PROVIDER: &str = "oidc-pkce-admin-provider";
- let session = login_identity(ADMIN).await;
-
- assert_allowed(
- &session,
- &[
- "provider",
- "create",
- "--name",
- PROVIDER,
- "--type",
- "openai",
- "--credential",
- "OPENAI_API_KEY=e2e-test-value",
- ],
- "create a provider",
- )
- .await;
-
- let get = assert_allowed(&session, &["provider", "get", PROVIDER], "read a provider").await;
- assert!(
- combined_output(&get).contains(PROVIDER),
- "provider get output should contain the created provider:\n{}",
- combined_output(&get)
- );
-
- assert_allowed(
- &session,
- &["provider", "delete", PROVIDER],
- "delete a provider",
- )
- .await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn user_cannot_create_provider() {
- const WORKSPACE: &str = "oidc-user-no-create";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "user").await;
- let output = run_workspace_cli(
- &user,
- WORKSPACE,
- &[
- "provider",
- "create",
- "--name",
- "oidc-pkce-user-provider",
- "--type",
- "openai",
- "--credential",
- "OPENAI_API_KEY=e2e-test-value",
- ],
- )
- .await;
- assert_workspace_admin_denial(&output, &user, WORKSPACE, "create a provider");
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn user_cannot_delete_provider() {
- const PROVIDER: &str = "oidc-pkce-user-delete-target";
- const WORKSPACE: &str = "oidc-user-no-delete";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "user").await;
- assert_workspace_allowed(
- &admin,
- WORKSPACE,
- &[
- "provider",
- "create",
- "--name",
- PROVIDER,
- "--type",
- "openai",
- "--credential",
- "OPENAI_API_KEY=e2e-test-value",
- ],
- "create the provider deletion target",
- )
- .await;
-
- let denied = run_workspace_cli(&user, WORKSPACE, &["provider", "delete", PROVIDER]).await;
- assert_workspace_admin_denial(&denied, &user, WORKSPACE, "delete a provider");
-
- assert_workspace_allowed(
- &admin,
- WORKSPACE,
- &["provider", "delete", PROVIDER],
- "clean up the provider deletion target",
- )
- .await;
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn admin_can_create_workspace() {
- const WORKSPACE: &str = "oidc-admin-create";
- let admin = login_identity(ADMIN).await;
- let _ = run_session_cli(&admin, &["workspace", "delete", WORKSPACE]).await;
- assert_allowed(
- &admin,
- &["workspace", "create", "--name", WORKSPACE],
- "create a workspace",
- )
- .await;
- let get = assert_allowed(
- &admin,
- &["workspace", "get", WORKSPACE],
- "read the created workspace",
- )
- .await;
- assert!(combined_output(&get).contains(WORKSPACE));
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn user_cannot_create_workspace() {
- let user = login_identity(USER).await;
- let denied = run_session_cli(
- &user,
- &["workspace", "create", "--name", "oidc-user-denied"],
- )
- .await;
- assert_admin_role_denial(&denied, "create a workspace");
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn admin_can_delete_workspace() {
- const WORKSPACE: &str = "oidc-admin-delete";
- let admin = login_identity(ADMIN).await;
- let _ = run_session_cli(&admin, &["workspace", "delete", WORKSPACE]).await;
- assert_allowed(
- &admin,
- &["workspace", "create", "--name", WORKSPACE],
- "create a workspace deletion target",
- )
- .await;
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn user_cannot_delete_workspace() {
- const WORKSPACE: &str = "oidc-user-del-deny";
- let admin = login_identity(ADMIN).await;
- let user = login_identity(USER).await;
- let _ = run_session_cli(&admin, &["workspace", "delete", WORKSPACE]).await;
- assert_allowed(
- &admin,
- &["workspace", "create", "--name", WORKSPACE],
- "create a workspace deletion target",
- )
- .await;
- let denied = run_session_cli(&user, &["workspace", "delete", WORKSPACE]).await;
- assert_admin_role_denial(&denied, "delete a workspace");
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_user_can_read_workspace() {
- const WORKSPACE: &str = "oidc-ws-user-read";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "user").await;
-
- let get = assert_allowed(
- &user,
- &["workspace", "get", WORKSPACE],
- "read a member workspace",
- )
- .await;
- let list = assert_allowed(
- &user,
- &["workspace", "list", "--output", "json"],
- "list member workspaces",
- )
- .await;
- let members = assert_allowed(
- &user,
- &["workspace", "member", "list", "--workspace", WORKSPACE],
- "list workspace members",
- )
- .await;
- assert!(combined_output(&get).contains(WORKSPACE));
- assert!(combined_output(&list).contains(WORKSPACE));
- assert!(combined_output(&members).contains(&user.subject));
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_user_cannot_manage_members() {
- const WORKSPACE: &str = "oidc-ws-user-deny";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "user").await;
- let denied = run_session_cli(
- &user,
- &[
- "workspace",
- "member",
- "add",
- "--workspace",
- WORKSPACE,
- "--subject",
- "oidc-fake-member",
- "--role",
- "user",
- ],
- )
- .await;
- assert_workspace_admin_denial(&denied, &user, WORKSPACE, "add a workspace member");
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_can_read_workspace() {
- const WORKSPACE: &str = "oidc-wsa-read";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "admin").await;
-
- let get = assert_allowed(
- &user,
- &["workspace", "get", WORKSPACE],
- "read an administered workspace",
- )
- .await;
- assert!(combined_output(&get).contains(WORKSPACE));
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_can_create_sandbox() {
- const WORKSPACE: &str = "oidc-wsa-create-sb";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "admin").await;
- let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await;
- assert_can_create_sandbox(&user, WORKSPACE, "oidc-wsa-create").await;
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_can_delete_sandbox() {
- const WORKSPACE: &str = "oidc-wsa-delete-sb";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "admin").await;
- let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await;
- assert_can_delete_sandbox(&user, WORKSPACE, "oidc-wsa-delete").await;
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_can_create_provider() {
- const WORKSPACE: &str = "oidc-wsa-create-pr";
- const PROVIDER: &str = "oidc-wsa-create-provider";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "admin").await;
- assert_workspace_allowed(
- &user,
- WORKSPACE,
- &[
- "provider",
- "create",
- "--name",
- PROVIDER,
- "--type",
- "openai",
- "--credential",
- "OPENAI_API_KEY=e2e-test-value",
- ],
- "create a provider as workspace admin",
- )
- .await;
-
- assert_workspace_allowed(
- &admin,
- WORKSPACE,
- &["provider", "delete", PROVIDER],
- "clean up the provider created by a workspace admin",
- )
- .await;
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_can_delete_provider() {
- const WORKSPACE: &str = "oidc-wsa-delete-pr";
- const PROVIDER: &str = "oidc-wsa-delete-provider";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "admin").await;
- assert_workspace_allowed(
- &admin,
- WORKSPACE,
- &[
- "provider",
- "create",
- "--name",
- PROVIDER,
- "--type",
- "openai",
- "--credential",
- "OPENAI_API_KEY=e2e-test-value",
- ],
- "create the provider deletion target",
- )
- .await;
- assert_workspace_allowed(
- &user,
- WORKSPACE,
- &["provider", "delete", PROVIDER],
- "delete a provider as workspace admin",
- )
- .await;
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_can_add_user_member() {
- const WORKSPACE: &str = "oidc-wsa-add-user";
- let workspace_admin = login_identity(USER).await;
- let user = login_identity(USER_B).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &workspace_admin, WORKSPACE, "admin").await;
-
- assert_allowed(
- &workspace_admin,
- &[
- "workspace",
- "member",
- "add",
- "--workspace",
- WORKSPACE,
- "--subject",
- &user.subject,
- "--role",
- "user",
- ],
- "add a standard workspace member",
- )
- .await;
- let members = assert_allowed(
- &workspace_admin,
- &["workspace", "member", "list", "--workspace", WORKSPACE],
- "list workspace members after adding one",
- )
- .await;
- assert!(combined_output(&members).contains(&user.subject));
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_can_remove_user_member() {
- const WORKSPACE: &str = "oidc-wsa-rm-user";
- let workspace_admin = login_identity(USER).await;
- let user = login_identity(USER_B).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &workspace_admin, WORKSPACE, "admin").await;
- assert_allowed(
- &admin,
- &[
- "workspace",
- "member",
- "add",
- "--workspace",
- WORKSPACE,
- "--subject",
- &user.subject,
- "--role",
- "user",
- ],
- "create the workspace member removal target",
- )
- .await;
-
- assert_allowed(
- &workspace_admin,
- &[
- "workspace",
- "member",
- "remove",
- "--workspace",
- WORKSPACE,
- "--subject",
- &user.subject,
- ],
- "remove a standard workspace member",
- )
- .await;
- let denied = run_session_cli(&user, &["workspace", "get", WORKSPACE]).await;
- assert_non_member_denial(&denied, "read a workspace after removal by its admin");
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_cannot_grant_admin() {
- const WORKSPACE: &str = "oidc-ws-admin-deny";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "admin").await;
- let denied = run_session_cli(
- &user,
- &[
- "workspace",
- "member",
- "add",
- "--workspace",
- WORKSPACE,
- "--subject",
- "oidc-fake-admin",
- "--role",
- "admin",
- ],
- )
- .await;
- assert_platform_admin_denial(&denied, "grant workspace admin");
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_cannot_create_workspace() {
- const WORKSPACE: &str = "oidc-wsa-no-create";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "admin").await;
-
- let denied =
- run_session_cli(&user, &["workspace", "create", "--name", "oidc-wsa-denied"]).await;
- assert_admin_role_denial(&denied, "create a workspace as workspace admin");
- delete_workspace(&admin, WORKSPACE).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_cannot_delete_workspace() {
- const WORKSPACE: &str = "oidc-wsa-no-delete";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "admin").await;
+use std::collections::HashMap;
+use std::ffi::OsString;
+use std::fs::Permissions;
+use std::os::unix::fs::PermissionsExt;
+use std::path::Path;
+use std::process::{Output, Stdio};
+use std::time::{Duration, Instant};
- let denied = run_session_cli(&user, &["workspace", "delete", WORKSPACE]).await;
- assert_admin_role_denial(&denied, "delete an administered workspace");
- delete_workspace(&admin, WORKSPACE).await;
-}
+use base64::Engine as _;
+use openshell_e2e::harness::binary::openshell_cmd;
+use serde_json::Value;
+use serial_test::serial;
+use tokio::process::Command;
+use tokio::sync::Mutex;
+use url::Url;
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_cannot_inspect_gateway() {
- const WORKSPACE: &str = "oidc-wsa-no-gw-info";
- let user = login_identity(USER).await;
- let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "admin").await;
+static SANDBOX_LIFECYCLE_LOCK: Mutex<()> = Mutex::const_new(());
- let denied = run_workspace_cli(&user, WORKSPACE, &["gateway", "info"]).await;
- assert_admin_role_denial(&denied, "inspect gateway info as workspace admin");
- delete_workspace(&admin, WORKSPACE).await;
+#[derive(Clone, Copy)]
+struct IdentityScenario {
+ gateway_name: &'static str,
+ username: &'static str,
+ password: &'static str,
+ expected_role: &'static str,
}
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_cannot_read_another_workspace() {
- const WORKSPACE_A: &str = "oidc-wsa-xread-a";
- const WORKSPACE_B: &str = "oidc-wsa-xread-b";
- let (admin, workspace_admin, _user_b) =
- prepare_isolated_workspaces_with_admin(WORKSPACE_A, WORKSPACE_B).await;
-
- let denied = run_session_cli(&workspace_admin, &["workspace", "get", WORKSPACE_B]).await;
- assert_non_member_denial(&denied, "read another workspace as workspace admin");
-
- delete_workspace(&admin, WORKSPACE_B).await;
- delete_workspace(&admin, WORKSPACE_A).await;
-}
+const ADMIN: IdentityScenario = IdentityScenario {
+ gateway_name: "oidc-pkce-admin",
+ username: "admin@test",
+ password: "admin",
+ expected_role: "openshell-admin",
+};
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_admin_cannot_manage_another_workspace_members() {
- const WORKSPACE_A: &str = "oidc-wsa-xmem-a";
- const WORKSPACE_B: &str = "oidc-wsa-xmem-b";
- let (admin, workspace_admin, _user_b) =
- prepare_isolated_workspaces_with_admin(WORKSPACE_A, WORKSPACE_B).await;
+const USER: IdentityScenario = IdentityScenario {
+ gateway_name: "oidc-pkce-user",
+ username: "user@test",
+ password: "user",
+ expected_role: "openshell-user",
+};
- let denied = run_session_cli(
- &workspace_admin,
- &[
- "workspace",
- "member",
- "add",
- "--workspace",
- WORKSPACE_B,
- "--subject",
- "oidc-fake-member",
- "--role",
- "user",
- ],
- )
- .await;
- assert_non_member_denial(
- &denied,
- "manage another workspace's members as workspace admin",
- );
+const USER_B: IdentityScenario = IdentityScenario {
+ gateway_name: "oidc-pkce-user-b",
+ username: "user-b@test",
+ password: "user-b",
+ expected_role: "openshell-user",
+};
- delete_workspace(&admin, WORKSPACE_B).await;
- delete_workspace(&admin, WORKSPACE_A).await;
+struct LoginSession {
+ config_home: tempfile::TempDir,
+ identity: IdentityScenario,
+ subject: String,
}
#[tokio::test]
#[serial(oidc_pkce)]
-async fn workspace_admin_cannot_manage_another_workspace_providers() {
- const WORKSPACE_A: &str = "oidc-wsa-xprov-a";
- const WORKSPACE_B: &str = "oidc-wsa-xprov-b";
- const PROVIDER: &str = "oidc-wsa-xprovider";
- let (admin, workspace_admin, _user_b) =
- prepare_isolated_workspaces_with_admin(WORKSPACE_A, WORKSPACE_B).await;
-
- let denied = run_workspace_cli(
- &workspace_admin,
- WORKSPACE_B,
- &[
- "provider",
- "create",
- "--name",
- PROVIDER,
- "--type",
- "openai",
- "--credential",
- "OPENAI_API_KEY=e2e-test-value",
- ],
- )
- .await;
- let diagnostic = combined_output(&denied);
- let compact: String = diagnostic
- .chars()
- .filter(|character| !character.is_whitespace() && *character != '│')
- .collect();
- // Profile lookup redacts backend diagnostics. Check the permission code and
- // safe recovery guidance without requiring the server's membership details.
- assert!(
- !denied.status.success()
- && compact.contains("PERMISSION_DENIED")
- && compact.contains("verifyworkspacemembershipandrequiredpermissions"),
- "cross-workspace provider creation did not report a safe permission denial:\n{diagnostic}"
- );
- assert!(!diagnostic.contains("e2e-test-value"));
-
- // Query with an independent authorized identity so a failed command alone
- // cannot hide a provider created before the denial was returned.
- let listed = assert_workspace_allowed(
+async fn admin_can_delete_workspace() {
+ const WORKSPACE: &str = "oidc-admin-delete";
+ let admin = login_identity(ADMIN).await;
+ let _ = run_session_cli(&admin, &["workspace", "delete", WORKSPACE]).await;
+ assert_allowed(
&admin,
- WORKSPACE_B,
- &["provider", "list", "--output", "json"],
- "verify denied creation left the target workspace empty",
+ &["workspace", "create", "--name", WORKSPACE],
+ "create a workspace deletion target",
)
.await;
- // CLI startup diagnostics may precede the JSON object on stdout.
- let stdout = String::from_utf8(listed.stdout).expect("provider list output should be UTF-8");
- let json_start = stdout
- .find('{')
- .expect("provider list output should contain JSON");
- let json_end = stdout
- .rfind('}')
- .expect("provider list output should contain a complete JSON object");
- let listing: Value = serde_json::from_str(&stdout[json_start..=json_end])
- .expect("provider list --output json should return JSON on stdout");
- assert_eq!(
- listing["next_page_token"], "",
- "provider listing is incomplete"
- );
- assert!(
- listing["providers"]
- .as_array()
- .expect("provider collection")
- .is_empty(),
- "denied creation added a provider to the isolated target workspace"
- );
-
- delete_workspace(&admin, WORKSPACE_B).await;
- delete_workspace(&admin, WORKSPACE_A).await;
+ delete_workspace(&admin, WORKSPACE).await;
}
#[tokio::test]
#[serial(oidc_pkce)]
-async fn membership_removal_revokes_workspace_access() {
- const WORKSPACE: &str = "oidc-ws-revoke";
+async fn workspace_admin_can_create_sandbox() {
+ const WORKSPACE: &str = "oidc-wsa-create-sb";
let user = login_identity(USER).await;
let admin = login_identity(ADMIN).await;
- prepare_workspace(&admin, &user, WORKSPACE, "user").await;
- assert_allowed(
- &admin,
- &[
- "workspace",
- "member",
- "remove",
- "--workspace",
- WORKSPACE,
- "--subject",
- &user.subject,
- ],
- "remove a workspace member",
- )
- .await;
- let denied = run_session_cli(&user, &["workspace", "get", WORKSPACE]).await;
- assert_non_member_denial(&denied, "read a workspace after membership removal");
+ prepare_workspace(&admin, &user, WORKSPACE, "admin").await;
+ let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await;
+ assert_can_create_sandbox(&user, WORKSPACE, "oidc-wsa-create").await;
delete_workspace(&admin, WORKSPACE).await;
}
#[tokio::test]
#[serial(oidc_pkce)]
-async fn workspace_user_cannot_read_another_users_workspace() {
- const WORKSPACE_A: &str = "oidc-xread-a";
- const WORKSPACE_B: &str = "oidc-xread-b";
- let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await;
-
- let denied = run_session_cli(&user_a, &["workspace", "get", WORKSPACE_B]).await;
- assert_non_member_denial(&denied, "read another user's workspace");
-
- delete_workspace(&admin, WORKSPACE_B).await;
- delete_workspace(&admin, WORKSPACE_A).await;
+async fn workspace_admin_can_delete_sandbox() {
+ const WORKSPACE: &str = "oidc-wsa-delete-sb";
+ let user = login_identity(USER).await;
+ let admin = login_identity(ADMIN).await;
+ prepare_workspace(&admin, &user, WORKSPACE, "admin").await;
+ let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await;
+ assert_can_delete_sandbox(&user, WORKSPACE, "oidc-wsa-delete").await;
+ delete_workspace(&admin, WORKSPACE).await;
}
#[tokio::test]
@@ -932,117 +120,6 @@ async fn second_workspace_user_cannot_read_first_users_workspace() {
delete_workspace(&admin, WORKSPACE_A).await;
}
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_list_hides_another_users_workspace() {
- const WORKSPACE_A: &str = "oidc-xlist-a";
- const WORKSPACE_B: &str = "oidc-xlist-b";
- let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await;
-
- let listed = assert_allowed(
- &user_a,
- &["workspace", "list", "--output", "json"],
- "list visible workspaces",
- )
- .await;
- let output = combined_output(&listed);
- assert!(
- output.contains(WORKSPACE_A),
- "workspace list should contain the caller's workspace:\n{output}"
- );
- assert!(
- !output.contains(WORKSPACE_B),
- "workspace list exposed another user's workspace:\n{output}"
- );
-
- delete_workspace(&admin, WORKSPACE_B).await;
- delete_workspace(&admin, WORKSPACE_A).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_user_cannot_list_another_workspace_sandboxes() {
- const WORKSPACE_A: &str = "oidc-xsbox-a";
- const WORKSPACE_B: &str = "oidc-xsbox-b";
- let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await;
-
- let denied = run_workspace_cli(
- &user_a,
- WORKSPACE_B,
- &["sandbox", "list", "--output", "json"],
- )
- .await;
- assert_non_member_denial(&denied, "list another workspace's sandboxes");
-
- delete_workspace(&admin, WORKSPACE_B).await;
- delete_workspace(&admin, WORKSPACE_A).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_user_cannot_create_sandbox_in_another_workspace() {
- const WORKSPACE_A: &str = "oidc-xcreate-a";
- const WORKSPACE_B: &str = "oidc-xcreate-b";
- let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await;
-
- let denied = run_workspace_cli(
- &user_a,
- WORKSPACE_B,
- &[
- "sandbox",
- "create",
- "--name",
- "oidc-xcreate-denied",
- "--no-tty",
- "--",
- "echo",
- "denied",
- ],
- )
- .await;
- assert_non_member_denial(&denied, "create a sandbox in another workspace");
-
- delete_workspace(&admin, WORKSPACE_B).await;
- delete_workspace(&admin, WORKSPACE_A).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_user_cannot_list_another_workspace_providers() {
- const WORKSPACE_A: &str = "oidc-xprov-a";
- const WORKSPACE_B: &str = "oidc-xprov-b";
- let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await;
-
- let denied = run_workspace_cli(
- &user_a,
- WORKSPACE_B,
- &["provider", "list", "--output", "json"],
- )
- .await;
- assert_non_member_denial(&denied, "list another workspace's providers");
-
- delete_workspace(&admin, WORKSPACE_B).await;
- delete_workspace(&admin, WORKSPACE_A).await;
-}
-
-#[tokio::test]
-#[serial(oidc_pkce)]
-async fn workspace_user_cannot_list_another_workspace_members() {
- const WORKSPACE_A: &str = "oidc-xmember-a";
- const WORKSPACE_B: &str = "oidc-xmember-b";
- let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await;
-
- let denied = run_session_cli(
- &user_a,
- &["workspace", "member", "list", "--workspace", WORKSPACE_B],
- )
- .await;
- assert_non_member_denial(&denied, "list another workspace's members");
-
- delete_workspace(&admin, WORKSPACE_B).await;
- delete_workspace(&admin, WORKSPACE_A).await;
-}
-
async fn login_identity(identity: IdentityScenario) -> LoginSession {
let issuer = std::env::var("OPENSHELL_E2E_OIDC_ISSUER")
.unwrap_or_else(|_| "http://localhost:8180/realms/openshell".to_string());
@@ -1365,22 +442,6 @@ async fn assert_allowed(session: &LoginSession, args: &[&str], action: &str) ->
output
}
-async fn assert_workspace_allowed(
- session: &LoginSession,
- workspace: &str,
- args: &[&str],
- action: &str,
-) -> Output {
- let output = run_workspace_cli(session, workspace, args).await;
- assert!(
- output.status.success(),
- "{} should be allowed to {action} in workspace {workspace}:\n{}",
- session.identity.username,
- combined_output(&output)
- );
- output
-}
-
async fn prepare_workspace(
admin: &LoginSession,
member: &LoginSession,
@@ -1424,18 +485,6 @@ async fn prepare_isolated_workspaces(
(admin, user_a, user_b)
}
-async fn prepare_isolated_workspaces_with_admin(
- workspace_a: &str,
- workspace_b: &str,
-) -> (LoginSession, LoginSession, LoginSession) {
- let admin = login_identity(ADMIN).await;
- let workspace_admin = login_identity(USER).await;
- let user_b = login_identity(USER_B).await;
- prepare_workspace(&admin, &workspace_admin, workspace_a, "admin").await;
- prepare_workspace(&admin, &user_b, workspace_b, "user").await;
- (admin, workspace_admin, user_b)
-}
-
async fn delete_workspace(admin: &LoginSession, workspace: &str) {
for attempt in 0..30 {
let output = run_session_cli(admin, &["workspace", "delete", workspace]).await;
@@ -1590,55 +639,6 @@ async fn run_workspace_cli(session: &LoginSession, workspace: &str, args: &[&str
run_cli(session.config_home.path(), &command_args).await
}
-fn assert_admin_role_denial(output: &Output, action: &str) {
- let denied = combined_output(output);
- let compact_denial: String = denied
- .chars()
- .filter(|character| !character.is_whitespace() && *character != '│')
- .collect();
- assert!(
- !output.status.success() && compact_denial.contains("openshell-admin"),
- "standard user unexpectedly authorized to {action}, or denial omitted the admin role:\n{denied}"
- );
-}
-
-fn assert_workspace_admin_denial(
- output: &Output,
- session: &LoginSession,
- workspace: &str,
- action: &str,
-) {
- let denied = combined_output(output);
- let remediation = format!(
- "openshell workspace member add --workspace '{workspace}' --subject '{}' --role admin",
- session.subject
- );
- let compact_denial: String = denied
- .chars()
- .filter(|character| !character.is_whitespace() && *character != '│')
- .collect();
- let compact_remediation: String = remediation
- .chars()
- .filter(|character| !character.is_whitespace())
- .collect();
- assert!(
- !output.status.success()
- && compact_denial
- .to_ascii_lowercase()
- .contains("workspacerole'admin'")
- && compact_denial.contains(&compact_remediation),
- "workspace user unexpectedly authorized to {action}, or denial omitted the admin remediation command:\n{denied}"
- );
-}
-
-fn assert_platform_admin_denial(output: &Output, action: &str) {
- let denied = combined_output(output);
- assert!(
- !output.status.success() && denied.to_ascii_lowercase().contains("platform admin"),
- "non-platform-admin unexpectedly authorized to {action}, or denial omitted the required platform role:\n{denied}"
- );
-}
-
fn assert_non_member_denial(output: &Output, action: &str) {
let denied = combined_output(output);
let compact_denial: String = denied
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/provider_auto_create.rs b/e2e/rust/tests/provider_auto_create.rs
deleted file mode 100644
index 2c8828deaf..0000000000
--- a/e2e/rust/tests/provider_auto_create.rs
+++ /dev/null
@@ -1,197 +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: `--provider ` auto-creates a provider from local credentials.
-//!
-//! When `--provider claude-code` is passed and no provider named "claude-code" exists,
-//! the CLI should discover `ANTHROPIC_API_KEY` from the local environment,
-//! auto-create a provider, and inject a supervisor-managed placeholder into the
-//! sandbox child process environment.
-//!
-//! The sandbox command (`printenv ANTHROPIC_API_KEY`) verifies that the
-//! placeholder made it all the way through to the sandbox process environment.
-//!
-//! Prerequisites:
-//! - A running openshell gateway (`mise run gateway:docker`)
-//! - The `openshell` binary (built automatically from the workspace)
-
-use std::process::Stdio;
-use std::sync::Mutex;
-
-use openshell_e2e::harness::binary::openshell_cmd;
-use openshell_e2e::harness::output::{extract_field, strip_ansi};
-#[cfg(feature = "e2e-local-container-driver")]
-use openshell_e2e::harness::sandbox::E2E_WORKLOAD_IMAGE;
-
-const TEST_API_KEY: &str = "sk-e2e-auto-provider-test-key";
-static CLAUDE_PROVIDER_LOCK: Mutex<()> = Mutex::new(());
-
-fn contains_placeholder_for_env_key(output: &str, key: &str) -> bool {
- let legacy = format!("openshell:resolve:env:{key}");
- let revision_prefix = "openshell:resolve:env:v";
- let revision_suffix = format!("_{key}");
- output.split_whitespace().any(|token| {
- token == legacy || (token.starts_with(revision_prefix) && token.ends_with(&revision_suffix))
- })
-}
-
-/// Helper: delete a provider by name, ignoring errors.
-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;
-}
-
-/// Helper: check whether a provider already exists.
-async fn provider_exists(name: &str) -> bool {
- let mut cmd = openshell_cmd();
- cmd.arg("provider")
- .arg("get")
- .arg(name)
- .stdout(Stdio::null())
- .stderr(Stdio::null());
- cmd.status().await.is_ok_and(|status| status.success())
-}
-
-/// Helper: delete a sandbox by name, ignoring errors.
-async fn delete_sandbox(name: &str) {
- let mut cmd = openshell_cmd();
- cmd.arg("sandbox")
- .arg("delete")
- .arg(name)
- .stdout(Stdio::null())
- .stderr(Stdio::null());
- let _ = cmd.status().await;
-}
-
-/// `--provider claude-code --auto-providers` with `ANTHROPIC_API_KEY` set should
-/// auto-create a "claude-code" provider and inject a placeholder into the sandbox.
-#[tokio::test]
-async fn auto_created_provider_credential_available_in_sandbox() {
- let _provider_lock = CLAUDE_PROVIDER_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
-
- if provider_exists("claude-code").await {
- eprintln!("Skipping test: existing provider 'claude-code' would make shared state unsafe");
- return;
- }
-
- // Clean up any leftover from a previous run.
- delete_provider("claude-code").await;
-
- // This test only reads the injected environment placeholder. Do not inherit
- // the published image's network rules, which may be incompatible with the
- // attached credential provider's startup validation.
- let policy = tempfile::NamedTempFile::new().expect("create provider test policy");
- std::fs::write(
- policy.path(),
- r"version: 1
-filesystem_policy:
- include_workdir: true
- read_only: [/usr, /lib, /etc, /proc]
- read_write: [/sandbox, /tmp, /dev/null]
-landlock:
- compatibility: best_effort
-process:
- run_as_user: sandbox
- run_as_group: sandbox
-network_policies: {}
-",
- )
- .expect("write provider test policy");
-
- // Create a sandbox that prints the ANTHROPIC_API_KEY env var.
- // --auto-providers skips the interactive prompt.
- let mut cmd = openshell_cmd();
- cmd.arg("sandbox").arg("create");
- #[cfg(feature = "e2e-local-container-driver")]
- cmd.arg("--from").arg(E2E_WORKLOAD_IMAGE);
- cmd.arg("--detach")
- .arg("--policy")
- .arg(policy.path())
- .arg("--provider")
- .arg("claude-code")
- .arg("--auto-providers")
- .args(["--", "sh", "-c", "exec sleep infinity"])
- .env("ANTHROPIC_API_KEY", TEST_API_KEY)
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
-
- let output = cmd
- .output()
- .await
- .expect("failed to spawn openshell sandbox create");
-
- 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}");
- let clean = strip_ansi(&combined);
-
- // Parse sandbox name for cleanup.
- let sandbox_name = extract_field(&combined, "Created sandbox");
- let exec_output = if let Some(ref name) = sandbox_name {
- let mut exec_cmd = openshell_cmd();
- exec_cmd
- .args([
- "sandbox",
- "exec",
- "--name",
- name,
- "--no-tty",
- "--",
- "printenv",
- "ANTHROPIC_API_KEY",
- ])
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
- Some(exec_cmd.output().await.expect("failed to run sandbox exec"))
- } else {
- None
- };
-
- // Always clean up, even if assertions fail.
- if let Some(ref name) = sandbox_name {
- delete_sandbox(name).await;
- }
- delete_provider("claude-code").await;
-
- // Now assert.
- assert!(
- output.status.success(),
- "sandbox create should succeed (exit {:?}):\n{clean}",
- output.status.code()
- );
-
- let exec_output = exec_output.expect("sandbox name should be present");
- let exec_clean = strip_ansi(&format!(
- "{}{}",
- String::from_utf8_lossy(&exec_output.stdout),
- String::from_utf8_lossy(&exec_output.stderr)
- ));
- assert!(
- exec_output.status.success(),
- "sandbox exec should succeed:\n{exec_clean}"
- );
-
- assert!(
- clean.contains("Created provider claude-code"),
- "output should confirm provider auto-creation:\n{clean}"
- );
-
- assert!(
- contains_placeholder_for_env_key(&exec_clean, "ANTHROPIC_API_KEY"),
- "sandbox should have placeholder ANTHROPIC_API_KEY in its environment:\n{exec_clean}"
- );
-
- assert!(
- !exec_clean.contains(TEST_API_KEY),
- "sandbox should not expose the raw ANTHROPIC_API_KEY secret:\n{exec_clean}"
- );
-}
diff --git a/e2e/rust/tests/provider_files.rs b/e2e/rust/tests/provider_files.rs
deleted file mode 100644
index 18db5db9b7..0000000000
--- a/e2e/rust/tests/provider_files.rs
+++ /dev/null
@@ -1,176 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-#![cfg(feature = "e2e-docker")]
-
-//! A provider profile serves read-only config on each workload open.
-
-use std::io::Write as _;
-use std::process::Stdio;
-use std::time::Duration;
-
-use openshell_e2e::harness::binary::openshell_bin;
-use openshell_e2e::harness::cli::run_cli;
-use openshell_e2e::harness::sandbox::SandboxGuard;
-use tokio::time::sleep;
-
-struct ProviderGuard {
- profile: String,
- provider: String,
-}
-
-impl Drop for ProviderGuard {
- fn drop(&mut self) {
- let binary = openshell_bin();
- for _ in 0..20 {
- let deleted = std::process::Command::new(&binary)
- .args(["provider", "delete", &self.provider])
- .stdout(Stdio::null())
- .stderr(Stdio::null())
- .status();
- if deleted.is_ok_and(|status| status.success()) {
- break;
- }
- std::thread::sleep(Duration::from_millis(250));
- }
- let _ = std::process::Command::new(&binary)
- .args(["profile", "delete", &self.profile])
- .stdout(Stdio::null())
- .stderr(Stdio::null())
- .status();
- }
-}
-
-async fn cli_ok(args: &[&str]) -> Result<(), String> {
- let (output, code) = run_cli(args).await;
- if code == 0 {
- Ok(())
- } else {
- Err(format!(
- "{} failed (exit {code}):\n{output}",
- args.join(" ")
- ))
- }
-}
-
-#[tokio::test]
-async fn provider_file_open_update_and_detach() -> Result<(), String> {
- let suffix = format!("{}-{:08x}", std::process::id(), rand::random::());
- let profile_id = format!("pf-{suffix}");
- let provider = format!("pf-{suffix}");
- let profile_yaml = include_str!("../../../examples/provider-managed-files/acme-config.yaml")
- .replace("id: acme-config", &format!("id: {profile_id}"));
- let mut profile_file = tempfile::Builder::new()
- .suffix(".yaml")
- .tempfile()
- .map_err(|error| error.to_string())?;
- profile_file
- .write_all(profile_yaml.as_bytes())
- .map_err(|error| error.to_string())?;
- cli_ok(&[
- "profile",
- "import",
- "--file",
- profile_file
- .path()
- .to_str()
- .ok_or("profile path is not UTF-8")?,
- ])
- .await?;
- let _provider_guard = ProviderGuard {
- profile: profile_id.clone(),
- provider: provider.clone(),
- };
- cli_ok(&[
- "provider",
- "create",
- "--name",
- &provider,
- "--type",
- &profile_id,
- "--config",
- "endpoint=https://api.acme.example",
- "--config",
- "project=production",
- ])
- .await?;
-
- let mut sandbox = SandboxGuard::create(&["--provider", &provider, "--no-tty"]).await?;
- let path = format!("/run/openshell/providers/{provider}/client.toml");
- let environment_path = sandbox.exec(&["printenv", "ACME_CONFIG_FILE"]).await?;
- if !environment_path.contains(&path) {
- return Err(format!(
- "provider path environment variable missing: {environment_path}"
- ));
- }
- let before = sandbox.exec(&["cat", &path]).await?;
- if !before.contains("project = \"production\"") {
- return Err(format!("initial provider file content missing:\n{before}"));
- }
- let permissions = sandbox
- .exec(&[
- "sh",
- "-c",
- &format!(
- "set -eu; exec 3<{path}; test \"$(stat -Lc %a /proc/self/fd/3)\" = 600; \
- test \"$(stat -Lc %F /proc/self/fd/3)\" = 'regular file'; \
- if (printf x >&3) 2>/dev/null; then exit 1; fi; \
- echo provider-file-permissions-ok"
- ),
- ])
- .await?;
- if !permissions.contains("provider-file-permissions-ok") {
- return Err(format!(
- "provider file permission assertion did not complete:\n{permissions}"
- ));
- }
-
- cli_ok(&[
- "provider",
- "update",
- &provider,
- "--config",
- "project=staging",
- "--wait",
- "--timeout",
- "90",
- ])
- .await?;
- let after = sandbox.exec(&["cat", &path]).await?;
- if !after.contains("project = \"staging\"") {
- return Err(format!("updated provider file content missing:\n{after}"));
- }
-
- cli_ok(&[
- "sandbox",
- "provider",
- "detach",
- &sandbox.name,
- &provider,
- "--wait",
- "--timeout",
- "90",
- ])
- .await?;
- let (detached, code) = run_cli(&[
- "sandbox",
- "exec",
- "--name",
- &sandbox.name,
- "--no-tty",
- "--",
- "cat",
- &path,
- ])
- .await;
- if code == 0 || !detached.contains("No such file or directory") {
- return Err(format!(
- "detached provider path remained readable: {detached}"
- ));
- }
- sandbox.cleanup().await;
- // Let the asynchronous sandbox deletion release the provider before
- // ProviderGuard removes the provider record and its profile.
- sleep(Duration::from_millis(250)).await;
- Ok(())
-}
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