diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index 92a1e461e1..0263c1d916 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -122,6 +122,7 @@ jobs: {"environment":"ubuntu-k3s","installer":"k3s-ha","family":"features","package":"routable-host-ip","gateway":"tmachine","runner":"ubuntu-24.04"}, {"environment":"ubuntu-k3s-ipv6","installer":"k3s-ha","family":"features","package":"policy-dns-ipv6","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-middleware-http-hooks","installer":"deb","family":"features","package":"middleware-http-hooks","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"}, diff --git a/e2e/rust/Cargo.lock b/e2e/rust/Cargo.lock index 854f087bae..8b5123b295 100644 --- a/e2e/rust/Cargo.lock +++ b/e2e/rust/Cargo.lock @@ -2413,7 +2413,6 @@ dependencies = [ "base64 0.22.1", "bollard", "bytes", - "flate2", "futures-util", "hex", "http-body-util", diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 1dc042b0fe..874d7881f3 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -193,11 +193,6 @@ name = "host_gateway_alias" path = "tests/host_gateway_alias.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 = "workspace_namespace_managed" path = "tests/workspace_namespace_managed.rs" @@ -248,7 +243,6 @@ tower = "0.5" url = "2" [dev-dependencies] -flate2 = "1" openshell-ocsf-validate = { path = "../../crates/openshell-ocsf-validate" } serial_test = "3" diff --git a/e2e/rust/e2e-podman.sh b/e2e/rust/e2e-podman.sh index 13bb7252ca..5c261e1163 100755 --- a/e2e/rust/e2e-podman.sh +++ b/e2e/rust/e2e-podman.sh @@ -33,7 +33,6 @@ PODMAN_CI_TESTS=( podman_host_gateway provider_github_app provider_token_exchange - sandbox_compat_signals_sched ) if [ -n "${E2E_TEST}" ] && [ -n "${E2E_TEST_SET}" ]; then diff --git a/e2e/rust/tests/supervisor_middleware_http_hooks.rs b/e2e/rust/tests/supervisor_middleware_http_hooks.rs deleted file mode 100644 index d3f6c612b7..0000000000 --- a/e2e/rust/tests/supervisor_middleware_http_hooks.rs +++ /dev/null @@ -1,869 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e-docker")] - -//! HTTP hooks end to end. -//! -//! Runs the `supervisor-middleware-content-guard` example from this checkout -//! as an operator-registered middleware service for the current gateway and -//! Docker sandbox supervisor. `mise run e2e:middleware-http-hooks` builds the -//! example and exports `OPENSHELL_E2E_CONTENT_GUARD_BIN`; without it the test -//! skips, unless `OPENSHELL_E2E_REQUIRE_MIDDLEWARE=1` makes the binary -//! mandatory. -//! -//! The test registers the service in the managed gateway config, restarts -//! the gateway (which describes it), and checks with sandboxes that: -//! - `WHOLE_BODY` redacts and denies request and response bodies; -//! - a response stage inspects the body of a server that compresses, because -//! OpenShell asks for an identity-coded response when the workload asks for -//! gzip; -//! - DUPLEX carries a request body larger than any `WHOLE_BODY` limit; -//! - DUPLEX delivers server-sent events one by one; -//! - a preflight rejection never contacts the upstream; -//! - a policy that mixes HTTP hook versions on one destination, or in which -//! the guard selects a `tls: skip` endpoint, is rejected at `policy set`. - -use std::io::Write as _; -use std::path::PathBuf; -use std::process::Stdio; -use std::sync::{Arc, Mutex}; -use std::time::Duration; - -use openshell_e2e::harness::cli::{run_cli, wait_for_healthy}; -use openshell_e2e::harness::gateway::ManagedGateway; -use openshell_e2e::harness::port::{find_free_port, wait_for_port}; -use openshell_e2e::harness::sandbox::SandboxGuard; -use serde_json::Value; -use serial_test::serial; -use tempfile::NamedTempFile; -use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; -use tokio::net::{TcpListener, TcpStream}; -use tokio::sync::Notify; -use tokio::task::JoinHandle; - -const BIN_ENV: &str = "OPENSHELL_E2E_CONTENT_GUARD_BIN"; -const REQUIRE_ENV: &str = "OPENSHELL_E2E_REQUIRE_MIDDLEWARE"; -/// Operator registration name used by the policies. -const REGISTRATION: &str = "content-guard-example"; -const SANDBOX_HOST: &str = "host.openshell.internal"; -const SENSITIVE_BODY: &str = "contains prototype-secret and internal-only"; -const CLEAN_BODY: &str = "ordinary public text"; -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""#; - -/// The content guard, run as a host process. -struct ContentGuard { - child: tokio::process::Child, - port: u16, -} - -impl ContentGuard { - async fn start(binary: &str) -> Self { - let port = find_free_port(); - let child = tokio::process::Command::new(binary) - .arg("--bind") - .arg(format!("0.0.0.0:{port}")) - .stdout(Stdio::null()) - .stderr(Stdio::inherit()) - .kill_on_drop(true) - .spawn() - .unwrap_or_else(|error| panic!("start content guard '{binary}': {error}")); - wait_for_port("127.0.0.1", port, Duration::from_secs(30)) - .await - .expect("content guard listens"); - Self { child, port } - } -} - -impl Drop for ContentGuard { - fn drop(&mut self) { - let _ = self.child.start_kill(); - } -} - -/// Appends the content-guard registration to the managed gateway config, -/// restarts the gateway, and restores both on drop. -struct GatewayRegistration { - config_path: PathBuf, - original: Vec, -} - -impl GatewayRegistration { - fn config_path() -> PathBuf { - let args_file = std::env::var("OPENSHELL_E2E_GATEWAY_ARGS_FILE") - .expect("OPENSHELL_E2E_GATEWAY_ARGS_FILE is set for a managed gateway"); - let raw = std::fs::read(&args_file).expect("read gateway args"); - let args: Vec = raw - .split(|byte| *byte == 0) - .filter(|arg| !arg.is_empty()) - .map(|arg| String::from_utf8_lossy(arg).into_owned()) - .collect(); - args.iter() - .position(|arg| arg == "--config") - .and_then(|index| args.get(index + 1)) - .map(PathBuf::from) - .expect("gateway args include --config") - } - - /// Host that both the gateway process and the host-networked Docker - /// supervisor use to reach this machine: the host of the driver's - /// gateway endpoint. Without one, the driver discovers the gateway on - /// loopback, which the host-networked supervisor shares. - fn shared_host(config: &str) -> String { - let driver = config - .find("[openshell.drivers.docker]") - .expect("gateway config has a Docker driver table"); - let Some(endpoint) = config[driver..] - .lines() - .skip(1) - .take_while(|line| !line.trim_start().starts_with('[')) - .find_map(|line| line.trim().strip_prefix("grpc_endpoint = ")) - else { - return "127.0.0.1".to_string(); - }; - let endpoint = endpoint.trim_matches('"'); - let authority = endpoint - .split_once("://") - .map_or(endpoint, |(_, rest)| rest); - let host = authority - .rsplit_once(':') - .map_or(authority, |(host, _)| host); - host.trim_start_matches('[') - .trim_end_matches(']') - .to_string() - } - - async fn apply(guard_port: u16) -> Self { - let config_path = Self::config_path(); - let original = std::fs::read(&config_path).expect("read gateway config"); - let config = String::from_utf8(original.clone()).expect("UTF-8 gateway config"); - let host = Self::shared_host(&config); - let registration = format!( - "\n[[openshell.supervisor.middleware]]\nname = \"{REGISTRATION}\"\ngrpc_endpoint = \"http://{host}:{guard_port}\"\nallow_insecure_transport = true\nmax_payload_bytes = 262144\ntimeout = \"2s\"\n" - ); - std::fs::write(&config_path, format!("{config}{registration}")) - .expect("write gateway config"); - let guard = Self { - config_path, - original, - }; - restart_gateway().await; - guard - } - - async fn restore(self) { - std::fs::write(&self.config_path, &self.original).expect("restore gateway config"); - restart_gateway().await; - std::mem::forget(self); - } -} - -impl Drop for GatewayRegistration { - fn drop(&mut self) { - let _ = std::fs::write(&self.config_path, &self.original); - if let Ok(Some(gateway)) = ManagedGateway::from_env() { - let _ = gateway.stop(); - let _ = gateway.start(); - } - } -} - -async fn restart_gateway() { - let gateway = ManagedGateway::from_env() - .expect("managed gateway metadata") - .expect("managed gateway"); - gateway.stop().expect("stop gateway"); - gateway.start().expect("start gateway"); - wait_for_healthy(Duration::from_secs(120)) - .await - .expect("gateway healthy with the middleware registered"); -} - -/// One request the upstream served. -struct ReceivedRequest { - target: String, - accept_encoding: Option, - body: Vec, -} - -type Received = Arc>>; - -/// Minimal HTTP/1.1 upstream on the host. It accepts `Content-Length` and -/// chunked request bodies, and every response closes its connection. -/// -/// - `POST /echo` returns the request body. -/// - `GET /sensitive` and `GET /clean` return fixed text. -/// - `GET /compressible` returns the `/sensitive` text, gzip-coded when the -/// request accepts gzip, as a typical server does. -/// - `GET /events` streams two server-sent events. It sends the second only -/// after `POST /ack`, or marks it `late` after a timeout, so a client that -/// acknowledges the first event proves it arrived on its own. -struct Upstream { - port: u16, - received: Received, - task: JoinHandle<()>, -} - -impl Upstream { - async fn start() -> Self { - let listener = TcpListener::bind(("0.0.0.0", 0)) - .await - .expect("bind upstream"); - let port = listener.local_addr().expect("upstream address").port(); - let received = Arc::new(Mutex::new(Vec::new())); - let task_received = Arc::clone(&received); - let acknowledged = Arc::new(Notify::new()); - let task = tokio::spawn(async move { - while let Ok((stream, _)) = listener.accept().await { - let received = Arc::clone(&task_received); - let acknowledged = Arc::clone(&acknowledged); - tokio::spawn(async move { - let _ = serve_one(stream, received, acknowledged).await; - }); - } - }); - Self { - port, - received, - task, - } - } - - fn targets(&self) -> Vec { - self.received - .lock() - .unwrap() - .iter() - .map(|request| request.target.clone()) - .collect() - } - - fn bodies(&self, target: &str) -> Vec> { - self.received - .lock() - .unwrap() - .iter() - .filter(|request| request.target == target) - .map(|request| request.body.clone()) - .collect() - } - - fn accept_encodings(&self, target: &str) -> Vec> { - self.received - .lock() - .unwrap() - .iter() - .filter(|request| request.target == target) - .map(|request| request.accept_encoding.clone()) - .collect() - } -} - -impl Drop for Upstream { - fn drop(&mut self) { - self.task.abort(); - } -} - -async fn read_request( - stream: &mut BufReader, -) -> std::io::Result> { - let mut request_line = String::new(); - if stream.read_line(&mut request_line).await? == 0 { - return Ok(None); - } - let target = request_line - .split_whitespace() - .nth(1) - .unwrap_or_default() - .to_string(); - let mut length = 0; - let mut chunked = false; - let mut accept_encoding = None; - loop { - let mut line = String::new(); - stream.read_line(&mut line).await?; - let line = line.trim_end(); - if line.is_empty() { - break; - } - let lower = line.to_ascii_lowercase(); - if let Some(value) = lower.strip_prefix("content-length:") { - length = value.trim().parse().unwrap_or(0); - } - if lower.starts_with("transfer-encoding:") && lower.contains("chunked") { - chunked = true; - } - if let Some(value) = lower.strip_prefix("accept-encoding:") { - accept_encoding = Some(value.trim().to_string()); - } - } - let mut body = Vec::new(); - if chunked { - loop { - let mut size = String::new(); - stream.read_line(&mut size).await?; - let size = usize::from_str_radix(size.trim().split(';').next().unwrap_or("0"), 16) - .unwrap_or(0); - if size == 0 { - // Trailer section. - loop { - let mut line = String::new(); - stream.read_line(&mut line).await?; - if line.trim_end().is_empty() { - break; - } - } - break; - } - let mut chunk = vec![0; size + 2]; - stream.read_exact(&mut chunk).await?; - body.extend_from_slice(&chunk[..size]); - } - } else { - body.resize(length, 0); - stream.read_exact(&mut body).await?; - } - Ok(Some(ReceivedRequest { - target, - accept_encoding, - body, - })) -} - -fn accepts_gzip(accept_encoding: Option<&str>) -> bool { - accept_encoding.is_some_and(|value| { - value - .split(',') - .any(|coding| coding.split(';').next().unwrap_or_default().trim() == "gzip") - }) -} - -fn gzip(data: &[u8]) -> Vec { - let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - encoder.write_all(data).expect("gzip response body"); - encoder.finish().expect("finish gzip response body") -} - -async fn serve_one( - stream: TcpStream, - received: Received, - acknowledged: Arc, -) -> std::io::Result<()> { - let mut stream = BufReader::new(stream); - let Some(request) = read_request(&mut stream).await? else { - return Ok(()); - }; - let target = request.target.clone(); - let body = request.body.clone(); - let compress = target == "/compressible" && accepts_gzip(request.accept_encoding.as_deref()); - received.lock().unwrap().push(request); - let mut stream = stream.into_inner(); - if target == "/events" { - stream - .write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n") - .await?; - write_chunk(&mut stream, b"data: one prototype-secret\n\n").await?; - let second = - match tokio::time::timeout(Duration::from_secs(20), acknowledged.notified()).await { - Ok(()) => &b"data: two\n\n"[..], - Err(_) => b"data: late\n\n", - }; - write_chunk(&mut stream, second).await?; - stream.write_all(b"0\r\n\r\n").await?; - return stream.shutdown().await; - } - if target == "/ack" { - acknowledged.notify_one(); - stream - .write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n") - .await?; - return stream.shutdown().await; - } - let (content_type, response_body) = match target.as_str() { - "/echo" => ("application/octet-stream", body), - "/sensitive" | "/compressible" => ("text/plain", SENSITIVE_BODY.as_bytes().to_vec()), - _ => ("text/plain", CLEAN_BODY.as_bytes().to_vec()), - }; - let (content_encoding, response_body) = if compress { - ("Content-Encoding: gzip\r\n", gzip(&response_body)) - } else { - ("", response_body) - }; - let head = format!( - "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\n{content_encoding}Content-Length: {}\r\nConnection: close\r\n\r\n", - response_body.len() - ); - stream.write_all(head.as_bytes()).await?; - stream.write_all(&response_body).await?; - stream.shutdown().await -} - -async fn write_chunk(stream: &mut TcpStream, data: &[u8]) -> std::io::Result<()> { - stream - .write_all(format!("{:X}\r\n", data.len()).as_bytes()) - .await?; - stream.write_all(data).await?; - stream.write_all(b"\r\n").await?; - stream.flush().await -} - -struct PolicyCase<'a> { - mode: &'a str, - body_mode: &'a str, - /// Port of a `tls: skip` endpoint the attachment also selects, which the - /// gateway rejects. - tls_skip_port: Option, - /// Also attach `openshell/regex` (legacy HTTP hooks) to the same host. - mixed: bool, -} - -fn write_policy(upstream_port: u16, case: &PolicyCase<'_>) -> NamedTempFile { - let replacement = if case.mode == "redact" { - " replacement: \"[FILTERED]\"\n" - } else { - "" - }; - let tls_skip_endpoint = case.tls_skip_port.map_or_else(String::new, |port| { - format!(" - host: {SANDBOX_HOST}\n port: {port}\n tls: skip\n{PRIVATE_ALLOWED_IPS}\n") - }); - let regex = if case.mixed { - r#" regex-redactor: - middleware: openshell/regex - order: 20 - config: - mode: redact - endpoints: - include: ["*.openshell.internal"] -"# - } else { - "" - }; - 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: - content-guard: - name: Content guard - middleware: {REGISTRATION} - order: 10 - config: - mode: {mode} - body_mode: {body_mode} - terms: - - prototype-secret - - internal-only -{replacement} on_error: fail_closed - endpoints: - include: ["{SANDBOX_HOST}"] -{regex} -network_policies: - guard_upstream: - name: guard_upstream - endpoints: - - host: {SANDBOX_HOST} - port: {upstream_port} - protocol: rest - enforcement: enforce - rules: - - allow: - method: POST - path: /echo - - allow: - method: POST - path: /ack - - allow: - method: GET - path: /sensitive - - allow: - method: GET - path: /clean - - allow: - method: GET - path: /compressible - - allow: - method: GET - path: /events -{PRIVATE_ALLOWED_IPS} -{tls_skip_endpoint} binaries: - - path: "/**" -"#, - mode = case.mode, - body_mode = case.body_mode, - ); - let mut file = NamedTempFile::new().expect("create policy file"); - file.write_all(policy.as_bytes()).expect("write policy"); - file.flush().expect("flush policy"); - file -} - -/// Upload size larger than any `WHOLE_BODY` limit (256 KiB), so only DUPLEX can -/// carry it. -const LARGE_UPLOAD_LINES: usize = 600; - -fn workload_script(upstream_port: u16, case: &PolicyCase<'_>) -> String { - format!( - r#" -import gzip -import http.client -import json - -HOST = "{SANDBOX_HOST}" -PORT = {upstream_port} -DUPLEX = {duplex} - -def call(method, path, body=None, headers=None): - conn = http.client.HTTPConnection(HOST, PORT, timeout=60) - request_headers = {{"Content-Type": "application/octet-stream"}} if body is not None else {{}} - request_headers.update(headers or {{}}) - conn.request(method, path, body=body, headers=request_headers) - response = conn.getresponse() - data = response.read() - encoding = response.getheader("Content-Encoding", "") - if encoding == "gzip": - data = gzip.decompress(data) - conn.close() - return {{"status": response.status, "body": data.decode("latin-1"), "encoding": encoding}} - -results = {{ - "echo_term": call("POST", "/echo", b'{{"note":"prototype-secret"}}'), - "sensitive": call("GET", "/sensitive"), - "clean": call("GET", "/clean"), - "target_term": call("GET", "/clean?q=prototype-secret"), - # Ask for gzip by default, as requests, httpx, and fetch do. - "compressible": call("GET", "/compressible", headers={{"Accept-Encoding": "gzip, deflate"}}), -}} - -if DUPLEX: - upload = (b"x" * 1000 + b" prototype-secret\n") * {LARGE_UPLOAD_LINES} - echoed = call("POST", "/echo", upload) - expected = upload.replace(b"prototype-secret", b"[FILTERED]") - results["large_upload"] = {{ - "status": echoed["status"], - "sent_bytes": len(upload), - "redacted": echoed["body"].encode("latin-1") == expected, - }} - - conn = http.client.HTTPConnection(HOST, PORT, timeout=60) - conn.request("GET", "/events") - response = conn.getresponse() - first = b"" - while not first.endswith(b"\n\n"): - line = response.readline() - if not line: - break - first += line - acknowledged = call("POST", "/ack") - rest = response.read() - conn.close() - results["events"] = {{ - "status": response.status, - "first": first.decode("utf-8"), - "ack": acknowledged["status"], - "rest": rest.decode("utf-8"), - }} - -print(json.dumps(results, sort_keys=True)) -"#, - duplex = if case.body_mode == "duplex" { - "True" - } else { - "False" - }, - ) -} - -async fn run_workload(upstream: &Upstream, case: &PolicyCase<'_>) -> Value { - let policy = write_policy(upstream.port, case); - let policy_path = policy.path().to_str().expect("UTF-8 policy path"); - let script = workload_script(upstream.port, case); - let mut sandbox = - SandboxGuard::create(&["--policy", policy_path, "--", "python3", "-c", &script]) - .await - .unwrap_or_else(|error| panic!("{} {} sandbox: {error}", case.mode, case.body_mode)); - let result = sandbox - .create_output - .lines() - .filter_map(|line| serde_json::from_str::(line.trim()).ok()) - .next_back() - .unwrap_or_else(|| panic!("missing workload result:\n{}", sandbox.create_output)); - sandbox.cleanup().await; - result -} - -fn assert_response(result: &Value, name: &str, status: u64, body: &str) { - assert_eq!(result[name]["status"], status, "{name}: {result}"); - assert_eq!(result[name]["body"], body, "{name}: {result}"); -} - -fn assert_platform_error(result: &Value, name: &str, status: u64, error: &str) -> Value { - assert_eq!(result[name]["status"], status, "{name}: {result}"); - let body: Value = serde_json::from_str(result[name]["body"].as_str().unwrap_or_default()) - .unwrap_or_else(|_| panic!("{name} returns a JSON error: {result}")); - assert_eq!(body["error"], error, "{name}: {body}"); - body -} - -fn should_run() -> Option { - let required = std::env::var(REQUIRE_ENV).as_deref() == Ok("1"); - let skip = |reason: &str| { - assert!(!required, "{REQUIRE_ENV}=1 but {reason}"); - eprintln!("Skipping HTTP hook middleware e2e: {reason}"); - None - }; - if std::env::var("OPENSHELL_E2E_DRIVER").as_deref() != Ok("docker") { - return skip("the e2e driver is not docker"); - } - if std::env::var("OPENSHELL_E2E_EXTERNAL_COMPUTE_DRIVER").as_deref() == Ok("1") { - return skip("the external Docker driver does not read gateway config"); - } - match ManagedGateway::from_env() { - Ok(Some(_)) => {} - Ok(None) => return skip("the gateway is not managed by this run"), - Err(error) => panic!("load managed gateway metadata: {error}"), - } - match std::env::var(BIN_ENV) { - Ok(binary) if !binary.is_empty() => Some(binary), - _ => skip(&format!( - "{BIN_ENV} is not set; run `mise run e2e:middleware-http-hooks`" - )), - } -} - -#[tokio::test] -#[serial(supervisor_middleware)] -async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor() { - let Some(binary) = should_run() else { - return; - }; - let guard = ContentGuard::start(&binary).await; - let upstream = Upstream::start().await; - let registration = GatewayRegistration::apply(guard.port).await; - - // WHOLE_BODY redaction in both directions and a preflight rejection. - let redact = run_workload( - &upstream, - &PolicyCase { - mode: "redact", - body_mode: "whole_body", - tls_skip_port: None, - mixed: false, - }, - ) - .await; - assert_response(&redact, "echo_term", 200, r#"{"note":"[FILTERED]"}"#); - assert_response( - &redact, - "sensitive", - 200, - "contains [FILTERED] and [FILTERED]", - ); - assert_response(&redact, "clean", 200, CLEAN_BODY); - // The workload asked for gzip. A response stage that may inspect bodies - // makes OpenShell ask for identity instead, so the guard can redact. - assert_response( - &redact, - "compressible", - 200, - "contains [FILTERED] and [FILTERED]", - ); - assert_eq!(redact["compressible"]["encoding"], "", "{redact}"); - let codings = upstream.accept_encodings("/compressible"); - assert!( - !codings.is_empty() - && codings - .iter() - .all(|coding| coding.as_deref() == Some("identity")), - "OpenShell asks the upstream for an identity-coded response: {codings:?}" - ); - assert!( - upstream - .bodies("/echo") - .contains(&br#"{"note":"[FILTERED]"}"#.to_vec()), - "the upstream receives the redacted body" - ); - let rejected = assert_platform_error(&redact, "target_term", 403, "middleware_denied"); - assert_eq!(rejected["reason_code"], "content_match", "{rejected}"); - assert!( - upstream - .targets() - .iter() - .all(|target| !target.contains("prototype-secret")), - "a preflight rejection never contacts the upstream" - ); - - // WHOLE_BODY denial in both directions. - let echo_bodies_before = upstream.bodies("/echo").len(); - let deny = run_workload( - &upstream, - &PolicyCase { - mode: "deny", - body_mode: "whole_body", - tls_skip_port: None, - mixed: false, - }, - ) - .await; - for name in ["echo_term", "sensitive", "compressible"] { - let body = assert_platform_error(&deny, name, 403, "middleware_denied"); - assert_eq!(body["reason_code"], "content_match", "{name}: {body}"); - assert!(!body.to_string().contains("prototype-secret"), "{body}"); - } - assert_response(&deny, "clean", 200, CLEAN_BODY); - assert_eq!( - upstream.bodies("/echo").len(), - echo_bodies_before, - "a denied request body never reaches the upstream" - ); - - // DUPLEX: a large upload and server-sent events one by one. - let stream = run_workload( - &upstream, - &PolicyCase { - mode: "redact", - body_mode: "duplex", - tls_skip_port: None, - mixed: false, - }, - ) - .await; - assert_response(&stream, "echo_term", 200, r#"{"note":"[FILTERED]"}"#); - assert_eq!(stream["large_upload"]["status"], 200, "{stream}"); - assert_eq!(stream["large_upload"]["redacted"], true, "{stream}"); - let large = upstream - .bodies("/echo") - .into_iter() - .max_by_key(Vec::len) - .expect("the upstream received the large upload"); - assert!( - large.len() > 256 * 1024, - "the large upload exceeds every WHOLE_BODY limit" - ); - assert!(!String::from_utf8_lossy(&large).contains("prototype-secret")); - assert_eq!(stream["events"]["status"], 200, "{stream}"); - assert_eq!( - stream["events"]["first"], "data: one [FILTERED]\n\n", - "{stream}" - ); - assert_eq!(stream["events"]["ack"], 204, "{stream}"); - assert_eq!( - stream["events"]["rest"], "data: two\n\n", - "the first event reached the sandbox before the second was sent: {stream}" - ); - - // A policy that runs both HTTP hook versions for one destination is rejected. - let base = write_policy( - upstream.port, - &PolicyCase { - mode: "redact", - body_mode: "whole_body", - tls_skip_port: None, - mixed: false, - }, - ); - let mixed = write_policy( - upstream.port, - &PolicyCase { - mode: "redact", - body_mode: "whole_body", - tls_skip_port: None, - mixed: true, - }, - ); - let mut sandbox = SandboxGuard::create_keep_with_args( - &[ - "--policy", - base.path().to_str().expect("UTF-8 policy path"), - "--no-tty", - ], - &["sh", "-c", "echo Ready && sleep infinity"], - "Ready", - ) - .await - .expect("create sandbox with the content guard"); - let (output, exit_code) = run_cli(&[ - "policy", - "set", - &sandbox.name, - "--policy", - mixed.path().to_str().expect("UTF-8 policy path"), - ]) - .await; - assert_ne!( - exit_code, 0, - "a mixed-version policy is rejected:\n{output}" - ); - // The CLI wraps long errors across lines. - let message = output - .replace('│', " ") - .split_whitespace() - .collect::>() - .join(" "); - assert!( - message.contains("separate their endpoint selectors"), - "the rejection says how to fix the policy:\n{output}" - ); - - // The guard is fail-closed and cannot inspect a `tls: skip` tunnel, so a - // policy in which it selects one is rejected. - let tls_skip = write_policy( - upstream.port, - &PolicyCase { - mode: "redact", - body_mode: "whole_body", - tls_skip_port: Some(find_free_port()), - mixed: false, - }, - ); - let (output, exit_code) = run_cli(&[ - "policy", - "set", - &sandbox.name, - "--policy", - tls_skip.path().to_str().expect("UTF-8 policy path"), - ]) - .await; - assert_ne!( - exit_code, 0, - "a policy in which the guard selects a tls: skip endpoint is rejected:\n{output}" - ); - let message = output - .replace('│', " ") - .split_whitespace() - .collect::>() - .join(" "); - assert!( - message.contains("tls: skip endpoint"), - "the rejection names the tls: skip endpoint:\n{output}" - ); - sandbox.cleanup().await; - - registration.restore().await; - drop(guard); -} diff --git a/e2e/with-docker-gateway.sh b/e2e/with-docker-gateway.sh index c3d86e1a9b..d98ee49473 100755 --- a/e2e/with-docker-gateway.sh +++ b/e2e/with-docker-gateway.sh @@ -126,6 +126,8 @@ ADDITIONAL_CA_SERVER_PID="" ADDITIONAL_CA_SERVER_LOG="${WORKDIR}/additional-ca-server.log" ADDITIONAL_CA_DIR="${WORKDIR}/additional-ca" ADDITIONAL_CA_PORT="" +CONTENT_GUARD_PID="" +CONTENT_GUARD_PORT="" IMAGE_UPDATES_MODE="${OPENSHELL_E2E_DOCKER_IMAGE_UPDATES:-0}" SUPERVISOR_NETWORK_MODE="${OPENSHELL_E2E_DOCKER_SUPERVISOR_NETWORK_MODE:-}" case "${SUPERVISOR_NETWORK_MODE}" in @@ -133,6 +135,11 @@ case "${SUPERVISOR_NETWORK_MODE}" in *) echo "ERROR: invalid Docker supervisor network mode for e2e." >&2; exit 2 ;; esac +if [ -n "${OPENSHELL_E2E_CONTENT_GUARD_BIN:-}" ] && [ -n "${OPENSHELL_GATEWAY_ENDPOINT:-}" ]; then + echo "ERROR: The content guard fixture requires a gateway started by this wrapper." >&2 + exit 2 +fi + if [ "${IMAGE_UPDATES_MODE}" = "1" ] && [ -n "${OPENSHELL_GATEWAY_ENDPOINT:-}" ]; then echo "ERROR: Docker image-update qualification requires a new gateway owned by this wrapper." >&2 exit 2 @@ -156,6 +163,7 @@ cleanup() { e2e_stop_gateway "${GATEWAY_PID}" "${GATEWAY_PID_FILE}" e2e_stop_process "${ADDITIONAL_CA_SERVER_PID}" "additional CA HTTPS fixture" + e2e_stop_process "${CONTENT_GUARD_PID}" "content guard middleware" if [ "${exit_code}" -ne 0 ] \ && [ -n "${E2E_NAMESPACE}" ] \ @@ -612,6 +620,27 @@ fi export OPENSHELL_E2E_GATEWAY_CA_CERT="${PKI_DIR}/ca.crt" GATEWAY_ENDPOINT="https://${SUPERVISOR_GATEWAY_HOST}:${HOST_PORT}" +if [ -n "${OPENSHELL_E2E_CONTENT_GUARD_BIN:-}" ]; then + CONTENT_GUARD_PORT="$(e2e_pick_port)" + "${OPENSHELL_E2E_CONTENT_GUARD_BIN}" --bind "0.0.0.0:${CONTENT_GUARD_PORT}" & + CONTENT_GUARD_PID=$! + for ((attempt = 0; attempt < 30; attempt++)); do + if ! kill -0 "${CONTENT_GUARD_PID}" 2>/dev/null; then + echo "ERROR: Content guard exited before it started listening." >&2 + exit 1 + fi + if (exec 3<>"/dev/tcp/127.0.0.1/${CONTENT_GUARD_PORT}") 2>/dev/null; then + break + fi + sleep 1 + done + if [ "${attempt}" -eq 30 ]; then + echo "ERROR: Content guard did not start listening." >&2 + exit 1 + fi + export OPENSHELL_TEST_CONTENT_GUARD_REGISTRATION=content-guard-example +fi + echo "Starting openshell-gateway on port ${HOST_PORT} (namespace: ${E2E_NAMESPACE})..." echo "Using sandbox image: ${SANDBOX_IMAGE} (pull policy: ${SANDBOX_IMAGE_PULL_POLICY})" e2e_generate_gateway_jwt "${JWT_DIR}" @@ -682,6 +711,12 @@ GATEWAY_CONFIG="${STATE_DIR}/gateway.toml" printf 'supervisor_image = %s\n' "$(toml_string "${SUPERVISOR_IMAGE}")" printf '\n[openshell.drivers.docker.resource_admission]\n' printf 'enabled = false\n' + if [ -n "${CONTENT_GUARD_PORT}" ]; then + printf '\n[[openshell.supervisor.middleware]]\n' + printf 'name = %s\n' "$(toml_string "${OPENSHELL_TEST_CONTENT_GUARD_REGISTRATION}")" + printf 'grpc_endpoint = %s\n' "$(toml_string "http://${SUPERVISOR_GATEWAY_HOST}:${CONTENT_GUARD_PORT}")" + printf 'allow_insecure_transport = true\nmax_payload_bytes = 262144\ntimeout = "2s"\n' + fi } > "${GATEWAY_CONFIG}" GATEWAY_ARGS=( diff --git a/tasks/test.toml b/tasks/test.toml index bdd923de3f..98441e8fed 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -239,9 +239,8 @@ TARGET_DIR="${CARGO_TARGET_DIR:-$PWD/target}/content-guard" cargo build --locked --manifest-path examples/supervisor-middleware-content-guard/Cargo.toml \ --target-dir "${TARGET_DIR}" export OPENSHELL_E2E_CONTENT_GUARD_BIN="${TARGET_DIR}/debug/supervisor-middleware-content-guard" -export OPENSHELL_E2E_REQUIRE_MIDDLEWARE=1 -exec e2e/with-docker-gateway.sh cargo test --manifest-path e2e/rust/Cargo.toml \ - --features e2e-docker --test supervisor_middleware_http_hooks -- --nocapture +exec e2e/with-docker-gateway.sh cargo test --locked \ + --manifest-path tests/suites/features/Cargo.toml -p middleware-http-hooks -- --nocapture """ ["e2e:mcp"] diff --git a/tests/suites/conformance/src/lib.rs b/tests/suites/conformance/src/lib.rs index 3d4dca0eaa..e21b7f3303 100644 --- a/tests/suites/conformance/src/lib.rs +++ b/tests/suites/conformance/src/lib.rs @@ -28,6 +28,7 @@ mod port_forward; mod process; mod providers; mod settings; +mod signals_scheduling; mod smoke; mod ssh; mod templates; diff --git a/e2e/rust/tests/sandbox_compat_signals_sched.rs b/tests/suites/conformance/src/signals_scheduling.rs similarity index 90% rename from e2e/rust/tests/sandbox_compat_signals_sched.rs rename to tests/suites/conformance/src/signals_scheduling.rs index 4bc5a5d308..aa03dad0da 100644 --- a/e2e/rust/tests/sandbox_compat_signals_sched.rs +++ b/tests/suites/conformance/src/signals_scheduling.rs @@ -9,9 +9,7 @@ //! failed with EPERM. The broker now mediates them: the caller's own thread //! group is allowed and every other target stays denied. -#![cfg(feature = "e2e")] - -use openshell_e2e::harness::sandbox::SandboxGuard; +use testkit::Context; const SUCCESS_MARKER: &str = "sandbox_compat_signals_sched=ok"; @@ -175,17 +173,24 @@ sys.exit(0 if not failures else 1) "# } -#[tokio::test] -async fn sandbox_allows_own_group_and_denies_foreign_scheduling_and_signals() { - let mut sandbox = SandboxGuard::create(&["--", "python3", "-c", compat_script()]) - .await - .expect("sandbox create"); - - assert!( - sandbox.create_output.contains(SUCCESS_MARKER), - "expected own-group probes to pass and foreign-target probes to be denied:\n{}", - sandbox.create_output +/// Scheduling and signal probes may act on the caller's thread group, but +/// scheduling changes that target another process must fail with EPERM. +#[testkit::test] +async fn sandbox_allows_own_group_and_denies_foreign_scheduling_and_signals( + cx: &mut Context, +) -> testkit::Result { + let sandbox = cx + .sandbox("sig") + .image(testkit::python_image()) + .command(["sleep", "infinity"]) + .create_ready() + .await?; + let output = sandbox.run_python(compat_script(), &[]).await?; + testkit::ensure!( + output.stdout.lines().any(|line| line == SUCCESS_MARKER), + "missing successful syscall probes:\n{}{}", + output.stdout, + output.stderr ); - - sandbox.cleanup().await; + Ok(()) } diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index e9ff22fc8f..37938a8518 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -636,6 +636,15 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + [[package]] name = "critical-section" version = "1.2.0" @@ -996,6 +1005,16 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + [[package]] name = "flume" version = "0.12.0" @@ -2153,6 +2172,21 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "middleware-http-hooks" +version = "0.0.0" +dependencies = [ + "async-stream", + "flate2", + "host-server-support", + "http-body-util", + "hyper", + "hyper-util", + "openshell-testkit", + "serde_json", + "tokio", +] + [[package]] name = "miette" version = "7.6.0" @@ -2202,6 +2236,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", + "simd-adler32", ] [[package]] @@ -3678,6 +3713,12 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simd-adler32" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" + [[package]] name = "simd_cesu8" version = "1.2.0" diff --git a/tests/suites/features/middleware-http-hooks/Cargo.toml b/tests/suites/features/middleware-http-hooks/Cargo.toml new file mode 100644 index 0000000000..c941e5e7ff --- /dev/null +++ b/tests/suites/features/middleware-http-hooks/Cargo.toml @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "middleware-http-hooks" +description = "Features suite: HTTP hooks against a registered middleware service" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/ai-openshell/openshell" +publish = false + +[[test]] +name = "middleware-http-hooks" +path = "tests/http_hooks.rs" +harness = false + +[dependencies] +async-stream = "0.3" +flate2 = "1" +host-server-support = { path = "../../../support/host-server" } +http-body-util = "0.1" +hyper = { version = "1", features = ["http1", "server"] } +hyper-util = { version = "0.1", features = ["tokio"] } +openshell-testkit = { path = "../../../testkit/testkit" } +serde_json = "1" +tokio = { version = "1", features = ["net", "rt", "sync", "time"] } diff --git a/tests/suites/features/middleware-http-hooks/README.md b/tests/suites/features/middleware-http-hooks/README.md new file mode 100644 index 0000000000..a620285288 --- /dev/null +++ b/tests/suites/features/middleware-http-hooks/README.md @@ -0,0 +1,13 @@ +# Registered middleware HTTP hooks + +Run `mise run e2e:middleware-http-hooks` to start a Docker gateway and the +content-guard example and run the suite. The tmachine row +`ubuntu-docker-rootful-middleware-http-hooks/deb` starts and registers the same +example during environment setup. Build its binary with +`nix run .#build-artifacts-test-archives` when preparing inputs locally. + +Both environments set `OPENSHELL_TEST_CONTENT_GUARD_REGISTRATION` to the name +registered in the gateway (typically `content-guard-example`). The suite fails +if it is missing. The gateway and supervisor must be able to reach the guard, +and the sandbox must be able to reach an upstream hosted by the test process +at `host.openshell.internal`. diff --git a/tests/suites/features/middleware-http-hooks/tests/http_hooks.rs b/tests/suites/features/middleware-http-hooks/tests/http_hooks.rs new file mode 100644 index 0000000000..2ea6d3c862 --- /dev/null +++ b/tests/suites/features/middleware-http-hooks/tests/http_hooks.rs @@ -0,0 +1,650 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! HTTP hooks against an environment with the content-guard service registered: +//! - `WHOLE_BODY` redacts and denies request and response bodies; +//! - a response stage inspects the body of a server that compresses, because +//! OpenShell asks for an identity-coded response when the workload asks for +//! gzip; +//! - DUPLEX carries a request body larger than any `WHOLE_BODY` limit; +//! - DUPLEX delivers server-sent events one by one; +//! - a preflight rejection never contacts the upstream; +//! - a policy that mixes HTTP hook versions on one destination, or in which +//! the guard selects a `tls: skip` endpoint, is rejected at `policy set`. + +use std::convert::Infallible; +use std::io::Write as _; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use host_server_support::TEST_HOST as SANDBOX_HOST; +use http_body_util::{BodyExt as _, Full, Limited, StreamBody, combinators::UnsyncBoxBody}; +use hyper::body::{Bytes, Frame, Incoming}; +use hyper::header::{ACCEPT_ENCODING, CACHE_CONTROL, CONTENT_ENCODING, CONTENT_TYPE}; +use hyper::server::conn::http1; +use hyper::service::service_fn; +use hyper::{Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use serde_json::Value; +use testkit::{Context, ResultExt as _, YamlFile}; +use tokio::net::TcpListener; +use tokio::sync::Notify; +use tokio::task::JoinHandle; + +const SENSITIVE_BODY: &str = "contains prototype-secret and internal-only"; +const CLEAN_BODY: &str = "ordinary public text"; +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""#; + +fn main() -> std::process::ExitCode { + testkit::main() +} + +/// One request the upstream served. +struct ReceivedRequest { + target: String, + accept_encoding: Option, + body: Bytes, +} + +type Received = Arc>>; +type FixtureBody = UnsyncBoxBody; + +/// Minimal HTTP/1.1 upstream on the host. It accepts `Content-Length` and +/// chunked request bodies, and every response closes its connection. +/// +/// - `POST /echo` returns the request body. +/// - `GET /sensitive` and `GET /clean` return fixed text. +/// - `GET /compressible` returns the `/sensitive` text, gzip-coded when the +/// request accepts gzip, as a typical server does. +/// - `GET /events` streams two server-sent events. It sends the second only +/// after `POST /ack`, or marks it `late` after a timeout, so a client that +/// acknowledges the first event proves it arrived on its own. +struct Upstream { + port: u16, + received: Received, + task: JoinHandle<()>, +} + +impl Upstream { + async fn start() -> testkit::Result { + let listener = TcpListener::bind(("0.0.0.0", 0)) + .await + .context("bind the middleware test upstream")?; + let port = listener + .local_addr() + .context("read upstream address")? + .port(); + let received = Arc::new(Mutex::new(Vec::new())); + let task_received = Arc::clone(&received); + let acknowledged = Arc::new(Notify::new()); + let task = tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + let _ = stream.set_nodelay(true); + let received = Arc::clone(&task_received); + let acknowledged = Arc::clone(&acknowledged); + tokio::spawn(async move { + let service = service_fn(|request| { + respond(request, Arc::clone(&received), Arc::clone(&acknowledged)) + }); + let _ = http1::Builder::new() + .keep_alive(false) + .serve_connection(TokioIo::new(stream), service) + .await; + }); + } + }); + Ok(Self { + port, + received, + task, + }) + } + + fn targets(&self) -> Vec { + self.received + .lock() + .unwrap() + .iter() + .map(|request| request.target.clone()) + .collect() + } + + fn bodies(&self, target: &str) -> Vec { + self.received + .lock() + .unwrap() + .iter() + .filter(|request| request.target == target) + .map(|request| request.body.clone()) + .collect() + } + + fn accept_encodings(&self, target: &str) -> Vec> { + self.received + .lock() + .unwrap() + .iter() + .filter(|request| request.target == target) + .map(|request| request.accept_encoding.clone()) + .collect() + } +} + +impl Drop for Upstream { + fn drop(&mut self) { + self.task.abort(); + } +} + +fn accepts_gzip(accept_encoding: Option<&str>) -> bool { + accept_encoding.is_some_and(|value| { + value + .split(',') + .any(|coding| coding.split(';').next().unwrap_or_default().trim() == "gzip") + }) +} + +fn gzip(data: &[u8]) -> Vec { + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(data).expect("gzip response body"); + encoder.finish().expect("finish gzip response body") +} + +async fn respond( + request: Request, + received: Received, + acknowledged: Arc, +) -> Result, Box> { + let (parts, body) = request.into_parts(); + let body = Limited::new(body, 1024 * 1024).collect().await?.to_bytes(); + let accept_encoding = parts + .headers + .get(ACCEPT_ENCODING) + .and_then(|value| value.to_str().ok()) + .map(str::to_ascii_lowercase); + let compress = accepts_gzip(accept_encoding.as_deref()); + received.lock().unwrap().push(ReceivedRequest { + target: parts + .uri + .path_and_query() + .map_or("/", |target| target.as_str()) + .to_owned(), + accept_encoding, + body: body.clone(), + }); + + let mut response = Response::builder(); + let body = match parts.uri.path() { + "/events" => { + response = response + .header(CONTENT_TYPE, "text/event-stream") + .header(CACHE_CONTROL, "no-cache"); + event_stream(acknowledged) + } + "/ack" => { + acknowledged.notify_one(); + response = response.status(StatusCode::NO_CONTENT); + Full::new(Bytes::new()).boxed_unsync() + } + "/echo" => { + response = response.header(CONTENT_TYPE, "application/octet-stream"); + Full::new(body).boxed_unsync() + } + path => { + response = response.header(CONTENT_TYPE, "text/plain"); + let body = match path { + "/compressible" if compress => { + response = response.header(CONTENT_ENCODING, "gzip"); + Bytes::from(gzip(SENSITIVE_BODY.as_bytes())) + } + "/sensitive" | "/compressible" => Bytes::from_static(SENSITIVE_BODY.as_bytes()), + _ => Bytes::from_static(CLEAN_BODY.as_bytes()), + }; + Full::new(body).boxed_unsync() + } + }; + Ok(response.body(body)?) +} + +fn event_stream(acknowledged: Arc) -> FixtureBody { + StreamBody::new(async_stream::stream! { + yield Ok(Frame::data(Bytes::from_static(b"data: one prototype-secret\n\n"))); + let second = match tokio::time::timeout(Duration::from_secs(20), acknowledged.notified()).await { + Ok(()) => &b"data: two\n\n"[..], + Err(_) => b"data: late\n\n", + }; + yield Ok(Frame::data(Bytes::from_static(second))); + }) + .boxed_unsync() +} + +struct PolicyCase<'a> { + mode: &'a str, + body_mode: &'a str, + /// Port of a `tls: skip` endpoint the attachment also selects, which the + /// gateway rejects. + tls_skip_port: Option, + /// Also attach `openshell/regex` (legacy HTTP hooks) to the same host. + mixed: bool, +} + +fn policy_yaml(registration: &str, upstream_port: u16, case: &PolicyCase<'_>) -> String { + let replacement = if case.mode == "redact" { + " replacement: \"[FILTERED]\"\n" + } else { + "" + }; + let tls_skip_endpoint = case.tls_skip_port.map_or_else(String::new, |port| { + format!(" - host: {SANDBOX_HOST}\n port: {port}\n tls: skip\n{PRIVATE_ALLOWED_IPS}\n") + }); + let regex = if case.mixed { + r#" regex-redactor: + middleware: openshell/regex + order: 20 + config: + mode: redact + endpoints: + include: ["*.openshell.internal"] +"# + } else { + "" + }; + 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: + content-guard: + name: Content guard + middleware: {registration} + order: 10 + config: + mode: {mode} + body_mode: {body_mode} + terms: + - prototype-secret + - internal-only +{replacement} on_error: fail_closed + endpoints: + include: ["{SANDBOX_HOST}"] +{regex} +network_policies: + guard_upstream: + name: guard_upstream + endpoints: + - host: {SANDBOX_HOST} + port: {upstream_port} + protocol: rest + enforcement: enforce + rules: + - allow: + method: POST + path: /echo + - allow: + method: POST + path: /ack + - allow: + method: GET + path: /sensitive + - allow: + method: GET + path: /clean + - allow: + method: GET + path: /compressible + - allow: + method: GET + path: /events +{PRIVATE_ALLOWED_IPS} +{tls_skip_endpoint} binaries: + - path: "/**" +"#, + mode = case.mode, + body_mode = case.body_mode, + ) +} + +/// Upload size larger than any `WHOLE_BODY` limit (256 KiB), so only DUPLEX can +/// carry it. +const LARGE_UPLOAD_LINES: usize = 600; + +fn workload_script(upstream_port: u16, case: &PolicyCase<'_>) -> String { + format!( + r#" +import gzip +import http.client +import json + +HOST = "{SANDBOX_HOST}" +PORT = {upstream_port} +DUPLEX = {duplex} + +def call(method, path, body=None, headers=None): + conn = http.client.HTTPConnection(HOST, PORT, timeout=60) + request_headers = {{"Content-Type": "application/octet-stream"}} if body is not None else {{}} + request_headers.update(headers or {{}}) + conn.request(method, path, body=body, headers=request_headers) + response = conn.getresponse() + data = response.read() + encoding = response.getheader("Content-Encoding", "") + if encoding == "gzip": + data = gzip.decompress(data) + conn.close() + return {{"status": response.status, "body": data.decode("latin-1"), "encoding": encoding}} + +results = {{ + "echo_term": call("POST", "/echo", b'{{"note":"prototype-secret"}}'), + "sensitive": call("GET", "/sensitive"), + "clean": call("GET", "/clean"), + "target_term": call("GET", "/clean?q=prototype-secret"), + # Ask for gzip by default, as requests, httpx, and fetch do. + "compressible": call("GET", "/compressible", headers={{"Accept-Encoding": "gzip, deflate"}}), +}} + +if DUPLEX: + upload = (b"x" * 1000 + b" prototype-secret\n") * {LARGE_UPLOAD_LINES} + echoed = call("POST", "/echo", upload) + expected = upload.replace(b"prototype-secret", b"[FILTERED]") + results["large_upload"] = {{ + "status": echoed["status"], + "sent_bytes": len(upload), + "redacted": echoed["body"].encode("latin-1") == expected, + }} + + conn = http.client.HTTPConnection(HOST, PORT, timeout=60) + conn.request("GET", "/events") + response = conn.getresponse() + first = b"" + while not first.endswith(b"\n\n"): + line = response.readline() + if not line: + break + first += line + acknowledged = call("POST", "/ack") + rest = response.read() + conn.close() + results["events"] = {{ + "status": response.status, + "first": first.decode("utf-8"), + "ack": acknowledged["status"], + "rest": rest.decode("utf-8"), + }} + +print(json.dumps(results, sort_keys=True)) +"#, + duplex = if case.body_mode == "duplex" { + "True" + } else { + "False" + }, + ) +} + +async fn run_workload( + cx: &mut Context, + registration: &str, + upstream: &Upstream, + case: &PolicyCase<'_>, +) -> testkit::Result { + let script = workload_script(upstream.port, case); + let sandbox = cx + .cli_sandbox(match (case.body_mode, case.mode) { + ("duplex", _) => "duplx", + (_, "redact") => "redct", + _ => "deny", + }) + .image(testkit::python_image()) + .policy_yaml(policy_yaml(registration, upstream.port, case)) + .command(["sleep", "infinity"]) + .create_ready() + .await?; + sandbox.run_python(&script, &[]).await?.last_json() +} + +fn assert_response(result: &Value, name: &str, status: u64, body: &str) { + assert_eq!(result[name]["status"], status, "{name}: {result}"); + assert_eq!(result[name]["body"], body, "{name}: {result}"); +} + +fn assert_platform_error(result: &Value, name: &str, status: u64, error: &str) -> Value { + assert_eq!(result[name]["status"], status, "{name}: {result}"); + let body: Value = serde_json::from_str(result[name]["body"].as_str().unwrap_or_default()) + .unwrap_or_else(|_| panic!("{name} returns a JSON error: {result}")); + assert_eq!(body["error"], error, "{name}: {body}"); + body +} + +/// The registered guard inspects and transforms HTTP traffic in both body +/// modes, and the gateway rejects policies the guard cannot enforce. +#[testkit::test] +async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor( + cx: &mut Context, +) -> testkit::Result { + const REGISTRATION_ENV: &str = "OPENSHELL_TEST_CONTENT_GUARD_REGISTRATION"; + let registration = std::env::var(REGISTRATION_ENV) + .map_err(|error| testkit::Error::msg(format!("read {REGISTRATION_ENV}: {error}")))?; + testkit::ensure!( + !registration.is_empty() + && registration + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')), + "{REGISTRATION_ENV} must be a non-empty middleware name (letters, digits, '-' or '_')" + ); + let upstream = Upstream::start().await?; + + // WHOLE_BODY redaction in both directions and a preflight rejection. + let redact = run_workload( + cx, + ®istration, + &upstream, + &PolicyCase { + mode: "redact", + body_mode: "whole_body", + tls_skip_port: None, + mixed: false, + }, + ) + .await?; + assert_response(&redact, "echo_term", 200, r#"{"note":"[FILTERED]"}"#); + assert_response( + &redact, + "sensitive", + 200, + "contains [FILTERED] and [FILTERED]", + ); + assert_response(&redact, "clean", 200, CLEAN_BODY); + // The workload asked for gzip. A response stage that may inspect bodies + // makes OpenShell ask for identity instead, so the guard can redact. + assert_response( + &redact, + "compressible", + 200, + "contains [FILTERED] and [FILTERED]", + ); + assert_eq!(redact["compressible"]["encoding"], "", "{redact}"); + let codings = upstream.accept_encodings("/compressible"); + assert!( + !codings.is_empty() + && codings + .iter() + .all(|coding| coding.as_deref() == Some("identity")), + "OpenShell asks the upstream for an identity-coded response: {codings:?}" + ); + assert!( + upstream + .bodies("/echo") + .contains(&Bytes::from_static(br#"{"note":"[FILTERED]"}"#)), + "the upstream receives the redacted body" + ); + let rejected = assert_platform_error(&redact, "target_term", 403, "middleware_denied"); + assert_eq!(rejected["reason_code"], "content_match", "{rejected}"); + assert!( + upstream + .targets() + .iter() + .all(|target| !target.contains("prototype-secret")), + "a preflight rejection never contacts the upstream" + ); + + // WHOLE_BODY denial in both directions. + let echo_bodies_before = upstream.bodies("/echo").len(); + let deny = run_workload( + cx, + ®istration, + &upstream, + &PolicyCase { + mode: "deny", + body_mode: "whole_body", + tls_skip_port: None, + mixed: false, + }, + ) + .await?; + for name in ["echo_term", "sensitive", "compressible"] { + let body = assert_platform_error(&deny, name, 403, "middleware_denied"); + assert_eq!(body["reason_code"], "content_match", "{name}: {body}"); + assert!(!body.to_string().contains("prototype-secret"), "{body}"); + } + assert_response(&deny, "clean", 200, CLEAN_BODY); + assert_eq!( + upstream.bodies("/echo").len(), + echo_bodies_before, + "a denied request body never reaches the upstream" + ); + + // DUPLEX: a large upload and server-sent events one by one. + let stream = run_workload( + cx, + ®istration, + &upstream, + &PolicyCase { + mode: "redact", + body_mode: "duplex", + tls_skip_port: None, + mixed: false, + }, + ) + .await?; + assert_response(&stream, "echo_term", 200, r#"{"note":"[FILTERED]"}"#); + assert_eq!(stream["large_upload"]["status"], 200, "{stream}"); + assert_eq!(stream["large_upload"]["redacted"], true, "{stream}"); + let large = upstream + .bodies("/echo") + .into_iter() + .max_by_key(Bytes::len) + .expect("the upstream received the large upload"); + assert!( + large.len() > 256 * 1024, + "the large upload exceeds every WHOLE_BODY limit" + ); + assert!(!String::from_utf8_lossy(&large).contains("prototype-secret")); + assert_eq!(stream["events"]["status"], 200, "{stream}"); + assert_eq!( + stream["events"]["first"], "data: one [FILTERED]\n\n", + "{stream}" + ); + assert_eq!(stream["events"]["ack"], 204, "{stream}"); + assert_eq!( + stream["events"]["rest"], "data: two\n\n", + "the first event reached the sandbox before the second was sent: {stream}" + ); + + // A policy that runs both HTTP hook versions for one destination is rejected. + let base = policy_yaml( + ®istration, + upstream.port, + &PolicyCase { + mode: "redact", + body_mode: "whole_body", + tls_skip_port: None, + mixed: false, + }, + ); + let mixed = policy_yaml( + ®istration, + upstream.port, + &PolicyCase { + mode: "redact", + body_mode: "whole_body", + tls_skip_port: None, + mixed: true, + }, + ); + let sandbox = cx + .cli_sandbox("guard") + .image(testkit::python_image()) + .policy_yaml(base) + .command(["sleep", "infinity"]) + .create_ready() + .await?; + assert_policy_rejected( + cx, + sandbox.name(), + &mixed, + "separate their endpoint selectors", + ) + .await?; + + // The guard is fail-closed and cannot inspect a `tls: skip` tunnel, so a + // policy in which it selects one is rejected. + // The rejected policy is never used to connect; it only needs a + // different endpoint port from the inspected endpoint. + let skip_port = if upstream.port == 443 { 8443 } else { 443 }; + let tls_skip = policy_yaml( + ®istration, + upstream.port, + &PolicyCase { + mode: "redact", + body_mode: "whole_body", + tls_skip_port: Some(skip_port), + mixed: false, + }, + ); + assert_policy_rejected(cx, sandbox.name(), &tls_skip, "tls: skip endpoint").await +} + +async fn assert_policy_rejected( + cx: &Context, + sandbox: &str, + policy: &str, + reason: &str, +) -> testkit::Result { + let file = YamlFile::new(policy)?; + let output = cx + .cli(["policy", "set", sandbox, "--policy", file.path()?]) + .await? + .failure() + .context("policy set should reject the middleware attachment")?; + testkit::ensure!( + output.report_text().contains(reason), + "expected policy rejection containing {reason:?}:\nstdout: {}\nstderr: {}", + output.stdout, + output.stderr + ); + Ok(()) +} diff --git a/tests/tmachine/ansible/playbooks/content-guard.yaml b/tests/tmachine/ansible/playbooks/content-guard.yaml new file mode 100644 index 0000000000..dd0b67eeda --- /dev/null +++ b/tests/tmachine/ansible/playbooks/content-guard.yaml @@ -0,0 +1,66 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +--- +- name: Run the example content-guard middleware + hosts: all + gather_facts: false + vars: + content_guard_name: content-guard-example + content_guard_port: 50881 + pre_tasks: + - name: Wait for SSH + ansible.builtin.wait_for_connection: + tasks: + - name: Install the content guard binary + become: true + ansible.builtin.copy: + src: "{{ content_guard_binary }}" + dest: /usr/local/bin/supervisor-middleware-content-guard + mode: "0755" + + - name: Install the content guard service + become: true + ansible.builtin.copy: + dest: /etc/systemd/system/openshell-test-content-guard.service + mode: "0644" + content: | + [Unit] + Description=OpenShell test content-guard middleware + [Service] + DynamicUser=yes + ExecStart=/usr/local/bin/supervisor-middleware-content-guard --bind 127.0.0.1:{{ content_guard_port }} + [Install] + WantedBy=multi-user.target + + - name: Start the content guard + become: true + ansible.builtin.systemd_service: + name: openshell-test-content-guard + daemon_reload: true + enabled: true + state: started + + - name: Wait for the content guard to listen + ansible.builtin.wait_for: + host: 127.0.0.1 + port: "{{ content_guard_port }}" + timeout: 30 + + - name: Publish middleware registration for the gateway installer + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: content-guard + gateway_overrides_content: | + [openshell.supervisor] + middleware = [ + { name = "{{ content_guard_name }}", grpc_endpoint = "http://127.0.0.1:{{ content_guard_port }}", allow_insecure_transport = true, max_payload_bytes = 262144, timeout = "2s" }, + ] + + - name: Publish the content guard registration for the suite + ansible.builtin.include_tasks: test-env.yaml + vars: + test_env_name: content-guard + test_env_vars: + OPENSHELL_TEST_CONTENT_GUARD_REGISTRATION: "{{ content_guard_name }}" diff --git a/tests/tmachine/artifacts.nix b/tests/tmachine/artifacts.nix index 2eac6909da..943c8f3cec 100644 --- a/tests/tmachine/artifacts.nix +++ b/tests/tmachine/artifacts.nix @@ -276,9 +276,22 @@ rec { name = "build-artifacts-test-archives"; runtimeInputs = [ podmanE2eArchive + pkgs.coreutils + pkgs.git + rustToolchain ]; + runtimeEnv = toolchainEnv; text = '' build-podman-e2e-test-archive + + root=$(git rev-parse --show-toplevel) + cd "$root" + cargo build --locked --target ${muslToolchain.target} \ + --target-dir "$root/target" \ + --manifest-path examples/supervisor-middleware-content-guard/Cargo.toml + install -D -m 0755 \ + target/${muslToolchain.target}/debug/supervisor-middleware-content-guard \ + artifacts/test-fixtures/${muslToolchain.target}/supervisor-middleware-content-guard ''; }; diff --git a/tests/tmachine/config.nix b/tests/tmachine/config.nix index 6d18cf6187..2e32fbc66e 100644 --- a/tests/tmachine/config.nix +++ b/tests/tmachine/config.nix @@ -101,6 +101,13 @@ let # A suite that needs a feature's setup runs in that environment, so the setup # lands in a cached layer and other suites don't carry it. features = { + middleware-http-hooks = { + bases = dockerBases; + setup = { + playbooks = [ "ansible/playbooks/content-guard.yaml" ]; + inputs.content_guard_binary = "../../artifacts/test-fixtures/${muslTarget}/supervisor-middleware-content-guard"; + }; + }; # Keycloak, for the keycloak-provider-refresh suite. keycloak = { bases = dockerBases ++ podmanBases;