From 3956699e75050023235c40b7cbdd0b807b04cfa9 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 11:51:53 -0800 Subject: [PATCH 1/3] test(conformance): port scheduling and signal mediation probes Signed-off-by: Matthew Grossman --- e2e/rust/e2e-podman.sh | 1 - tests/suites/conformance/src/lib.rs | 1 + .../conformance/src/signals_scheduling.rs | 35 +++++++++++-------- 3 files changed, 21 insertions(+), 16 deletions(-) rename e2e/rust/tests/sandbox_compat_signals_sched.rs => tests/suites/conformance/src/signals_scheduling.rs (90%) diff --git a/e2e/rust/e2e-podman.sh b/e2e/rust/e2e-podman.sh index db4c26dbe8..73a0734b68 100755 --- a/e2e/rust/e2e-podman.sh +++ b/e2e/rust/e2e-podman.sh @@ -34,7 +34,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/tests/suites/conformance/src/lib.rs b/tests/suites/conformance/src/lib.rs index e3a4726e9e..f1c8d720d7 100644 --- a/tests/suites/conformance/src/lib.rs +++ b/tests/suites/conformance/src/lib.rs @@ -27,6 +27,7 @@ mod policy_update; mod port_forward; mod process; 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(()) } From c03fa008756ed3388c6db27d188d8d4cbe29b6aa Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 11:53:22 -0800 Subject: [PATCH 2/3] test(e2e): run registered HTTP middleware hooks in testkit Signed-off-by: Matthew Grossman --- .github/workflows/e2e-suites.yml | 1 + e2e/rust/Cargo.lock | 1 - e2e/rust/Cargo.toml | 6 - e2e/with-docker-gateway.sh | 35 ++ tasks/test.toml | 5 +- tests/suites/features/Cargo.lock | 45 +++ tests/suites/features/Cargo.toml | 2 +- .../features/middleware-http-hooks/Cargo.toml | 25 ++ .../features/middleware-http-hooks/README.md | 13 + .../middleware-http-hooks/tests/http_hooks.rs | 359 +++++------------- tests/support/Cargo.lock | 7 + tests/support/Cargo.toml | 2 +- tests/support/middleware/Cargo.toml | 15 + tests/support/middleware/src/lib.rs | 22 ++ .../ansible/playbooks/content-guard.yaml | 66 ++++ tests/tmachine/artifacts.nix | 13 + tests/tmachine/config.nix | 7 + 17 files changed, 340 insertions(+), 284 deletions(-) create mode 100644 tests/suites/features/middleware-http-hooks/Cargo.toml create mode 100644 tests/suites/features/middleware-http-hooks/README.md rename e2e/rust/tests/supervisor_middleware_http_hooks.rs => tests/suites/features/middleware-http-hooks/tests/http_hooks.rs (65%) create mode 100644 tests/support/middleware/Cargo.toml create mode 100644 tests/support/middleware/src/lib.rs create mode 100644 tests/tmachine/ansible/playbooks/content-guard.yaml diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index c84837c976..b7d1b285c9 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -116,6 +116,7 @@ jobs: {"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-middleware-http-hooks","installer":"deb","family":"features","package":"middleware-http-hooks","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/e2e/rust/Cargo.lock b/e2e/rust/Cargo.lock index d4afe2b166..97c5f2af27 100644 --- a/e2e/rust/Cargo.lock +++ b/e2e/rust/Cargo.lock @@ -2415,7 +2415,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 6b0f5d5d1e..db3da9c641 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -213,11 +213,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" @@ -270,7 +265,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/with-docker-gateway.sh b/e2e/with-docker-gateway.sh index 8f62245c9c..47d2de3450 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}" ] \ @@ -608,6 +616,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}" @@ -677,6 +706,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 1da2926103..93ab9ad95d 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -240,9 +240,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/features/Cargo.lock b/tests/suites/features/Cargo.lock index 04592b09f0..06c0291028 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -616,6 +616,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" @@ -976,6 +985,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" @@ -2085,6 +2104,25 @@ 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 = [ + "flate2", + "host-server-support", + "middleware-support", + "openshell-testkit", + "serde_json", + "tokio", +] + +[[package]] +name = "middleware-support" +version = "0.0.0" +dependencies = [ + "openshell-testkit", +] + [[package]] name = "miette" version = "7.6.0" @@ -2134,6 +2172,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", + "simd-adler32", ] [[package]] @@ -3544,6 +3583,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/Cargo.toml b/tests/suites/features/Cargo.toml index 7c7fe40ae7..c12c2fbce3 100644 --- a/tests/suites/features/Cargo.toml +++ b/tests/suites/features/Cargo.toml @@ -3,4 +3,4 @@ [workspace] resolver = "2" -members = ["cdi", "connect-ssh-supervision", "docker-updates", "host-gateway", "keycloak-provider-refresh", "kubernetes-updates", "oci-image", "routable-host-ip"] +members = ["cdi", "connect-ssh-supervision", "docker-updates", "host-gateway", "keycloak-provider-refresh", "kubernetes-updates", "middleware-http-hooks", "oci-image", "routable-host-ip"] 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..505b658b3e --- /dev/null +++ b/tests/suites/features/middleware-http-hooks/Cargo.toml @@ -0,0 +1,25 @@ +# 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] +flate2 = "1" +host-server-support = { path = "../../../support/host-server" } +middleware-support = { path = "../../../support/middleware" } +openshell-testkit = { path = "../../../testkit/testkit" } +serde_json = "1" +tokio = { version = "1", features = ["io-util", "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/e2e/rust/tests/supervisor_middleware_http_hooks.rs b/tests/suites/features/middleware-http-hooks/tests/http_hooks.rs similarity index 65% rename from e2e/rust/tests/supervisor_middleware_http_hooks.rs rename to tests/suites/features/middleware-http-hooks/tests/http_hooks.rs index d3f6c612b7..49a6c11536 100644 --- a/e2e/rust/tests/supervisor_middleware_http_hooks.rs +++ b/tests/suites/features/middleware-http-hooks/tests/http_hooks.rs @@ -1,19 +1,7 @@ // 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: +//! 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 @@ -25,28 +13,17 @@ //! 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 host_server_support::TEST_HOST as SANDBOX_HOST; use serde_json::Value; -use serial_test::serial; -use tempfile::NamedTempFile; +use testkit::{Context, ResultExt as _, YamlFile}; 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: @@ -55,132 +32,8 @@ const PRIVATE_ALLOWED_IPS: &str = r#" allowed_ips: - "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"); +fn main() -> std::process::ExitCode { + testkit::main() } /// One request the upstream served. @@ -422,7 +275,7 @@ struct PolicyCase<'a> { mixed: bool, } -fn write_policy(upstream_port: u16, case: &PolicyCase<'_>) -> NamedTempFile { +fn policy_yaml(registration: &str, upstream_port: u16, case: &PolicyCase<'_>) -> String { let replacement = if case.mode == "redact" { " replacement: \"[FILTERED]\"\n" } else { @@ -443,7 +296,7 @@ fn write_policy(upstream_port: u16, case: &PolicyCase<'_>) -> NamedTempFile { } else { "" }; - let policy = format!( + format!( r#"version: 1 filesystem_policy: @@ -471,7 +324,7 @@ process: network_middlewares: content-guard: name: Content guard - middleware: {REGISTRATION} + middleware: {registration} order: 10 config: mode: {mode} @@ -516,11 +369,7 @@ network_policies: "#, 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 @@ -599,22 +448,25 @@ print(json.dumps(results, sort_keys=True)) ) } -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"); +async fn run_workload( + cx: &mut Context, + registration: &str, + upstream: &Upstream, + case: &PolicyCase<'_>, +) -> testkit::Result { 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 + 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) { @@ -630,44 +482,19 @@ fn assert_platform_error(result: &Value, name: &str, status: u64, error: &str) - 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; +/// 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 { + let registration = middleware_support::content_guard_registration()?; 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( + cx, + ®istration, &upstream, &PolicyCase { mode: "redact", @@ -676,7 +503,7 @@ async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor() { mixed: false, }, ) - .await; + .await?; assert_response(&redact, "echo_term", 200, r#"{"note":"[FILTERED]"}"#); assert_response( &redact, @@ -721,6 +548,8 @@ async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor() { // WHOLE_BODY denial in both directions. let echo_bodies_before = upstream.bodies("/echo").len(); let deny = run_workload( + cx, + ®istration, &upstream, &PolicyCase { mode: "deny", @@ -729,7 +558,7 @@ async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor() { mixed: false, }, ) - .await; + .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}"); @@ -744,6 +573,8 @@ async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor() { // DUPLEX: a large upload and server-sent events one by one. let stream = run_workload( + cx, + ®istration, &upstream, &PolicyCase { mode: "redact", @@ -752,7 +583,7 @@ async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor() { mixed: false, }, ) - .await; + .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}"); @@ -778,7 +609,8 @@ async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor() { ); // A policy that runs both HTTP hook versions for one destination is rejected. - let base = write_policy( + let base = policy_yaml( + ®istration, upstream.port, &PolicyCase { mode: "redact", @@ -787,7 +619,8 @@ async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor() { mixed: false, }, ); - let mixed = write_policy( + let mixed = policy_yaml( + ®istration, upstream.port, &PolicyCase { mode: "redact", @@ -796,74 +629,56 @@ async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor() { 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", + 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 - .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}" - ); + .await?; // 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( + // 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(find_free_port()), + tls_skip_port: Some(skip_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; + assert_policy_rejected(cx, sandbox.name(), &tls_skip, "tls: skip endpoint").await +} - registration.restore().await; - drop(guard); +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/support/Cargo.lock b/tests/support/Cargo.lock index 4de10e2dd6..6b9dcb9d85 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -2041,6 +2041,13 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "middleware-support" +version = "0.0.0" +dependencies = [ + "openshell-testkit", +] + [[package]] name = "miette" version = "7.6.0" diff --git a/tests/support/Cargo.toml b/tests/support/Cargo.toml index e3dae4234d..8dde848059 100644 --- a/tests/support/Cargo.toml +++ b/tests/support/Cargo.toml @@ -5,4 +5,4 @@ # environment runs. Suites depend on them by path. [workspace] resolver = "2" -members = ["container-engine", "host-server", "keycloak", "podman", "sandbox-clients"] +members = ["container-engine", "host-server", "keycloak", "middleware", "podman", "sandbox-clients"] diff --git a/tests/support/middleware/Cargo.toml b/tests/support/middleware/Cargo.toml new file mode 100644 index 0000000000..cb37af8d58 --- /dev/null +++ b/tests/support/middleware/Cargo.toml @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "middleware-support" +description = "Test environment contract for registered middleware services" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/ai-openshell/openshell" +publish = false + +[dependencies] +openshell-testkit = { path = "../../testkit/testkit" } diff --git a/tests/support/middleware/src/lib.rs b/tests/support/middleware/src/lib.rs new file mode 100644 index 0000000000..582540c116 --- /dev/null +++ b/tests/support/middleware/src/lib.rs @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The environment starts the content-guard example and registers it before +//! the gateway starts. Suites refer to that registration in their policies. + +/// Read `OPENSHELL_TEST_CONTENT_GUARD_REGISTRATION`, the gateway registration +/// name for the example. Missing or invalid configuration fails the test. +pub fn content_guard_registration() -> testkit::Result { + const VAR: &str = "OPENSHELL_TEST_CONTENT_GUARD_REGISTRATION"; + let name = std::env::var(VAR).map_err(|error| { + testkit::Error::msg(format!("read the registration from {VAR}: {error}")) + })?; + testkit::ensure!( + !name.is_empty() + && name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')), + "{VAR} must be a non-empty middleware name (letters, digits, '-' or '_')" + ); + Ok(name) +} 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 d8b743b803..17008ad843 100644 --- a/tests/tmachine/artifacts.nix +++ b/tests/tmachine/artifacts.nix @@ -274,9 +274,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 ed62c23eb6..faee08edc4 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; From 43e8daa96ccd43a9daa4839ec6194d2b48b9fbad Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 30 Nov 2026 15:55:01 -0800 Subject: [PATCH 3/3] refactor(e2e): simplify the HTTP hooks test fixture Signed-off-by: Matthew Grossman --- tests/suites/features/Cargo.lock | 12 +- .../features/middleware-http-hooks/Cargo.toml | 7 +- .../middleware-http-hooks/tests/http_hooks.rs | 236 ++++++++---------- tests/support/Cargo.lock | 7 - tests/support/Cargo.toml | 2 +- tests/support/middleware/Cargo.toml | 15 -- tests/support/middleware/src/lib.rs | 22 -- 7 files changed, 111 insertions(+), 190 deletions(-) delete mode 100644 tests/support/middleware/Cargo.toml delete mode 100644 tests/support/middleware/src/lib.rs diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index bf4f7c3306..c902612973 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -2153,21 +2153,17 @@ checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" name = "middleware-http-hooks" version = "0.0.0" dependencies = [ + "async-stream", "flate2", "host-server-support", - "middleware-support", + "http-body-util", + "hyper", + "hyper-util", "openshell-testkit", "serde_json", "tokio", ] -[[package]] -name = "middleware-support" -version = "0.0.0" -dependencies = [ - "openshell-testkit", -] - [[package]] name = "miette" version = "7.6.0" diff --git a/tests/suites/features/middleware-http-hooks/Cargo.toml b/tests/suites/features/middleware-http-hooks/Cargo.toml index 505b658b3e..c941e5e7ff 100644 --- a/tests/suites/features/middleware-http-hooks/Cargo.toml +++ b/tests/suites/features/middleware-http-hooks/Cargo.toml @@ -17,9 +17,12 @@ path = "tests/http_hooks.rs" harness = false [dependencies] +async-stream = "0.3" flate2 = "1" host-server-support = { path = "../../../support/host-server" } -middleware-support = { path = "../../../support/middleware" } +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 = ["io-util", "net", "rt", "sync", "time"] } +tokio = { version = "1", features = ["net", "rt", "sync", "time"] } diff --git a/tests/suites/features/middleware-http-hooks/tests/http_hooks.rs b/tests/suites/features/middleware-http-hooks/tests/http_hooks.rs index 49a6c11536..2ea6d3c862 100644 --- a/tests/suites/features/middleware-http-hooks/tests/http_hooks.rs +++ b/tests/suites/features/middleware-http-hooks/tests/http_hooks.rs @@ -12,15 +12,22 @@ //! - 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::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; -use tokio::net::{TcpListener, TcpStream}; +use tokio::net::TcpListener; use tokio::sync::Notify; use tokio::task::JoinHandle; @@ -40,10 +47,11 @@ fn main() -> std::process::ExitCode { struct ReceivedRequest { target: String, accept_encoding: Option, - body: Vec, + 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. @@ -62,28 +70,38 @@ struct Upstream { } impl Upstream { - async fn start() -> Self { + async fn start() -> testkit::Result { let listener = TcpListener::bind(("0.0.0.0", 0)) .await - .expect("bind upstream"); - let port = listener.local_addr().expect("upstream address").port(); + .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 _ = serve_one(stream, received, acknowledged).await; + 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; }); } }); - Self { + Ok(Self { port, received, task, - } + }) } fn targets(&self) -> Vec { @@ -95,7 +113,7 @@ impl Upstream { .collect() } - fn bodies(&self, target: &str) -> Vec> { + fn bodies(&self, target: &str) -> Vec { self.received .lock() .unwrap() @@ -122,72 +140,6 @@ impl Drop for Upstream { } } -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 @@ -202,67 +154,72 @@ fn gzip(data: &[u8]) -> Vec { encoder.finish().expect("finish gzip response body") } -async fn serve_one( - stream: TcpStream, +async fn respond( + request: Request, 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", +) -> 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()), }; - 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) + Full::new(body).boxed_unsync() + } }; - 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 + Ok(response.body(body)?) } -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 +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> { @@ -488,8 +445,17 @@ fn assert_platform_error(result: &Value, name: &str, status: u64, error: &str) - async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor( cx: &mut Context, ) -> testkit::Result { - let registration = middleware_support::content_guard_registration()?; - let upstream = Upstream::start().await; + 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( @@ -532,7 +498,7 @@ async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor( assert!( upstream .bodies("/echo") - .contains(&br#"{"note":"[FILTERED]"}"#.to_vec()), + .contains(&Bytes::from_static(br#"{"note":"[FILTERED]"}"#)), "the upstream receives the redacted body" ); let rejected = assert_platform_error(&redact, "target_term", 403, "middleware_denied"); @@ -590,7 +556,7 @@ async fn http_hook_content_guard_runs_against_the_gateway_and_supervisor( let large = upstream .bodies("/echo") .into_iter() - .max_by_key(Vec::len) + .max_by_key(Bytes::len) .expect("the upstream received the large upload"); assert!( large.len() > 256 * 1024, diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 1026498882..b8fef4d8b7 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -2086,13 +2086,6 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" -[[package]] -name = "middleware-support" -version = "0.0.0" -dependencies = [ - "openshell-testkit", -] - [[package]] name = "miette" version = "7.6.0" diff --git a/tests/support/Cargo.toml b/tests/support/Cargo.toml index 8dde848059..e3dae4234d 100644 --- a/tests/support/Cargo.toml +++ b/tests/support/Cargo.toml @@ -5,4 +5,4 @@ # environment runs. Suites depend on them by path. [workspace] resolver = "2" -members = ["container-engine", "host-server", "keycloak", "middleware", "podman", "sandbox-clients"] +members = ["container-engine", "host-server", "keycloak", "podman", "sandbox-clients"] diff --git a/tests/support/middleware/Cargo.toml b/tests/support/middleware/Cargo.toml deleted file mode 100644 index cb37af8d58..0000000000 --- a/tests/support/middleware/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -[package] -name = "middleware-support" -description = "Test environment contract for registered middleware services" -version = "0.0.0" -edition = "2024" -rust-version = "1.94" -license = "Apache-2.0" -repository = "https://github.com/ai-openshell/openshell" -publish = false - -[dependencies] -openshell-testkit = { path = "../../testkit/testkit" } diff --git a/tests/support/middleware/src/lib.rs b/tests/support/middleware/src/lib.rs deleted file mode 100644 index 582540c116..0000000000 --- a/tests/support/middleware/src/lib.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! The environment starts the content-guard example and registers it before -//! the gateway starts. Suites refer to that registration in their policies. - -/// Read `OPENSHELL_TEST_CONTENT_GUARD_REGISTRATION`, the gateway registration -/// name for the example. Missing or invalid configuration fails the test. -pub fn content_guard_registration() -> testkit::Result { - const VAR: &str = "OPENSHELL_TEST_CONTENT_GUARD_REGISTRATION"; - let name = std::env::var(VAR).map_err(|error| { - testkit::Error::msg(format!("read the registration from {VAR}: {error}")) - })?; - testkit::ensure!( - !name.is_empty() - && name - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')), - "{VAR} must be a non-empty middleware name (letters, digits, '-' or '_')" - ); - Ok(name) -}