From 5f05e93686b3f5492d45a8415f5423cda65b0a30 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 11:51:53 -0800 Subject: [PATCH 1/2] 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 ef1374aa414d42a772ac336af5876b282956d924 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 11:53:22 -0800 Subject: [PATCH 2/2] 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 | 356 +++++------------- 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, 341 insertions(+), 280 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 (66%) 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 ba47285c9a..2a4bc4fa3f 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" @@ -2081,6 +2100,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" @@ -2130,6 +2168,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", + "simd-adler32", ] [[package]] @@ -3524,6 +3563,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 66% rename from e2e/rust/tests/supervisor_middleware_http_hooks.rs rename to tests/suites/features/middleware-http-hooks/tests/http_hooks.rs index d3f6c612b7..281b4d66e1 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(if case.body_mode == "duplex" { + "duplex" + } else { + case.mode + }) + .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,61 @@ 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 + 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")?; + // The CLI wraps long errors across lines. + let diagnostic = format!("{}{}", output.stdout, output.stderr); + let message = diagnostic .replace('│', " ") .split_whitespace() .collect::>() .join(" "); - assert!( - message.contains("tls: skip endpoint"), - "the rejection names the tls: skip endpoint:\n{output}" + testkit::ensure!( + message.contains(reason), + "expected policy rejection containing {reason:?}:\n{diagnostic}" ); - sandbox.cleanup().await; - - registration.restore().await; - drop(guard); + Ok(()) } diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 8ba9df07e9..2c802ffaf7 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -2036,6 +2036,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..a429be4dc2 --- /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 + become: true + ansible.builtin.copy: + dest: /etc/openshell-test/gateway-overrides.toml + mode: "0644" + 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;